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,430
Fix LSP semantic tokens algorithm
This PR primarily accomplishes two tasks: 1) Overhauls the existing LSP semantic tokens edits processing algorithm to align with [Razor's](https://github.com/dotnet/aspnetcore-tooling/blob/main/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/Semantic/Services/SemanticTokensEditsDiffer.cs) (shoutout to Ryan and the rest of the Razor team for writing the original 😄). The main change here is going from calculating edits per token (i.e. five ints) to per int. The updated algorithm is much more efficient than our previous algorithm, and returns less edits back to the LSP client. 2) The interpretation of Roslyn's LongestCommonSubstring algorithm, which we use to calculate raw edits, was missing a critical piece. Namely, for insertions, we need to keep track of _where_ we should be inserting into the original token set. We don't keep track of this in the existing implementation, resulting in bugs such as #54671. Resolves #54671
allisonchou
2021-08-05T06:06:43Z
2021-08-06T23:44:44Z
b9200d03a76c74d404040d44b9bbe12b1d0a8ef2
f300a818940ea1acef66c946cfa83756729d5e59
Fix LSP semantic tokens algorithm. This PR primarily accomplishes two tasks: 1) Overhauls the existing LSP semantic tokens edits processing algorithm to align with [Razor's](https://github.com/dotnet/aspnetcore-tooling/blob/main/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/Semantic/Services/SemanticTokensEditsDiffer.cs) (shoutout to Ryan and the rest of the Razor team for writing the original 😄). The main change here is going from calculating edits per token (i.e. five ints) to per int. The updated algorithm is much more efficient than our previous algorithm, and returns less edits back to the LSP client. 2) The interpretation of Roslyn's LongestCommonSubstring algorithm, which we use to calculate raw edits, was missing a critical piece. Namely, for insertions, we need to keep track of _where_ we should be inserting into the original token set. We don't keep track of this in the existing implementation, resulting in bugs such as #54671. Resolves #54671
./src/Scripting/Core/ScriptOptions.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.Reflection; using System.Text; using System.Threading; using Microsoft.CodeAnalysis.Scripting.Hosting; namespace Microsoft.CodeAnalysis.Scripting { using static ParameterValidationHelpers; /// <summary> /// Options for creating and running scripts. /// </summary> public sealed class ScriptOptions { public static ScriptOptions Default { get; } = new ScriptOptions( filePath: string.Empty, references: GetDefaultMetadataReferences(), namespaces: ImmutableArray<string>.Empty, metadataResolver: ScriptMetadataResolver.Default, sourceResolver: SourceFileResolver.Default, emitDebugInformation: false, fileEncoding: null, OptimizationLevel.Debug, checkOverflow: false, allowUnsafe: true, warningLevel: 4, parseOptions: null); private static ImmutableArray<MetadataReference> GetDefaultMetadataReferences() { if (GacFileResolver.IsAvailable) { return ImmutableArray<MetadataReference>.Empty; } // These references are resolved lazily. Keep in sync with list in core csi.rsp. var files = new[] { "System.Collections", "System.Collections.Concurrent", "System.Console", "System.Diagnostics.Debug", "System.Diagnostics.Process", "System.Diagnostics.StackTrace", "System.Globalization", "System.IO", "System.IO.FileSystem", "System.IO.FileSystem.Primitives", "System.Reflection", "System.Reflection.Extensions", "System.Reflection.Primitives", "System.Runtime", "System.Runtime.Extensions", "System.Runtime.InteropServices", "System.Text.Encoding", "System.Text.Encoding.CodePages", "System.Text.Encoding.Extensions", "System.Text.RegularExpressions", "System.Threading", "System.Threading.Tasks", "System.Threading.Tasks.Parallel", "System.Threading.Thread", "System.ValueTuple", }; return ImmutableArray.CreateRange(files.Select(CreateUnresolvedReference)); } /// <summary> /// An array of <see cref="MetadataReference"/>s to be added to the script. /// </summary> /// <remarks> /// The array may contain both resolved and unresolved references (<see cref="UnresolvedMetadataReference"/>). /// Unresolved references are resolved when the script is about to be executed /// (<see cref="Script.RunAsync(object, CancellationToken)"/>. /// Any resolution errors are reported at that point through <see cref="CompilationErrorException"/>. /// </remarks> public ImmutableArray<MetadataReference> MetadataReferences { get; private set; } /// <summary> /// <see cref="MetadataReferenceResolver"/> to be used to resolve missing dependencies, unresolved metadata references and #r directives. /// </summary> public MetadataReferenceResolver MetadataResolver { get; private set; } /// <summary> /// <see cref="SourceReferenceResolver"/> to be used to resolve source of scripts referenced via #load directive. /// </summary> public SourceReferenceResolver SourceResolver { get; private set; } /// <summary> /// The namespaces, static classes and aliases imported by the script. /// </summary> public ImmutableArray<string> Imports { get; private set; } /// <summary> /// Specifies whether debugging symbols should be emitted. /// </summary> public bool EmitDebugInformation { get; private set; } = false; /// <summary> /// Specifies the encoding to be used when debugging scripts loaded from a file, or saved to a file for debugging purposes. /// If it's null, the compiler will attempt to detect the necessary encoding for debugging /// </summary> public Encoding FileEncoding { get; private set; } /// <summary> /// The path to the script source if it originated from a file, empty otherwise. /// </summary> public string FilePath { get; private set; } /// <summary> /// Specifies whether or not optimizations should be performed on the output IL. /// </summary> public OptimizationLevel OptimizationLevel { get; private set; } /// <summary> /// Whether bounds checking on integer arithmetic is enforced by default or not. /// </summary> public bool CheckOverflow { get; private set; } /// <summary> /// Allow unsafe regions (i.e. unsafe modifiers on members and unsafe blocks). /// </summary> public bool AllowUnsafe { get; private set; } /// <summary> /// Global warning level (from 0 to 4). /// </summary> public int WarningLevel { get; private set; } internal ParseOptions ParseOptions { get; private set; } internal ScriptOptions( string filePath, ImmutableArray<MetadataReference> references, ImmutableArray<string> namespaces, MetadataReferenceResolver metadataResolver, SourceReferenceResolver sourceResolver, bool emitDebugInformation, Encoding fileEncoding, OptimizationLevel optimizationLevel, bool checkOverflow, bool allowUnsafe, int warningLevel, ParseOptions parseOptions) { Debug.Assert(filePath != null); Debug.Assert(!references.IsDefault); Debug.Assert(!namespaces.IsDefault); Debug.Assert(metadataResolver != null); Debug.Assert(sourceResolver != null); FilePath = filePath; MetadataReferences = references; Imports = namespaces; MetadataResolver = metadataResolver; SourceResolver = sourceResolver; EmitDebugInformation = emitDebugInformation; FileEncoding = fileEncoding; OptimizationLevel = optimizationLevel; CheckOverflow = checkOverflow; AllowUnsafe = allowUnsafe; WarningLevel = warningLevel; ParseOptions = parseOptions; } private ScriptOptions(ScriptOptions other) : this(filePath: other.FilePath, references: other.MetadataReferences, namespaces: other.Imports, metadataResolver: other.MetadataResolver, sourceResolver: other.SourceResolver, emitDebugInformation: other.EmitDebugInformation, fileEncoding: other.FileEncoding, optimizationLevel: other.OptimizationLevel, checkOverflow: other.CheckOverflow, allowUnsafe: other.AllowUnsafe, warningLevel: other.WarningLevel, parseOptions: other.ParseOptions) { } // a reference to an assembly should by default be equivalent to #r, which applies recursive global alias: private static readonly MetadataReferenceProperties s_assemblyReferenceProperties = MetadataReferenceProperties.Assembly.WithRecursiveAliases(true); /// <summary> /// Creates a new <see cref="ScriptOptions"/> with the <see cref="FilePath"/> changed. /// </summary> public ScriptOptions WithFilePath(string filePath) => (FilePath == filePath) ? this : new ScriptOptions(this) { FilePath = filePath ?? "" }; private static MetadataReference CreateUnresolvedReference(string reference) => new UnresolvedMetadataReference(reference, s_assemblyReferenceProperties); /// <summary> /// Creates a new <see cref="ScriptOptions"/> with the references changed. /// </summary> /// <exception cref="ArgumentNullException"><paramref name="references"/> is null or contains a null reference.</exception> private ScriptOptions WithReferences(ImmutableArray<MetadataReference> references) => MetadataReferences.Equals(references) ? this : new ScriptOptions(this) { MetadataReferences = CheckImmutableArray(references, nameof(references)) }; /// <summary> /// Creates a new <see cref="ScriptOptions"/> with the references changed. /// </summary> /// <exception cref="ArgumentNullException"><paramref name="references"/> is null or contains a null reference.</exception> public ScriptOptions WithReferences(IEnumerable<MetadataReference> references) => WithReferences(ToImmutableArrayChecked(references, nameof(references))); /// <summary> /// Creates a new <see cref="ScriptOptions"/> with the references changed. /// </summary> /// <exception cref="ArgumentNullException"><paramref name="references"/> is null or contains a null reference.</exception> public ScriptOptions WithReferences(params MetadataReference[] references) => WithReferences((IEnumerable<MetadataReference>)references); /// <summary> /// Creates a new <see cref="ScriptOptions"/> with references added. /// </summary> /// <exception cref="ArgumentNullException"><paramref name="references"/> is null or contains a null reference.</exception> public ScriptOptions AddReferences(IEnumerable<MetadataReference> references) => WithReferences(ConcatChecked(MetadataReferences, references, nameof(references))); /// <summary> /// Creates a new <see cref="ScriptOptions"/> with references added. /// </summary> public ScriptOptions AddReferences(params MetadataReference[] references) => AddReferences((IEnumerable<MetadataReference>)references); /// <summary> /// Creates a new <see cref="ScriptOptions"/> with the references changed. /// </summary> /// <exception cref="ArgumentNullException"><paramref name="references"/> is null or contains a null reference.</exception> /// <exception cref="NotSupportedException">Specified assembly is not supported (e.g. it's a dynamic assembly).</exception> public ScriptOptions WithReferences(IEnumerable<Assembly> references) => WithReferences(SelectChecked(references, nameof(references), CreateReferenceFromAssembly)); /// <summary> /// Creates a new <see cref="ScriptOptions"/> with the references changed. /// </summary> /// <exception cref="ArgumentNullException"><paramref name="references"/> is null or contains a null reference.</exception> /// <exception cref="NotSupportedException">Specified assembly is not supported (e.g. it's a dynamic assembly).</exception> public ScriptOptions WithReferences(params Assembly[] references) => WithReferences((IEnumerable<Assembly>)references); /// <summary> /// Creates a new <see cref="ScriptOptions"/> with references added. /// </summary> /// <exception cref="ArgumentNullException"><paramref name="references"/> is null or contains a null reference.</exception> /// <exception cref="NotSupportedException">Specified assembly is not supported (e.g. it's a dynamic assembly).</exception> public ScriptOptions AddReferences(IEnumerable<Assembly> references) => AddReferences(SelectChecked(references, nameof(references), CreateReferenceFromAssembly)); private static MetadataReference CreateReferenceFromAssembly(Assembly assembly) { return MetadataReference.CreateFromAssemblyInternal(assembly, s_assemblyReferenceProperties); } /// <summary> /// Creates a new <see cref="ScriptOptions"/> with references added. /// </summary> /// <exception cref="ArgumentNullException"><paramref name="references"/> is null or contains a null reference.</exception> /// <exception cref="NotSupportedException">Specified assembly is not supported (e.g. it's a dynamic assembly).</exception> public ScriptOptions AddReferences(params Assembly[] references) => AddReferences((IEnumerable<Assembly>)references); /// <summary> /// Creates a new <see cref="ScriptOptions"/> with the references changed. /// </summary> /// <exception cref="ArgumentNullException"><paramref name="references"/> is null or contains a null reference.</exception> public ScriptOptions WithReferences(IEnumerable<string> references) => WithReferences(SelectChecked(references, nameof(references), CreateUnresolvedReference)); /// <summary> /// Creates a new <see cref="ScriptOptions"/> with the references changed. /// </summary> /// <exception cref="ArgumentNullException"><paramref name="references"/> is null or contains a null reference.</exception> public ScriptOptions WithReferences(params string[] references) => WithReferences((IEnumerable<string>)references); /// <summary> /// Creates a new <see cref="ScriptOptions"/> with references added. /// </summary> /// <exception cref="ArgumentNullException"><paramref name="references"/> is null or contains a null reference.</exception> public ScriptOptions AddReferences(IEnumerable<string> references) => AddReferences(SelectChecked(references, nameof(references), CreateUnresolvedReference)); /// <summary> /// Creates a new <see cref="ScriptOptions"/> with references added. /// </summary> public ScriptOptions AddReferences(params string[] references) => AddReferences((IEnumerable<string>)references); /// <summary> /// Creates a new <see cref="ScriptOptions"/> with specified <see cref="MetadataResolver"/>. /// </summary> public ScriptOptions WithMetadataResolver(MetadataReferenceResolver resolver) => MetadataResolver == resolver ? this : new ScriptOptions(this) { MetadataResolver = resolver }; /// <summary> /// Creates a new <see cref="ScriptOptions"/> with specified <see cref="SourceResolver"/>. /// </summary> public ScriptOptions WithSourceResolver(SourceReferenceResolver resolver) => SourceResolver == resolver ? this : new ScriptOptions(this) { SourceResolver = resolver }; /// <summary> /// Creates a new <see cref="ScriptOptions"/> with the <see cref="Imports"/> changed. /// </summary> /// <exception cref="ArgumentNullException"><paramref name="imports"/> is null or contains a null reference.</exception> private ScriptOptions WithImports(ImmutableArray<string> imports) => Imports.Equals(imports) ? this : new ScriptOptions(this) { Imports = CheckImmutableArray(imports, nameof(imports)) }; /// <summary> /// Creates a new <see cref="ScriptOptions"/> with the <see cref="Imports"/> changed. /// </summary> /// <exception cref="ArgumentNullException"><paramref name="imports"/> is null or contains a null reference.</exception> public ScriptOptions WithImports(IEnumerable<string> imports) => WithImports(ToImmutableArrayChecked(imports, nameof(imports))); /// <summary> /// Creates a new <see cref="ScriptOptions"/> with the <see cref="Imports"/> changed. /// </summary> /// <exception cref="ArgumentNullException"><paramref name="imports"/> is null or contains a null reference.</exception> public ScriptOptions WithImports(params string[] imports) => WithImports((IEnumerable<string>)imports); /// <summary> /// Creates a new <see cref="ScriptOptions"/> with <see cref="Imports"/> added. /// </summary> /// <exception cref="ArgumentNullException"><paramref name="imports"/> is null or contains a null reference.</exception> public ScriptOptions AddImports(IEnumerable<string> imports) => WithImports(ConcatChecked(Imports, imports, nameof(imports))); /// <summary> /// Creates a new <see cref="ScriptOptions"/> with <see cref="Imports"/> added. /// </summary> /// <exception cref="ArgumentNullException"><paramref name="imports"/> is null or contains a null reference.</exception> public ScriptOptions AddImports(params string[] imports) => AddImports((IEnumerable<string>)imports); /// <summary> /// Creates a new <see cref="ScriptOptions"/> with debugging information enabled. /// </summary> public ScriptOptions WithEmitDebugInformation(bool emitDebugInformation) => emitDebugInformation == EmitDebugInformation ? this : new ScriptOptions(this) { EmitDebugInformation = emitDebugInformation }; /// <summary> /// Creates a new <see cref="ScriptOptions"/> with specified <see cref="FileEncoding"/>. /// </summary> public ScriptOptions WithFileEncoding(Encoding encoding) => encoding == FileEncoding ? this : new ScriptOptions(this) { FileEncoding = encoding }; /// <summary> /// Create a new <see cref="ScriptOptions"/> with the specified <see cref="OptimizationLevel"/>. /// </summary> /// <returns></returns> public ScriptOptions WithOptimizationLevel(OptimizationLevel optimizationLevel) => optimizationLevel == OptimizationLevel ? this : new ScriptOptions(this) { OptimizationLevel = optimizationLevel }; /// <summary> /// Create a new <see cref="ScriptOptions"/> with unsafe code regions allowed. /// </summary> public ScriptOptions WithAllowUnsafe(bool allowUnsafe) => allowUnsafe == AllowUnsafe ? this : new ScriptOptions(this) { AllowUnsafe = allowUnsafe }; /// <summary> /// Create a new <see cref="ScriptOptions"/> with bounds checking on integer arithmetic enforced. /// </summary> public ScriptOptions WithCheckOverflow(bool checkOverflow) => checkOverflow == CheckOverflow ? this : new ScriptOptions(this) { CheckOverflow = checkOverflow }; /// <summary> /// Create a new <see cref="ScriptOptions"/> with the specific <see cref="WarningLevel"/>. /// </summary> public ScriptOptions WithWarningLevel(int warningLevel) => warningLevel == WarningLevel ? this : new ScriptOptions(this) { WarningLevel = warningLevel }; internal ScriptOptions WithParseOptions(ParseOptions parseOptions) => parseOptions == ParseOptions ? this : new ScriptOptions(this) { ParseOptions = parseOptions }; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Linq; using System.Reflection; using System.Text; using System.Threading; using Microsoft.CodeAnalysis.Scripting.Hosting; namespace Microsoft.CodeAnalysis.Scripting { using static ParameterValidationHelpers; /// <summary> /// Options for creating and running scripts. /// </summary> public sealed class ScriptOptions { public static ScriptOptions Default { get; } = new ScriptOptions( filePath: string.Empty, references: GetDefaultMetadataReferences(), namespaces: ImmutableArray<string>.Empty, metadataResolver: ScriptMetadataResolver.Default, sourceResolver: SourceFileResolver.Default, emitDebugInformation: false, fileEncoding: null, OptimizationLevel.Debug, checkOverflow: false, allowUnsafe: true, warningLevel: 4, parseOptions: null); private static ImmutableArray<MetadataReference> GetDefaultMetadataReferences() { if (GacFileResolver.IsAvailable) { return ImmutableArray<MetadataReference>.Empty; } // These references are resolved lazily. Keep in sync with list in core csi.rsp. var files = new[] { "System.Collections", "System.Collections.Concurrent", "System.Console", "System.Diagnostics.Debug", "System.Diagnostics.Process", "System.Diagnostics.StackTrace", "System.Globalization", "System.IO", "System.IO.FileSystem", "System.IO.FileSystem.Primitives", "System.Reflection", "System.Reflection.Extensions", "System.Reflection.Primitives", "System.Runtime", "System.Runtime.Extensions", "System.Runtime.InteropServices", "System.Text.Encoding", "System.Text.Encoding.CodePages", "System.Text.Encoding.Extensions", "System.Text.RegularExpressions", "System.Threading", "System.Threading.Tasks", "System.Threading.Tasks.Parallel", "System.Threading.Thread", "System.ValueTuple", }; return ImmutableArray.CreateRange(files.Select(CreateUnresolvedReference)); } /// <summary> /// An array of <see cref="MetadataReference"/>s to be added to the script. /// </summary> /// <remarks> /// The array may contain both resolved and unresolved references (<see cref="UnresolvedMetadataReference"/>). /// Unresolved references are resolved when the script is about to be executed /// (<see cref="Script.RunAsync(object, CancellationToken)"/>. /// Any resolution errors are reported at that point through <see cref="CompilationErrorException"/>. /// </remarks> public ImmutableArray<MetadataReference> MetadataReferences { get; private set; } /// <summary> /// <see cref="MetadataReferenceResolver"/> to be used to resolve missing dependencies, unresolved metadata references and #r directives. /// </summary> public MetadataReferenceResolver MetadataResolver { get; private set; } /// <summary> /// <see cref="SourceReferenceResolver"/> to be used to resolve source of scripts referenced via #load directive. /// </summary> public SourceReferenceResolver SourceResolver { get; private set; } /// <summary> /// The namespaces, static classes and aliases imported by the script. /// </summary> public ImmutableArray<string> Imports { get; private set; } /// <summary> /// Specifies whether debugging symbols should be emitted. /// </summary> public bool EmitDebugInformation { get; private set; } = false; /// <summary> /// Specifies the encoding to be used when debugging scripts loaded from a file, or saved to a file for debugging purposes. /// If it's null, the compiler will attempt to detect the necessary encoding for debugging /// </summary> public Encoding FileEncoding { get; private set; } /// <summary> /// The path to the script source if it originated from a file, empty otherwise. /// </summary> public string FilePath { get; private set; } /// <summary> /// Specifies whether or not optimizations should be performed on the output IL. /// </summary> public OptimizationLevel OptimizationLevel { get; private set; } /// <summary> /// Whether bounds checking on integer arithmetic is enforced by default or not. /// </summary> public bool CheckOverflow { get; private set; } /// <summary> /// Allow unsafe regions (i.e. unsafe modifiers on members and unsafe blocks). /// </summary> public bool AllowUnsafe { get; private set; } /// <summary> /// Global warning level (from 0 to 4). /// </summary> public int WarningLevel { get; private set; } internal ParseOptions ParseOptions { get; private set; } internal ScriptOptions( string filePath, ImmutableArray<MetadataReference> references, ImmutableArray<string> namespaces, MetadataReferenceResolver metadataResolver, SourceReferenceResolver sourceResolver, bool emitDebugInformation, Encoding fileEncoding, OptimizationLevel optimizationLevel, bool checkOverflow, bool allowUnsafe, int warningLevel, ParseOptions parseOptions) { Debug.Assert(filePath != null); Debug.Assert(!references.IsDefault); Debug.Assert(!namespaces.IsDefault); Debug.Assert(metadataResolver != null); Debug.Assert(sourceResolver != null); FilePath = filePath; MetadataReferences = references; Imports = namespaces; MetadataResolver = metadataResolver; SourceResolver = sourceResolver; EmitDebugInformation = emitDebugInformation; FileEncoding = fileEncoding; OptimizationLevel = optimizationLevel; CheckOverflow = checkOverflow; AllowUnsafe = allowUnsafe; WarningLevel = warningLevel; ParseOptions = parseOptions; } private ScriptOptions(ScriptOptions other) : this(filePath: other.FilePath, references: other.MetadataReferences, namespaces: other.Imports, metadataResolver: other.MetadataResolver, sourceResolver: other.SourceResolver, emitDebugInformation: other.EmitDebugInformation, fileEncoding: other.FileEncoding, optimizationLevel: other.OptimizationLevel, checkOverflow: other.CheckOverflow, allowUnsafe: other.AllowUnsafe, warningLevel: other.WarningLevel, parseOptions: other.ParseOptions) { } // a reference to an assembly should by default be equivalent to #r, which applies recursive global alias: private static readonly MetadataReferenceProperties s_assemblyReferenceProperties = MetadataReferenceProperties.Assembly.WithRecursiveAliases(true); /// <summary> /// Creates a new <see cref="ScriptOptions"/> with the <see cref="FilePath"/> changed. /// </summary> public ScriptOptions WithFilePath(string filePath) => (FilePath == filePath) ? this : new ScriptOptions(this) { FilePath = filePath ?? "" }; private static MetadataReference CreateUnresolvedReference(string reference) => new UnresolvedMetadataReference(reference, s_assemblyReferenceProperties); /// <summary> /// Creates a new <see cref="ScriptOptions"/> with the references changed. /// </summary> /// <exception cref="ArgumentNullException"><paramref name="references"/> is null or contains a null reference.</exception> private ScriptOptions WithReferences(ImmutableArray<MetadataReference> references) => MetadataReferences.Equals(references) ? this : new ScriptOptions(this) { MetadataReferences = CheckImmutableArray(references, nameof(references)) }; /// <summary> /// Creates a new <see cref="ScriptOptions"/> with the references changed. /// </summary> /// <exception cref="ArgumentNullException"><paramref name="references"/> is null or contains a null reference.</exception> public ScriptOptions WithReferences(IEnumerable<MetadataReference> references) => WithReferences(ToImmutableArrayChecked(references, nameof(references))); /// <summary> /// Creates a new <see cref="ScriptOptions"/> with the references changed. /// </summary> /// <exception cref="ArgumentNullException"><paramref name="references"/> is null or contains a null reference.</exception> public ScriptOptions WithReferences(params MetadataReference[] references) => WithReferences((IEnumerable<MetadataReference>)references); /// <summary> /// Creates a new <see cref="ScriptOptions"/> with references added. /// </summary> /// <exception cref="ArgumentNullException"><paramref name="references"/> is null or contains a null reference.</exception> public ScriptOptions AddReferences(IEnumerable<MetadataReference> references) => WithReferences(ConcatChecked(MetadataReferences, references, nameof(references))); /// <summary> /// Creates a new <see cref="ScriptOptions"/> with references added. /// </summary> public ScriptOptions AddReferences(params MetadataReference[] references) => AddReferences((IEnumerable<MetadataReference>)references); /// <summary> /// Creates a new <see cref="ScriptOptions"/> with the references changed. /// </summary> /// <exception cref="ArgumentNullException"><paramref name="references"/> is null or contains a null reference.</exception> /// <exception cref="NotSupportedException">Specified assembly is not supported (e.g. it's a dynamic assembly).</exception> public ScriptOptions WithReferences(IEnumerable<Assembly> references) => WithReferences(SelectChecked(references, nameof(references), CreateReferenceFromAssembly)); /// <summary> /// Creates a new <see cref="ScriptOptions"/> with the references changed. /// </summary> /// <exception cref="ArgumentNullException"><paramref name="references"/> is null or contains a null reference.</exception> /// <exception cref="NotSupportedException">Specified assembly is not supported (e.g. it's a dynamic assembly).</exception> public ScriptOptions WithReferences(params Assembly[] references) => WithReferences((IEnumerable<Assembly>)references); /// <summary> /// Creates a new <see cref="ScriptOptions"/> with references added. /// </summary> /// <exception cref="ArgumentNullException"><paramref name="references"/> is null or contains a null reference.</exception> /// <exception cref="NotSupportedException">Specified assembly is not supported (e.g. it's a dynamic assembly).</exception> public ScriptOptions AddReferences(IEnumerable<Assembly> references) => AddReferences(SelectChecked(references, nameof(references), CreateReferenceFromAssembly)); private static MetadataReference CreateReferenceFromAssembly(Assembly assembly) { return MetadataReference.CreateFromAssemblyInternal(assembly, s_assemblyReferenceProperties); } /// <summary> /// Creates a new <see cref="ScriptOptions"/> with references added. /// </summary> /// <exception cref="ArgumentNullException"><paramref name="references"/> is null or contains a null reference.</exception> /// <exception cref="NotSupportedException">Specified assembly is not supported (e.g. it's a dynamic assembly).</exception> public ScriptOptions AddReferences(params Assembly[] references) => AddReferences((IEnumerable<Assembly>)references); /// <summary> /// Creates a new <see cref="ScriptOptions"/> with the references changed. /// </summary> /// <exception cref="ArgumentNullException"><paramref name="references"/> is null or contains a null reference.</exception> public ScriptOptions WithReferences(IEnumerable<string> references) => WithReferences(SelectChecked(references, nameof(references), CreateUnresolvedReference)); /// <summary> /// Creates a new <see cref="ScriptOptions"/> with the references changed. /// </summary> /// <exception cref="ArgumentNullException"><paramref name="references"/> is null or contains a null reference.</exception> public ScriptOptions WithReferences(params string[] references) => WithReferences((IEnumerable<string>)references); /// <summary> /// Creates a new <see cref="ScriptOptions"/> with references added. /// </summary> /// <exception cref="ArgumentNullException"><paramref name="references"/> is null or contains a null reference.</exception> public ScriptOptions AddReferences(IEnumerable<string> references) => AddReferences(SelectChecked(references, nameof(references), CreateUnresolvedReference)); /// <summary> /// Creates a new <see cref="ScriptOptions"/> with references added. /// </summary> public ScriptOptions AddReferences(params string[] references) => AddReferences((IEnumerable<string>)references); /// <summary> /// Creates a new <see cref="ScriptOptions"/> with specified <see cref="MetadataResolver"/>. /// </summary> public ScriptOptions WithMetadataResolver(MetadataReferenceResolver resolver) => MetadataResolver == resolver ? this : new ScriptOptions(this) { MetadataResolver = resolver }; /// <summary> /// Creates a new <see cref="ScriptOptions"/> with specified <see cref="SourceResolver"/>. /// </summary> public ScriptOptions WithSourceResolver(SourceReferenceResolver resolver) => SourceResolver == resolver ? this : new ScriptOptions(this) { SourceResolver = resolver }; /// <summary> /// Creates a new <see cref="ScriptOptions"/> with the <see cref="Imports"/> changed. /// </summary> /// <exception cref="ArgumentNullException"><paramref name="imports"/> is null or contains a null reference.</exception> private ScriptOptions WithImports(ImmutableArray<string> imports) => Imports.Equals(imports) ? this : new ScriptOptions(this) { Imports = CheckImmutableArray(imports, nameof(imports)) }; /// <summary> /// Creates a new <see cref="ScriptOptions"/> with the <see cref="Imports"/> changed. /// </summary> /// <exception cref="ArgumentNullException"><paramref name="imports"/> is null or contains a null reference.</exception> public ScriptOptions WithImports(IEnumerable<string> imports) => WithImports(ToImmutableArrayChecked(imports, nameof(imports))); /// <summary> /// Creates a new <see cref="ScriptOptions"/> with the <see cref="Imports"/> changed. /// </summary> /// <exception cref="ArgumentNullException"><paramref name="imports"/> is null or contains a null reference.</exception> public ScriptOptions WithImports(params string[] imports) => WithImports((IEnumerable<string>)imports); /// <summary> /// Creates a new <see cref="ScriptOptions"/> with <see cref="Imports"/> added. /// </summary> /// <exception cref="ArgumentNullException"><paramref name="imports"/> is null or contains a null reference.</exception> public ScriptOptions AddImports(IEnumerable<string> imports) => WithImports(ConcatChecked(Imports, imports, nameof(imports))); /// <summary> /// Creates a new <see cref="ScriptOptions"/> with <see cref="Imports"/> added. /// </summary> /// <exception cref="ArgumentNullException"><paramref name="imports"/> is null or contains a null reference.</exception> public ScriptOptions AddImports(params string[] imports) => AddImports((IEnumerable<string>)imports); /// <summary> /// Creates a new <see cref="ScriptOptions"/> with debugging information enabled. /// </summary> public ScriptOptions WithEmitDebugInformation(bool emitDebugInformation) => emitDebugInformation == EmitDebugInformation ? this : new ScriptOptions(this) { EmitDebugInformation = emitDebugInformation }; /// <summary> /// Creates a new <see cref="ScriptOptions"/> with specified <see cref="FileEncoding"/>. /// </summary> public ScriptOptions WithFileEncoding(Encoding encoding) => encoding == FileEncoding ? this : new ScriptOptions(this) { FileEncoding = encoding }; /// <summary> /// Create a new <see cref="ScriptOptions"/> with the specified <see cref="OptimizationLevel"/>. /// </summary> /// <returns></returns> public ScriptOptions WithOptimizationLevel(OptimizationLevel optimizationLevel) => optimizationLevel == OptimizationLevel ? this : new ScriptOptions(this) { OptimizationLevel = optimizationLevel }; /// <summary> /// Create a new <see cref="ScriptOptions"/> with unsafe code regions allowed. /// </summary> public ScriptOptions WithAllowUnsafe(bool allowUnsafe) => allowUnsafe == AllowUnsafe ? this : new ScriptOptions(this) { AllowUnsafe = allowUnsafe }; /// <summary> /// Create a new <see cref="ScriptOptions"/> with bounds checking on integer arithmetic enforced. /// </summary> public ScriptOptions WithCheckOverflow(bool checkOverflow) => checkOverflow == CheckOverflow ? this : new ScriptOptions(this) { CheckOverflow = checkOverflow }; /// <summary> /// Create a new <see cref="ScriptOptions"/> with the specific <see cref="WarningLevel"/>. /// </summary> public ScriptOptions WithWarningLevel(int warningLevel) => warningLevel == WarningLevel ? this : new ScriptOptions(this) { WarningLevel = warningLevel }; internal ScriptOptions WithParseOptions(ParseOptions parseOptions) => parseOptions == ParseOptions ? this : new ScriptOptions(this) { ParseOptions = parseOptions }; } }
-1
dotnet/roslyn
55,430
Fix LSP semantic tokens algorithm
This PR primarily accomplishes two tasks: 1) Overhauls the existing LSP semantic tokens edits processing algorithm to align with [Razor's](https://github.com/dotnet/aspnetcore-tooling/blob/main/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/Semantic/Services/SemanticTokensEditsDiffer.cs) (shoutout to Ryan and the rest of the Razor team for writing the original 😄). The main change here is going from calculating edits per token (i.e. five ints) to per int. The updated algorithm is much more efficient than our previous algorithm, and returns less edits back to the LSP client. 2) The interpretation of Roslyn's LongestCommonSubstring algorithm, which we use to calculate raw edits, was missing a critical piece. Namely, for insertions, we need to keep track of _where_ we should be inserting into the original token set. We don't keep track of this in the existing implementation, resulting in bugs such as #54671. Resolves #54671
allisonchou
2021-08-05T06:06:43Z
2021-08-06T23:44:44Z
b9200d03a76c74d404040d44b9bbe12b1d0a8ef2
f300a818940ea1acef66c946cfa83756729d5e59
Fix LSP semantic tokens algorithm. This PR primarily accomplishes two tasks: 1) Overhauls the existing LSP semantic tokens edits processing algorithm to align with [Razor's](https://github.com/dotnet/aspnetcore-tooling/blob/main/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/Semantic/Services/SemanticTokensEditsDiffer.cs) (shoutout to Ryan and the rest of the Razor team for writing the original 😄). The main change here is going from calculating edits per token (i.e. five ints) to per int. The updated algorithm is much more efficient than our previous algorithm, and returns less edits back to the LSP client. 2) The interpretation of Roslyn's LongestCommonSubstring algorithm, which we use to calculate raw edits, was missing a critical piece. Namely, for insertions, we need to keep track of _where_ we should be inserting into the original token set. We don't keep track of this in the existing implementation, resulting in bugs such as #54671. Resolves #54671
./src/Compilers/CSharp/Portable/Symbols/Source/CrefTypeParameterSymbol.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.Threading; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Symbols { /// <summary> /// Type parameters in documentation comments are complicated since they sort of act as declarations, /// rather than references. Consider the following example: /// /// <![CDATA[ /// /// <summary>See <see cref="B{U}.M(U)" />.</summary> /// class B<T> { void M(T t) { } } /// ]]> /// /// We make some key observations: /// 1) The type parameter name in the cref is not tied to the type parameter name in the type declaration. /// 2) A relationship exists between the two occurrences of "U" in the cref: they both refer to (or define) /// the same symbol. /// /// In Roslyn, we've decided on the following representation: within the (entire) scope of a cref, the names /// of all type parameters "declared" in the cref are in scope and bind to the corresponding type parameters. /// This representation has one major advantage: as long as the appropriate binder (i.e. the one that knows /// about the implicitly-declared type parameters) is used, TypeSyntaxes within the cref can be bound by /// calling BindType. In addition to eliminating the necessity for custom binding code in the batch case, /// this reduces the problem of exposing such nodes in the SemanticModel to one of ensuring that the right /// enclosing binder is chosen. That is, new code will have to be written to handle CrefSyntaxes, but the /// existing code for TypeSyntaxes should just work! /// /// In the example above, this means that, between the cref quotation marks, the name "U" binds to an /// implicitly declared type parameter, whether it is in "B{U}", "M{U}", or "M{List{U[]}}". /// /// Of course, it's not all gravy. One thing we're giving up by using this representation is the ability to /// distinguish between "declared" type parameters with the same name. Consider the following example: /// /// <![CDATA[ /// <summary>See <see cref=""A{T, T}.M(T)""/>.</summary> /// class A<T, U> /// { /// void M(T t) { } /// void M(U u) { } /// } /// ]]> /// </summary> /// /// The native compiler interprets this in the same way as it would interpret A{T1, T2}.M(T2) and unambiguously /// (i.e. without a warning) binds to A{T, U}.M(U). Since Roslyn does not distinguish between the T's, Roslyn /// reports an ambiguity warning and picks the first method. Furthermore, renaming one 'T' will rename all of /// them. /// /// This class represents such an implicitly declared type parameter. The declaring syntax is expected to be /// an IdentifierNameSyntax in the type argument list of a QualifiedNameSyntax. internal sealed class CrefTypeParameterSymbol : TypeParameterSymbol { private readonly string _name; private readonly int _ordinal; private readonly SyntaxReference _declaringSyntax; public CrefTypeParameterSymbol(string name, int ordinal, IdentifierNameSyntax declaringSyntax) { _name = name; _ordinal = ordinal; _declaringSyntax = declaringSyntax.GetReference(); } public override TypeParameterKind TypeParameterKind { get { return TypeParameterKind.Cref; } } public override string Name { get { return _name; } } public override int Ordinal { get { return _ordinal; } } internal override bool Equals(TypeSymbol t2, TypeCompareKind comparison) { if (ReferenceEquals(this, t2)) { return true; } if ((object)t2 == null) { return false; } CrefTypeParameterSymbol other = t2 as CrefTypeParameterSymbol; return (object)other != null && other._name == _name && other._ordinal == _ordinal && other._declaringSyntax.GetSyntax() == _declaringSyntax.GetSyntax(); } public override int GetHashCode() { return Hash.Combine(_name, _ordinal); } public override VarianceKind Variance { get { return VarianceKind.None; } } public override bool HasValueTypeConstraint { get { return false; } } public override bool IsValueTypeFromConstraintTypes { get { return false; } } public override bool HasReferenceTypeConstraint { get { return false; } } public override bool IsReferenceTypeFromConstraintTypes { get { return false; } } internal override bool? ReferenceTypeConstraintIsNullable { get { return false; } } public override bool HasNotNullConstraint => false; internal override bool? IsNotNullable => null; public override bool HasUnmanagedTypeConstraint { get { return false; } } public override bool HasConstructorConstraint { get { return false; } } public override Symbol ContainingSymbol { get { return null; } } public override ImmutableArray<Location> Locations { get { return ImmutableArray.Create<Location>(_declaringSyntax.GetLocation()); } } public override ImmutableArray<SyntaxReference> DeclaringSyntaxReferences { get { return ImmutableArray.Create<SyntaxReference>(_declaringSyntax); } } internal override void EnsureAllConstraintsAreResolved() { } internal override ImmutableArray<TypeWithAnnotations> GetConstraintTypes(ConsList<TypeParameterSymbol> inProgress) { return ImmutableArray<TypeWithAnnotations>.Empty; } internal override ImmutableArray<NamedTypeSymbol> GetInterfaces(ConsList<TypeParameterSymbol> inProgress) { return ImmutableArray<NamedTypeSymbol>.Empty; } internal override NamedTypeSymbol GetEffectiveBaseClass(ConsList<TypeParameterSymbol> inProgress) { // Constraints are not checked in crefs, so this should never be examined. throw ExceptionUtilities.Unreachable; } internal override TypeSymbol GetDeducedBaseType(ConsList<TypeParameterSymbol> inProgress) { // Constraints are not checked in crefs, so this should never be examined. throw ExceptionUtilities.Unreachable; } public override bool IsImplicitlyDeclared { 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. #nullable disable using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Threading; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Symbols { /// <summary> /// Type parameters in documentation comments are complicated since they sort of act as declarations, /// rather than references. Consider the following example: /// /// <![CDATA[ /// /// <summary>See <see cref="B{U}.M(U)" />.</summary> /// class B<T> { void M(T t) { } } /// ]]> /// /// We make some key observations: /// 1) The type parameter name in the cref is not tied to the type parameter name in the type declaration. /// 2) A relationship exists between the two occurrences of "U" in the cref: they both refer to (or define) /// the same symbol. /// /// In Roslyn, we've decided on the following representation: within the (entire) scope of a cref, the names /// of all type parameters "declared" in the cref are in scope and bind to the corresponding type parameters. /// This representation has one major advantage: as long as the appropriate binder (i.e. the one that knows /// about the implicitly-declared type parameters) is used, TypeSyntaxes within the cref can be bound by /// calling BindType. In addition to eliminating the necessity for custom binding code in the batch case, /// this reduces the problem of exposing such nodes in the SemanticModel to one of ensuring that the right /// enclosing binder is chosen. That is, new code will have to be written to handle CrefSyntaxes, but the /// existing code for TypeSyntaxes should just work! /// /// In the example above, this means that, between the cref quotation marks, the name "U" binds to an /// implicitly declared type parameter, whether it is in "B{U}", "M{U}", or "M{List{U[]}}". /// /// Of course, it's not all gravy. One thing we're giving up by using this representation is the ability to /// distinguish between "declared" type parameters with the same name. Consider the following example: /// /// <![CDATA[ /// <summary>See <see cref=""A{T, T}.M(T)""/>.</summary> /// class A<T, U> /// { /// void M(T t) { } /// void M(U u) { } /// } /// ]]> /// </summary> /// /// The native compiler interprets this in the same way as it would interpret A{T1, T2}.M(T2) and unambiguously /// (i.e. without a warning) binds to A{T, U}.M(U). Since Roslyn does not distinguish between the T's, Roslyn /// reports an ambiguity warning and picks the first method. Furthermore, renaming one 'T' will rename all of /// them. /// /// This class represents such an implicitly declared type parameter. The declaring syntax is expected to be /// an IdentifierNameSyntax in the type argument list of a QualifiedNameSyntax. internal sealed class CrefTypeParameterSymbol : TypeParameterSymbol { private readonly string _name; private readonly int _ordinal; private readonly SyntaxReference _declaringSyntax; public CrefTypeParameterSymbol(string name, int ordinal, IdentifierNameSyntax declaringSyntax) { _name = name; _ordinal = ordinal; _declaringSyntax = declaringSyntax.GetReference(); } public override TypeParameterKind TypeParameterKind { get { return TypeParameterKind.Cref; } } public override string Name { get { return _name; } } public override int Ordinal { get { return _ordinal; } } internal override bool Equals(TypeSymbol t2, TypeCompareKind comparison) { if (ReferenceEquals(this, t2)) { return true; } if ((object)t2 == null) { return false; } CrefTypeParameterSymbol other = t2 as CrefTypeParameterSymbol; return (object)other != null && other._name == _name && other._ordinal == _ordinal && other._declaringSyntax.GetSyntax() == _declaringSyntax.GetSyntax(); } public override int GetHashCode() { return Hash.Combine(_name, _ordinal); } public override VarianceKind Variance { get { return VarianceKind.None; } } public override bool HasValueTypeConstraint { get { return false; } } public override bool IsValueTypeFromConstraintTypes { get { return false; } } public override bool HasReferenceTypeConstraint { get { return false; } } public override bool IsReferenceTypeFromConstraintTypes { get { return false; } } internal override bool? ReferenceTypeConstraintIsNullable { get { return false; } } public override bool HasNotNullConstraint => false; internal override bool? IsNotNullable => null; public override bool HasUnmanagedTypeConstraint { get { return false; } } public override bool HasConstructorConstraint { get { return false; } } public override Symbol ContainingSymbol { get { return null; } } public override ImmutableArray<Location> Locations { get { return ImmutableArray.Create<Location>(_declaringSyntax.GetLocation()); } } public override ImmutableArray<SyntaxReference> DeclaringSyntaxReferences { get { return ImmutableArray.Create<SyntaxReference>(_declaringSyntax); } } internal override void EnsureAllConstraintsAreResolved() { } internal override ImmutableArray<TypeWithAnnotations> GetConstraintTypes(ConsList<TypeParameterSymbol> inProgress) { return ImmutableArray<TypeWithAnnotations>.Empty; } internal override ImmutableArray<NamedTypeSymbol> GetInterfaces(ConsList<TypeParameterSymbol> inProgress) { return ImmutableArray<NamedTypeSymbol>.Empty; } internal override NamedTypeSymbol GetEffectiveBaseClass(ConsList<TypeParameterSymbol> inProgress) { // Constraints are not checked in crefs, so this should never be examined. throw ExceptionUtilities.Unreachable; } internal override TypeSymbol GetDeducedBaseType(ConsList<TypeParameterSymbol> inProgress) { // Constraints are not checked in crefs, so this should never be examined. throw ExceptionUtilities.Unreachable; } public override bool IsImplicitlyDeclared { get { return false; } } } }
-1
dotnet/roslyn
55,430
Fix LSP semantic tokens algorithm
This PR primarily accomplishes two tasks: 1) Overhauls the existing LSP semantic tokens edits processing algorithm to align with [Razor's](https://github.com/dotnet/aspnetcore-tooling/blob/main/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/Semantic/Services/SemanticTokensEditsDiffer.cs) (shoutout to Ryan and the rest of the Razor team for writing the original 😄). The main change here is going from calculating edits per token (i.e. five ints) to per int. The updated algorithm is much more efficient than our previous algorithm, and returns less edits back to the LSP client. 2) The interpretation of Roslyn's LongestCommonSubstring algorithm, which we use to calculate raw edits, was missing a critical piece. Namely, for insertions, we need to keep track of _where_ we should be inserting into the original token set. We don't keep track of this in the existing implementation, resulting in bugs such as #54671. Resolves #54671
allisonchou
2021-08-05T06:06:43Z
2021-08-06T23:44:44Z
b9200d03a76c74d404040d44b9bbe12b1d0a8ef2
f300a818940ea1acef66c946cfa83756729d5e59
Fix LSP semantic tokens algorithm. This PR primarily accomplishes two tasks: 1) Overhauls the existing LSP semantic tokens edits processing algorithm to align with [Razor's](https://github.com/dotnet/aspnetcore-tooling/blob/main/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/Semantic/Services/SemanticTokensEditsDiffer.cs) (shoutout to Ryan and the rest of the Razor team for writing the original 😄). The main change here is going from calculating edits per token (i.e. five ints) to per int. The updated algorithm is much more efficient than our previous algorithm, and returns less edits back to the LSP client. 2) The interpretation of Roslyn's LongestCommonSubstring algorithm, which we use to calculate raw edits, was missing a critical piece. Namely, for insertions, we need to keep track of _where_ we should be inserting into the original token set. We don't keep track of this in the existing implementation, resulting in bugs such as #54671. Resolves #54671
./src/Compilers/Core/Portable/Syntax/SyntaxNodeOrToken.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Runtime.InteropServices; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis { /// <summary> /// A wrapper for either a syntax node (<see cref="SyntaxNode"/>) or a syntax token (<see /// cref="SyntaxToken"/>). /// </summary> /// <remarks> /// Note that we do not store the token directly, we just store enough information to reconstruct it. /// This allows us to reuse nodeOrToken as a token's parent. /// </remarks> [StructLayout(LayoutKind.Auto)] [DebuggerDisplay("{GetDebuggerDisplay(), nq}")] public readonly struct SyntaxNodeOrToken : IEquatable<SyntaxNodeOrToken> { // In a case if we are wrapping a SyntaxNode this is the SyntaxNode itself. // In a case where we are wrapping a token, this is the token's parent. private readonly SyntaxNode? _nodeOrParent; // Green node for the token. private readonly GreenNode? _token; // Used in both node and token cases. // When we have a node, _position == _nodeOrParent.Position. private readonly int _position; // Index of the token among parent's children. // This field only makes sense if this is a token. // For regular nodes it is set to -1 to distinguish from default(SyntaxToken) private readonly int _tokenIndex; internal SyntaxNodeOrToken(SyntaxNode node) : this() { Debug.Assert(!node.Green.IsList, "node cannot be a list"); _position = node.Position; _nodeOrParent = node; _tokenIndex = -1; } internal SyntaxNodeOrToken(SyntaxNode? parent, GreenNode? token, int position, int index) { Debug.Assert(parent == null || !parent.Green.IsList, "parent cannot be a list"); Debug.Assert(token != null || (parent == null && position == 0 && index == 0), "parts must form a token"); Debug.Assert(token == null || token.IsToken, "token must be a token"); Debug.Assert(index >= 0, "index must not be negative"); Debug.Assert(parent == null || token != null, "null token cannot have parent"); _position = position; _tokenIndex = index; _nodeOrParent = parent; _token = token; } internal string GetDebuggerDisplay() { return GetType().Name + " " + KindText + " " + ToString(); } private string KindText { get { if (_token != null) { return _token.KindText; } if (_nodeOrParent != null) { return _nodeOrParent.Green.KindText; } return "None"; } } /// <summary> /// An integer representing the language specific kind of the underlying node or token. /// </summary> public int RawKind => _token?.RawKind ?? _nodeOrParent?.RawKind ?? 0; /// <summary> /// The language name that this node or token is syntax of. /// </summary> public string Language { get { if (_token != null) { return _token.Language; } if (_nodeOrParent != null) { return _nodeOrParent.Language; } return string.Empty; } } /// <summary> /// Determines whether the underlying node or token represents a language construct that was actually parsed /// from source code. Missing nodes and tokens are typically generated by the parser in error scenarios to /// represent constructs that should have been present in the source code for the source code to compile /// successfully but were actually missing. /// </summary> public bool IsMissing => _token?.IsMissing ?? _nodeOrParent?.IsMissing ?? false; /// <summary> /// The node that contains the underlying node or token in its Children collection. /// </summary> public SyntaxNode? Parent => _token != null ? _nodeOrParent : _nodeOrParent?.Parent; internal GreenNode? UnderlyingNode => _token ?? _nodeOrParent?.Green; internal int Position => _position; internal GreenNode RequiredUnderlyingNode { get { Debug.Assert(UnderlyingNode is not null); return UnderlyingNode; } } /// <summary> /// Determines whether this <see cref="SyntaxNodeOrToken"/> is wrapping a token. /// </summary> public bool IsToken => !IsNode; /// <summary> /// Determines whether this <see cref="SyntaxNodeOrToken"/> is wrapping a node. /// </summary> public bool IsNode => _tokenIndex < 0; /// <summary> /// Returns the underlying token if this <see cref="SyntaxNodeOrToken"/> is wrapping a /// token. /// </summary> /// <returns> /// The underlying token if this <see cref="SyntaxNodeOrToken"/> is wrapping a token. /// </returns> public SyntaxToken AsToken() { if (_token != null) { return new SyntaxToken(_nodeOrParent, _token, this.Position, _tokenIndex); } return default(SyntaxToken); } internal bool AsToken(out SyntaxToken token) { if (IsToken) { token = AsToken()!; return true; } token = default; return false; } /// <summary> /// Returns the underlying node if this <see cref="SyntaxNodeOrToken"/> is wrapping a /// node. /// </summary> /// <returns> /// The underlying node if this <see cref="SyntaxNodeOrToken"/> is wrapping a node. /// </returns> public SyntaxNode? AsNode() { if (_token != null) { return null; } return _nodeOrParent; } internal bool AsNode([NotNullWhen(true)] out SyntaxNode? node) { if (IsNode) { node = _nodeOrParent; return node is object; } node = null; return false; } /// <summary> /// The list of child nodes and tokens of the underlying node or token. /// </summary> public ChildSyntaxList ChildNodesAndTokens() { if (AsNode(out var node)) { return node.ChildNodesAndTokens(); } return default; } /// <summary> /// The absolute span of the underlying node or token in characters, not including its leading and trailing /// trivia. /// </summary> public TextSpan Span { get { if (_token != null) { return this.AsToken().Span; } if (_nodeOrParent != null) { return _nodeOrParent.Span; } return default(TextSpan); } } /// <summary> /// Same as accessing <see cref="TextSpan.Start"/> on <see cref="Span"/>. /// </summary> /// <remarks> /// Slight performance improvement. /// </remarks> public int SpanStart { get { if (_token != null) { // PERF: Inlined "this.AsToken().SpanStart" return _position + _token.GetLeadingTriviaWidth(); } if (_nodeOrParent != null) { return _nodeOrParent.SpanStart; } return 0; //default(TextSpan).Start } } /// <summary> /// The absolute span of the underlying node or token in characters, including its leading and trailing trivia. /// </summary> public TextSpan FullSpan { get { if (_token != null) { return new TextSpan(Position, _token.FullWidth); } if (_nodeOrParent != null) { return _nodeOrParent.FullSpan; } return default(TextSpan); } } /// <summary> /// Returns the string representation of this node or token, not including its leading and trailing /// trivia. /// </summary> /// <returns> /// The string representation of this node or token, not including its leading and trailing trivia. /// </returns> /// <remarks>The length of the returned string is always the same as Span.Length</remarks> public override string ToString() { if (_token != null) { return _token.ToString(); } if (_nodeOrParent != null) { return _nodeOrParent.ToString(); } return string.Empty; } /// <summary> /// Returns the full string representation of this node or token including its leading and trailing trivia. /// </summary> /// <returns>The full string representation of this node or token including its leading and trailing /// trivia.</returns> /// <remarks>The length of the returned string is always the same as FullSpan.Length</remarks> public string ToFullString() { if (_token != null) { return _token.ToFullString(); } if (_nodeOrParent != null) { return _nodeOrParent.ToFullString(); } return string.Empty; } /// <summary> /// Writes the full text of this node or token to the specified TextWriter. /// </summary> public void WriteTo(System.IO.TextWriter writer) { if (_token != null) { _token.WriteTo(writer); } else { _nodeOrParent?.WriteTo(writer); } } /// <summary> /// Determines whether the underlying node or token has any leading trivia. /// </summary> public bool HasLeadingTrivia => this.GetLeadingTrivia().Count > 0; /// <summary> /// The list of trivia that appear before the underlying node or token in the source code and are attached to a /// token that is a descendant of the underlying node or token. /// </summary> public SyntaxTriviaList GetLeadingTrivia() { if (_token != null) { return this.AsToken().LeadingTrivia; } if (_nodeOrParent != null) { return _nodeOrParent.GetLeadingTrivia(); } return default(SyntaxTriviaList); } /// <summary> /// Determines whether the underlying node or token has any trailing trivia. /// </summary> public bool HasTrailingTrivia => this.GetTrailingTrivia().Count > 0; /// <summary> /// The list of trivia that appear after the underlying node or token in the source code and are attached to a /// token that is a descendant of the underlying node or token. /// </summary> public SyntaxTriviaList GetTrailingTrivia() { if (_token != null) { return this.AsToken().TrailingTrivia; } if (_nodeOrParent != null) { return _nodeOrParent.GetTrailingTrivia(); } return default(SyntaxTriviaList); } public SyntaxNodeOrToken WithLeadingTrivia(IEnumerable<SyntaxTrivia> trivia) { if (_token != null) { return AsToken().WithLeadingTrivia(trivia); } if (_nodeOrParent != null) { return _nodeOrParent.WithLeadingTrivia(trivia); } return this; } public SyntaxNodeOrToken WithLeadingTrivia(params SyntaxTrivia[] trivia) { return WithLeadingTrivia((IEnumerable<SyntaxTrivia>)trivia); } public SyntaxNodeOrToken WithTrailingTrivia(IEnumerable<SyntaxTrivia> trivia) { if (_token != null) { return AsToken().WithTrailingTrivia(trivia); } if (_nodeOrParent != null) { return _nodeOrParent.WithTrailingTrivia(trivia); } return this; } public SyntaxNodeOrToken WithTrailingTrivia(params SyntaxTrivia[] trivia) { return WithTrailingTrivia((IEnumerable<SyntaxTrivia>)trivia); } /// <summary> /// Determines whether the underlying node or token or any of its descendant nodes, tokens or trivia have any /// diagnostics on them. /// </summary> public bool ContainsDiagnostics { get { if (_token != null) { return _token.ContainsDiagnostics; } if (_nodeOrParent != null) { return _nodeOrParent.ContainsDiagnostics; } return false; } } /// <summary> /// Gets a list of all the diagnostics in either the sub tree that has this node as its root or /// associated with this token and its related trivia. /// This method does not filter diagnostics based on #pragmas and compiler options /// like nowarn, warnaserror etc. /// </summary> public IEnumerable<Diagnostic> GetDiagnostics() { if (_token != null) { return this.AsToken().GetDiagnostics(); } if (_nodeOrParent != null) { return _nodeOrParent.GetDiagnostics(); } return SpecializedCollections.EmptyEnumerable<Diagnostic>(); } /// <summary> /// Determines whether the underlying node or token has any descendant preprocessor directives. /// </summary> public bool ContainsDirectives { get { if (_token != null) { return _token.ContainsDirectives; } if (_nodeOrParent != null) { return _nodeOrParent.ContainsDirectives; } return false; } } #region Annotations /// <summary> /// Determines whether this node or token (or any sub node, token or trivia) as annotations. /// </summary> public bool ContainsAnnotations { get { if (_token != null) { return _token.ContainsAnnotations; } if (_nodeOrParent != null) { return _nodeOrParent.ContainsAnnotations; } return false; } } /// <summary> /// Determines whether this node or token has annotations of the specified kind. /// </summary> public bool HasAnnotations(string annotationKind) { if (_token != null) { return _token.HasAnnotations(annotationKind); } if (_nodeOrParent != null) { return _nodeOrParent.HasAnnotations(annotationKind); } return false; } /// <summary> /// Determines whether this node or token has annotations of the specified kind. /// </summary> public bool HasAnnotations(IEnumerable<string> annotationKinds) { if (_token != null) { return _token.HasAnnotations(annotationKinds); } if (_nodeOrParent != null) { return _nodeOrParent.HasAnnotations(annotationKinds); } return false; } /// <summary> /// Determines if this node or token has the specific annotation. /// </summary> public bool HasAnnotation([NotNullWhen(true)] SyntaxAnnotation? annotation) { if (_token != null) { return _token.HasAnnotation(annotation); } if (_nodeOrParent != null) { return _nodeOrParent.HasAnnotation(annotation); } return false; } /// <summary> /// Gets all annotations of the specified annotation kind. /// </summary> public IEnumerable<SyntaxAnnotation> GetAnnotations(string annotationKind) { if (_token != null) { return _token.GetAnnotations(annotationKind); } if (_nodeOrParent != null) { return _nodeOrParent.GetAnnotations(annotationKind); } return SpecializedCollections.EmptyEnumerable<SyntaxAnnotation>(); } /// <summary> /// Gets all annotations of the specified annotation kind. /// </summary> public IEnumerable<SyntaxAnnotation> GetAnnotations(IEnumerable<string> annotationKinds) { if (_token != null) { return _token.GetAnnotations(annotationKinds); } if (_nodeOrParent != null) { return _nodeOrParent.GetAnnotations(annotationKinds); } return SpecializedCollections.EmptyEnumerable<SyntaxAnnotation>(); } /// <summary> /// Creates a new node or token identical to this one with the specified annotations. /// </summary> public SyntaxNodeOrToken WithAdditionalAnnotations(params SyntaxAnnotation[] annotations) { return WithAdditionalAnnotations((IEnumerable<SyntaxAnnotation>)annotations); } /// <summary> /// Creates a new node or token identical to this one with the specified annotations. /// </summary> public SyntaxNodeOrToken WithAdditionalAnnotations(IEnumerable<SyntaxAnnotation> annotations) { if (annotations == null) { throw new ArgumentNullException(nameof(annotations)); } if (_token != null) { return this.AsToken().WithAdditionalAnnotations(annotations); } if (_nodeOrParent != null) { return _nodeOrParent.WithAdditionalAnnotations(annotations); } return this; } /// <summary> /// Creates a new node or token identical to this one without the specified annotations. /// </summary> public SyntaxNodeOrToken WithoutAnnotations(params SyntaxAnnotation[] annotations) { return WithoutAnnotations((IEnumerable<SyntaxAnnotation>)annotations); } /// <summary> /// Creates a new node or token identical to this one without the specified annotations. /// </summary> public SyntaxNodeOrToken WithoutAnnotations(IEnumerable<SyntaxAnnotation> annotations) { if (annotations == null) { throw new ArgumentNullException(nameof(annotations)); } if (_token != null) { return this.AsToken().WithoutAnnotations(annotations); } if (_nodeOrParent != null) { return _nodeOrParent.WithoutAnnotations(annotations); } return this; } /// <summary> /// Creates a new node or token identical to this one without annotations of the specified kind. /// </summary> public SyntaxNodeOrToken WithoutAnnotations(string annotationKind) { if (annotationKind == null) { throw new ArgumentNullException(nameof(annotationKind)); } if (this.HasAnnotations(annotationKind)) { return this.WithoutAnnotations(this.GetAnnotations(annotationKind)); } return this; } #endregion /// <summary> /// Determines whether the supplied <see cref="SyntaxNodeOrToken"/> is equal to this /// <see cref="SyntaxNodeOrToken"/>. /// </summary> public bool Equals(SyntaxNodeOrToken other) { // index replaces position to ensure equality. Assert if offset affects equality. Debug.Assert( (_nodeOrParent == other._nodeOrParent && _token == other._token && _position == other._position && _tokenIndex == other._tokenIndex) == (_nodeOrParent == other._nodeOrParent && _token == other._token && _tokenIndex == other._tokenIndex)); return _nodeOrParent == other._nodeOrParent && _token == other._token && _tokenIndex == other._tokenIndex; } /// <summary> /// Determines whether two <see cref="SyntaxNodeOrToken"/>s are equal. /// </summary> public static bool operator ==(SyntaxNodeOrToken left, SyntaxNodeOrToken right) { return left.Equals(right); } /// <summary> /// Determines whether two <see cref="SyntaxNodeOrToken"/>s are unequal. /// </summary> public static bool operator !=(SyntaxNodeOrToken left, SyntaxNodeOrToken right) { return !left.Equals(right); } /// <summary> /// Determines whether the supplied <see cref="SyntaxNodeOrToken"/> is equal to this /// <see cref="SyntaxNodeOrToken"/>. /// </summary> public override bool Equals(object? obj) { return obj is SyntaxNodeOrToken token && Equals(token); } /// <summary> /// Serves as hash function for <see cref="SyntaxNodeOrToken"/>. /// </summary> public override int GetHashCode() { return Hash.Combine(_nodeOrParent, Hash.Combine(_token, _tokenIndex)); } /// <summary> /// Determines if the two nodes or tokens are equivalent. /// </summary> public bool IsEquivalentTo(SyntaxNodeOrToken other) { if (this.IsNode != other.IsNode) { return false; } var thisUnderlying = this.UnderlyingNode; var otherUnderlying = other.UnderlyingNode; return (thisUnderlying == otherUnderlying) || (thisUnderlying != null && thisUnderlying.IsEquivalentTo(otherUnderlying)); } /// <summary> /// See <see cref="SyntaxNode.IsIncrementallyIdenticalTo"/> and <see cref="SyntaxToken.IsIncrementallyIdenticalTo"/>. /// </summary> public bool IsIncrementallyIdenticalTo(SyntaxNodeOrToken other) => this.UnderlyingNode != null && this.UnderlyingNode == other.UnderlyingNode; /// <summary> /// Returns a new <see cref="SyntaxNodeOrToken"/> that wraps the supplied token. /// </summary> /// <param name="token">The input token.</param> /// <returns> /// A <see cref="SyntaxNodeOrToken"/> that wraps the supplied token. /// </returns> public static implicit operator SyntaxNodeOrToken(SyntaxToken token) { return new SyntaxNodeOrToken(token.Parent, token.Node, token.Position, token.Index); } /// <summary> /// Returns the underlying token wrapped by the supplied <see cref="SyntaxNodeOrToken"/>. /// </summary> /// <param name="nodeOrToken"> /// The input <see cref="SyntaxNodeOrToken"/>. /// </param> /// <returns> /// The underlying token wrapped by the supplied <see cref="SyntaxNodeOrToken"/>. /// </returns> public static explicit operator SyntaxToken(SyntaxNodeOrToken nodeOrToken) { return nodeOrToken.AsToken(); } /// <summary> /// Returns a new <see cref="SyntaxNodeOrToken"/> that wraps the supplied node. /// </summary> /// <param name="node">The input node.</param> /// <returns> /// A <see cref="SyntaxNodeOrToken"/> that wraps the supplied node. /// </returns> public static implicit operator SyntaxNodeOrToken(SyntaxNode? node) { return node is object ? new SyntaxNodeOrToken(node) : default; } /// <summary> /// Returns the underlying node wrapped by the supplied <see cref="SyntaxNodeOrToken"/>. /// </summary> /// <param name="nodeOrToken"> /// The input <see cref="SyntaxNodeOrToken"/>. /// </param> /// <returns> /// The underlying node wrapped by the supplied <see cref="SyntaxNodeOrToken"/>. /// </returns> public static explicit operator SyntaxNode?(SyntaxNodeOrToken nodeOrToken) { return nodeOrToken.AsNode(); } /// <summary> /// SyntaxTree which contains current SyntaxNodeOrToken. /// </summary> public SyntaxTree? SyntaxTree => _nodeOrParent?.SyntaxTree; /// <summary> /// Get the location of this node or token. /// </summary> public Location? GetLocation() { if (AsToken(out var token)) { return token.GetLocation(); } return _nodeOrParent?.GetLocation(); } #region Directive Lookup // Get all directives under the node and its children in source code order. internal IList<TDirective> GetDirectives<TDirective>(Func<TDirective, bool>? filter = null) where TDirective : SyntaxNode { List<TDirective>? directives = null; GetDirectives(this, filter, ref directives); return directives ?? SpecializedCollections.EmptyList<TDirective>(); } private static void GetDirectives<TDirective>(in SyntaxNodeOrToken node, Func<TDirective, bool>? filter, ref List<TDirective>? directives) where TDirective : SyntaxNode { if (node._token != null && node.AsToken() is var token && token.ContainsDirectives) { GetDirectives(token.LeadingTrivia, filter, ref directives); GetDirectives(token.TrailingTrivia, filter, ref directives); } else if (node._nodeOrParent != null) { GetDirectives(node._nodeOrParent, filter, ref directives); } } private static void GetDirectives<TDirective>(SyntaxNode node, Func<TDirective, bool>? filter, ref List<TDirective>? directives) where TDirective : SyntaxNode { foreach (var trivia in node.DescendantTrivia(node => node.ContainsDirectives, descendIntoTrivia: true)) { _ = GetDirectivesInTrivia(trivia, filter, ref directives); } } private static bool GetDirectivesInTrivia<TDirective>(in SyntaxTrivia trivia, Func<TDirective, bool>? filter, ref List<TDirective>? directives) where TDirective : SyntaxNode { if (trivia.IsDirective) { if (trivia.GetStructure() is TDirective directive && filter?.Invoke(directive) != false) { if (directives == null) { directives = new List<TDirective>(); } directives.Add(directive); } return true; } return false; } private static void GetDirectives<TDirective>(in SyntaxTriviaList trivia, Func<TDirective, bool>? filter, ref List<TDirective>? directives) where TDirective : SyntaxNode { foreach (var tr in trivia) { if (!GetDirectivesInTrivia(tr, filter, ref directives) && tr.GetStructure() is SyntaxNode node) { GetDirectives(node, filter, ref directives); } } } #endregion internal int Width => _token?.Width ?? _nodeOrParent?.Width ?? 0; internal int FullWidth => _token?.FullWidth ?? _nodeOrParent?.FullWidth ?? 0; internal int EndPosition => _position + this.FullWidth; public static int GetFirstChildIndexSpanningPosition(SyntaxNode node, int position) { if (!node.FullSpan.IntersectsWith(position)) { throw new ArgumentException("Must be within node's FullSpan", nameof(position)); } return GetFirstChildIndexSpanningPosition(node.ChildNodesAndTokens(), position); } internal static int GetFirstChildIndexSpanningPosition(ChildSyntaxList list, int position) { int lo = 0; int hi = list.Count - 1; while (lo <= hi) { int r = lo + ((hi - lo) >> 1); var m = list[r]; if (position < m.Position) { hi = r - 1; } else { if (position == m.Position) { // If we hit a zero width node, move left to the first such node (or the // first one in the list) for (; r > 0 && list[r - 1].FullWidth == 0; r--) { ; } return r; } if (position >= m.EndPosition) { lo = r + 1; continue; } return r; } } throw ExceptionUtilities.Unreachable; } public SyntaxNodeOrToken GetNextSibling() { var parent = this.Parent; if (parent == null) { return default(SyntaxNodeOrToken); } var siblings = parent.ChildNodesAndTokens(); return siblings.Count < 8 ? GetNextSiblingFromStart(siblings) : GetNextSiblingWithSearch(siblings); } public SyntaxNodeOrToken GetPreviousSibling() { if (this.Parent != null) { // walk reverse in parent's child list until we find ourself // and then return the next child var returnNext = false; foreach (var child in this.Parent.ChildNodesAndTokens().Reverse()) { if (returnNext) { return child; } if (child == this) { returnNext = true; } } } return default(SyntaxNodeOrToken); } private SyntaxNodeOrToken GetNextSiblingFromStart(ChildSyntaxList siblings) { var returnNext = false; foreach (var sibling in siblings) { if (returnNext) { return sibling; } if (sibling == this) { returnNext = true; } } return default(SyntaxNodeOrToken); } private SyntaxNodeOrToken GetNextSiblingWithSearch(ChildSyntaxList siblings) { var firstIndex = GetFirstChildIndexSpanningPosition(siblings, _position); var count = siblings.Count; var returnNext = false; for (int i = firstIndex; i < count; i++) { if (returnNext) { return siblings[i]; } if (siblings[i] == this) { returnNext = true; } } return default(SyntaxNodeOrToken); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Runtime.InteropServices; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis { /// <summary> /// A wrapper for either a syntax node (<see cref="SyntaxNode"/>) or a syntax token (<see /// cref="SyntaxToken"/>). /// </summary> /// <remarks> /// Note that we do not store the token directly, we just store enough information to reconstruct it. /// This allows us to reuse nodeOrToken as a token's parent. /// </remarks> [StructLayout(LayoutKind.Auto)] [DebuggerDisplay("{GetDebuggerDisplay(), nq}")] public readonly struct SyntaxNodeOrToken : IEquatable<SyntaxNodeOrToken> { // In a case if we are wrapping a SyntaxNode this is the SyntaxNode itself. // In a case where we are wrapping a token, this is the token's parent. private readonly SyntaxNode? _nodeOrParent; // Green node for the token. private readonly GreenNode? _token; // Used in both node and token cases. // When we have a node, _position == _nodeOrParent.Position. private readonly int _position; // Index of the token among parent's children. // This field only makes sense if this is a token. // For regular nodes it is set to -1 to distinguish from default(SyntaxToken) private readonly int _tokenIndex; internal SyntaxNodeOrToken(SyntaxNode node) : this() { Debug.Assert(!node.Green.IsList, "node cannot be a list"); _position = node.Position; _nodeOrParent = node; _tokenIndex = -1; } internal SyntaxNodeOrToken(SyntaxNode? parent, GreenNode? token, int position, int index) { Debug.Assert(parent == null || !parent.Green.IsList, "parent cannot be a list"); Debug.Assert(token != null || (parent == null && position == 0 && index == 0), "parts must form a token"); Debug.Assert(token == null || token.IsToken, "token must be a token"); Debug.Assert(index >= 0, "index must not be negative"); Debug.Assert(parent == null || token != null, "null token cannot have parent"); _position = position; _tokenIndex = index; _nodeOrParent = parent; _token = token; } internal string GetDebuggerDisplay() { return GetType().Name + " " + KindText + " " + ToString(); } private string KindText { get { if (_token != null) { return _token.KindText; } if (_nodeOrParent != null) { return _nodeOrParent.Green.KindText; } return "None"; } } /// <summary> /// An integer representing the language specific kind of the underlying node or token. /// </summary> public int RawKind => _token?.RawKind ?? _nodeOrParent?.RawKind ?? 0; /// <summary> /// The language name that this node or token is syntax of. /// </summary> public string Language { get { if (_token != null) { return _token.Language; } if (_nodeOrParent != null) { return _nodeOrParent.Language; } return string.Empty; } } /// <summary> /// Determines whether the underlying node or token represents a language construct that was actually parsed /// from source code. Missing nodes and tokens are typically generated by the parser in error scenarios to /// represent constructs that should have been present in the source code for the source code to compile /// successfully but were actually missing. /// </summary> public bool IsMissing => _token?.IsMissing ?? _nodeOrParent?.IsMissing ?? false; /// <summary> /// The node that contains the underlying node or token in its Children collection. /// </summary> public SyntaxNode? Parent => _token != null ? _nodeOrParent : _nodeOrParent?.Parent; internal GreenNode? UnderlyingNode => _token ?? _nodeOrParent?.Green; internal int Position => _position; internal GreenNode RequiredUnderlyingNode { get { Debug.Assert(UnderlyingNode is not null); return UnderlyingNode; } } /// <summary> /// Determines whether this <see cref="SyntaxNodeOrToken"/> is wrapping a token. /// </summary> public bool IsToken => !IsNode; /// <summary> /// Determines whether this <see cref="SyntaxNodeOrToken"/> is wrapping a node. /// </summary> public bool IsNode => _tokenIndex < 0; /// <summary> /// Returns the underlying token if this <see cref="SyntaxNodeOrToken"/> is wrapping a /// token. /// </summary> /// <returns> /// The underlying token if this <see cref="SyntaxNodeOrToken"/> is wrapping a token. /// </returns> public SyntaxToken AsToken() { if (_token != null) { return new SyntaxToken(_nodeOrParent, _token, this.Position, _tokenIndex); } return default(SyntaxToken); } internal bool AsToken(out SyntaxToken token) { if (IsToken) { token = AsToken()!; return true; } token = default; return false; } /// <summary> /// Returns the underlying node if this <see cref="SyntaxNodeOrToken"/> is wrapping a /// node. /// </summary> /// <returns> /// The underlying node if this <see cref="SyntaxNodeOrToken"/> is wrapping a node. /// </returns> public SyntaxNode? AsNode() { if (_token != null) { return null; } return _nodeOrParent; } internal bool AsNode([NotNullWhen(true)] out SyntaxNode? node) { if (IsNode) { node = _nodeOrParent; return node is object; } node = null; return false; } /// <summary> /// The list of child nodes and tokens of the underlying node or token. /// </summary> public ChildSyntaxList ChildNodesAndTokens() { if (AsNode(out var node)) { return node.ChildNodesAndTokens(); } return default; } /// <summary> /// The absolute span of the underlying node or token in characters, not including its leading and trailing /// trivia. /// </summary> public TextSpan Span { get { if (_token != null) { return this.AsToken().Span; } if (_nodeOrParent != null) { return _nodeOrParent.Span; } return default(TextSpan); } } /// <summary> /// Same as accessing <see cref="TextSpan.Start"/> on <see cref="Span"/>. /// </summary> /// <remarks> /// Slight performance improvement. /// </remarks> public int SpanStart { get { if (_token != null) { // PERF: Inlined "this.AsToken().SpanStart" return _position + _token.GetLeadingTriviaWidth(); } if (_nodeOrParent != null) { return _nodeOrParent.SpanStart; } return 0; //default(TextSpan).Start } } /// <summary> /// The absolute span of the underlying node or token in characters, including its leading and trailing trivia. /// </summary> public TextSpan FullSpan { get { if (_token != null) { return new TextSpan(Position, _token.FullWidth); } if (_nodeOrParent != null) { return _nodeOrParent.FullSpan; } return default(TextSpan); } } /// <summary> /// Returns the string representation of this node or token, not including its leading and trailing /// trivia. /// </summary> /// <returns> /// The string representation of this node or token, not including its leading and trailing trivia. /// </returns> /// <remarks>The length of the returned string is always the same as Span.Length</remarks> public override string ToString() { if (_token != null) { return _token.ToString(); } if (_nodeOrParent != null) { return _nodeOrParent.ToString(); } return string.Empty; } /// <summary> /// Returns the full string representation of this node or token including its leading and trailing trivia. /// </summary> /// <returns>The full string representation of this node or token including its leading and trailing /// trivia.</returns> /// <remarks>The length of the returned string is always the same as FullSpan.Length</remarks> public string ToFullString() { if (_token != null) { return _token.ToFullString(); } if (_nodeOrParent != null) { return _nodeOrParent.ToFullString(); } return string.Empty; } /// <summary> /// Writes the full text of this node or token to the specified TextWriter. /// </summary> public void WriteTo(System.IO.TextWriter writer) { if (_token != null) { _token.WriteTo(writer); } else { _nodeOrParent?.WriteTo(writer); } } /// <summary> /// Determines whether the underlying node or token has any leading trivia. /// </summary> public bool HasLeadingTrivia => this.GetLeadingTrivia().Count > 0; /// <summary> /// The list of trivia that appear before the underlying node or token in the source code and are attached to a /// token that is a descendant of the underlying node or token. /// </summary> public SyntaxTriviaList GetLeadingTrivia() { if (_token != null) { return this.AsToken().LeadingTrivia; } if (_nodeOrParent != null) { return _nodeOrParent.GetLeadingTrivia(); } return default(SyntaxTriviaList); } /// <summary> /// Determines whether the underlying node or token has any trailing trivia. /// </summary> public bool HasTrailingTrivia => this.GetTrailingTrivia().Count > 0; /// <summary> /// The list of trivia that appear after the underlying node or token in the source code and are attached to a /// token that is a descendant of the underlying node or token. /// </summary> public SyntaxTriviaList GetTrailingTrivia() { if (_token != null) { return this.AsToken().TrailingTrivia; } if (_nodeOrParent != null) { return _nodeOrParent.GetTrailingTrivia(); } return default(SyntaxTriviaList); } public SyntaxNodeOrToken WithLeadingTrivia(IEnumerable<SyntaxTrivia> trivia) { if (_token != null) { return AsToken().WithLeadingTrivia(trivia); } if (_nodeOrParent != null) { return _nodeOrParent.WithLeadingTrivia(trivia); } return this; } public SyntaxNodeOrToken WithLeadingTrivia(params SyntaxTrivia[] trivia) { return WithLeadingTrivia((IEnumerable<SyntaxTrivia>)trivia); } public SyntaxNodeOrToken WithTrailingTrivia(IEnumerable<SyntaxTrivia> trivia) { if (_token != null) { return AsToken().WithTrailingTrivia(trivia); } if (_nodeOrParent != null) { return _nodeOrParent.WithTrailingTrivia(trivia); } return this; } public SyntaxNodeOrToken WithTrailingTrivia(params SyntaxTrivia[] trivia) { return WithTrailingTrivia((IEnumerable<SyntaxTrivia>)trivia); } /// <summary> /// Determines whether the underlying node or token or any of its descendant nodes, tokens or trivia have any /// diagnostics on them. /// </summary> public bool ContainsDiagnostics { get { if (_token != null) { return _token.ContainsDiagnostics; } if (_nodeOrParent != null) { return _nodeOrParent.ContainsDiagnostics; } return false; } } /// <summary> /// Gets a list of all the diagnostics in either the sub tree that has this node as its root or /// associated with this token and its related trivia. /// This method does not filter diagnostics based on #pragmas and compiler options /// like nowarn, warnaserror etc. /// </summary> public IEnumerable<Diagnostic> GetDiagnostics() { if (_token != null) { return this.AsToken().GetDiagnostics(); } if (_nodeOrParent != null) { return _nodeOrParent.GetDiagnostics(); } return SpecializedCollections.EmptyEnumerable<Diagnostic>(); } /// <summary> /// Determines whether the underlying node or token has any descendant preprocessor directives. /// </summary> public bool ContainsDirectives { get { if (_token != null) { return _token.ContainsDirectives; } if (_nodeOrParent != null) { return _nodeOrParent.ContainsDirectives; } return false; } } #region Annotations /// <summary> /// Determines whether this node or token (or any sub node, token or trivia) as annotations. /// </summary> public bool ContainsAnnotations { get { if (_token != null) { return _token.ContainsAnnotations; } if (_nodeOrParent != null) { return _nodeOrParent.ContainsAnnotations; } return false; } } /// <summary> /// Determines whether this node or token has annotations of the specified kind. /// </summary> public bool HasAnnotations(string annotationKind) { if (_token != null) { return _token.HasAnnotations(annotationKind); } if (_nodeOrParent != null) { return _nodeOrParent.HasAnnotations(annotationKind); } return false; } /// <summary> /// Determines whether this node or token has annotations of the specified kind. /// </summary> public bool HasAnnotations(IEnumerable<string> annotationKinds) { if (_token != null) { return _token.HasAnnotations(annotationKinds); } if (_nodeOrParent != null) { return _nodeOrParent.HasAnnotations(annotationKinds); } return false; } /// <summary> /// Determines if this node or token has the specific annotation. /// </summary> public bool HasAnnotation([NotNullWhen(true)] SyntaxAnnotation? annotation) { if (_token != null) { return _token.HasAnnotation(annotation); } if (_nodeOrParent != null) { return _nodeOrParent.HasAnnotation(annotation); } return false; } /// <summary> /// Gets all annotations of the specified annotation kind. /// </summary> public IEnumerable<SyntaxAnnotation> GetAnnotations(string annotationKind) { if (_token != null) { return _token.GetAnnotations(annotationKind); } if (_nodeOrParent != null) { return _nodeOrParent.GetAnnotations(annotationKind); } return SpecializedCollections.EmptyEnumerable<SyntaxAnnotation>(); } /// <summary> /// Gets all annotations of the specified annotation kind. /// </summary> public IEnumerable<SyntaxAnnotation> GetAnnotations(IEnumerable<string> annotationKinds) { if (_token != null) { return _token.GetAnnotations(annotationKinds); } if (_nodeOrParent != null) { return _nodeOrParent.GetAnnotations(annotationKinds); } return SpecializedCollections.EmptyEnumerable<SyntaxAnnotation>(); } /// <summary> /// Creates a new node or token identical to this one with the specified annotations. /// </summary> public SyntaxNodeOrToken WithAdditionalAnnotations(params SyntaxAnnotation[] annotations) { return WithAdditionalAnnotations((IEnumerable<SyntaxAnnotation>)annotations); } /// <summary> /// Creates a new node or token identical to this one with the specified annotations. /// </summary> public SyntaxNodeOrToken WithAdditionalAnnotations(IEnumerable<SyntaxAnnotation> annotations) { if (annotations == null) { throw new ArgumentNullException(nameof(annotations)); } if (_token != null) { return this.AsToken().WithAdditionalAnnotations(annotations); } if (_nodeOrParent != null) { return _nodeOrParent.WithAdditionalAnnotations(annotations); } return this; } /// <summary> /// Creates a new node or token identical to this one without the specified annotations. /// </summary> public SyntaxNodeOrToken WithoutAnnotations(params SyntaxAnnotation[] annotations) { return WithoutAnnotations((IEnumerable<SyntaxAnnotation>)annotations); } /// <summary> /// Creates a new node or token identical to this one without the specified annotations. /// </summary> public SyntaxNodeOrToken WithoutAnnotations(IEnumerable<SyntaxAnnotation> annotations) { if (annotations == null) { throw new ArgumentNullException(nameof(annotations)); } if (_token != null) { return this.AsToken().WithoutAnnotations(annotations); } if (_nodeOrParent != null) { return _nodeOrParent.WithoutAnnotations(annotations); } return this; } /// <summary> /// Creates a new node or token identical to this one without annotations of the specified kind. /// </summary> public SyntaxNodeOrToken WithoutAnnotations(string annotationKind) { if (annotationKind == null) { throw new ArgumentNullException(nameof(annotationKind)); } if (this.HasAnnotations(annotationKind)) { return this.WithoutAnnotations(this.GetAnnotations(annotationKind)); } return this; } #endregion /// <summary> /// Determines whether the supplied <see cref="SyntaxNodeOrToken"/> is equal to this /// <see cref="SyntaxNodeOrToken"/>. /// </summary> public bool Equals(SyntaxNodeOrToken other) { // index replaces position to ensure equality. Assert if offset affects equality. Debug.Assert( (_nodeOrParent == other._nodeOrParent && _token == other._token && _position == other._position && _tokenIndex == other._tokenIndex) == (_nodeOrParent == other._nodeOrParent && _token == other._token && _tokenIndex == other._tokenIndex)); return _nodeOrParent == other._nodeOrParent && _token == other._token && _tokenIndex == other._tokenIndex; } /// <summary> /// Determines whether two <see cref="SyntaxNodeOrToken"/>s are equal. /// </summary> public static bool operator ==(SyntaxNodeOrToken left, SyntaxNodeOrToken right) { return left.Equals(right); } /// <summary> /// Determines whether two <see cref="SyntaxNodeOrToken"/>s are unequal. /// </summary> public static bool operator !=(SyntaxNodeOrToken left, SyntaxNodeOrToken right) { return !left.Equals(right); } /// <summary> /// Determines whether the supplied <see cref="SyntaxNodeOrToken"/> is equal to this /// <see cref="SyntaxNodeOrToken"/>. /// </summary> public override bool Equals(object? obj) { return obj is SyntaxNodeOrToken token && Equals(token); } /// <summary> /// Serves as hash function for <see cref="SyntaxNodeOrToken"/>. /// </summary> public override int GetHashCode() { return Hash.Combine(_nodeOrParent, Hash.Combine(_token, _tokenIndex)); } /// <summary> /// Determines if the two nodes or tokens are equivalent. /// </summary> public bool IsEquivalentTo(SyntaxNodeOrToken other) { if (this.IsNode != other.IsNode) { return false; } var thisUnderlying = this.UnderlyingNode; var otherUnderlying = other.UnderlyingNode; return (thisUnderlying == otherUnderlying) || (thisUnderlying != null && thisUnderlying.IsEquivalentTo(otherUnderlying)); } /// <summary> /// See <see cref="SyntaxNode.IsIncrementallyIdenticalTo"/> and <see cref="SyntaxToken.IsIncrementallyIdenticalTo"/>. /// </summary> public bool IsIncrementallyIdenticalTo(SyntaxNodeOrToken other) => this.UnderlyingNode != null && this.UnderlyingNode == other.UnderlyingNode; /// <summary> /// Returns a new <see cref="SyntaxNodeOrToken"/> that wraps the supplied token. /// </summary> /// <param name="token">The input token.</param> /// <returns> /// A <see cref="SyntaxNodeOrToken"/> that wraps the supplied token. /// </returns> public static implicit operator SyntaxNodeOrToken(SyntaxToken token) { return new SyntaxNodeOrToken(token.Parent, token.Node, token.Position, token.Index); } /// <summary> /// Returns the underlying token wrapped by the supplied <see cref="SyntaxNodeOrToken"/>. /// </summary> /// <param name="nodeOrToken"> /// The input <see cref="SyntaxNodeOrToken"/>. /// </param> /// <returns> /// The underlying token wrapped by the supplied <see cref="SyntaxNodeOrToken"/>. /// </returns> public static explicit operator SyntaxToken(SyntaxNodeOrToken nodeOrToken) { return nodeOrToken.AsToken(); } /// <summary> /// Returns a new <see cref="SyntaxNodeOrToken"/> that wraps the supplied node. /// </summary> /// <param name="node">The input node.</param> /// <returns> /// A <see cref="SyntaxNodeOrToken"/> that wraps the supplied node. /// </returns> public static implicit operator SyntaxNodeOrToken(SyntaxNode? node) { return node is object ? new SyntaxNodeOrToken(node) : default; } /// <summary> /// Returns the underlying node wrapped by the supplied <see cref="SyntaxNodeOrToken"/>. /// </summary> /// <param name="nodeOrToken"> /// The input <see cref="SyntaxNodeOrToken"/>. /// </param> /// <returns> /// The underlying node wrapped by the supplied <see cref="SyntaxNodeOrToken"/>. /// </returns> public static explicit operator SyntaxNode?(SyntaxNodeOrToken nodeOrToken) { return nodeOrToken.AsNode(); } /// <summary> /// SyntaxTree which contains current SyntaxNodeOrToken. /// </summary> public SyntaxTree? SyntaxTree => _nodeOrParent?.SyntaxTree; /// <summary> /// Get the location of this node or token. /// </summary> public Location? GetLocation() { if (AsToken(out var token)) { return token.GetLocation(); } return _nodeOrParent?.GetLocation(); } #region Directive Lookup // Get all directives under the node and its children in source code order. internal IList<TDirective> GetDirectives<TDirective>(Func<TDirective, bool>? filter = null) where TDirective : SyntaxNode { List<TDirective>? directives = null; GetDirectives(this, filter, ref directives); return directives ?? SpecializedCollections.EmptyList<TDirective>(); } private static void GetDirectives<TDirective>(in SyntaxNodeOrToken node, Func<TDirective, bool>? filter, ref List<TDirective>? directives) where TDirective : SyntaxNode { if (node._token != null && node.AsToken() is var token && token.ContainsDirectives) { GetDirectives(token.LeadingTrivia, filter, ref directives); GetDirectives(token.TrailingTrivia, filter, ref directives); } else if (node._nodeOrParent != null) { GetDirectives(node._nodeOrParent, filter, ref directives); } } private static void GetDirectives<TDirective>(SyntaxNode node, Func<TDirective, bool>? filter, ref List<TDirective>? directives) where TDirective : SyntaxNode { foreach (var trivia in node.DescendantTrivia(node => node.ContainsDirectives, descendIntoTrivia: true)) { _ = GetDirectivesInTrivia(trivia, filter, ref directives); } } private static bool GetDirectivesInTrivia<TDirective>(in SyntaxTrivia trivia, Func<TDirective, bool>? filter, ref List<TDirective>? directives) where TDirective : SyntaxNode { if (trivia.IsDirective) { if (trivia.GetStructure() is TDirective directive && filter?.Invoke(directive) != false) { if (directives == null) { directives = new List<TDirective>(); } directives.Add(directive); } return true; } return false; } private static void GetDirectives<TDirective>(in SyntaxTriviaList trivia, Func<TDirective, bool>? filter, ref List<TDirective>? directives) where TDirective : SyntaxNode { foreach (var tr in trivia) { if (!GetDirectivesInTrivia(tr, filter, ref directives) && tr.GetStructure() is SyntaxNode node) { GetDirectives(node, filter, ref directives); } } } #endregion internal int Width => _token?.Width ?? _nodeOrParent?.Width ?? 0; internal int FullWidth => _token?.FullWidth ?? _nodeOrParent?.FullWidth ?? 0; internal int EndPosition => _position + this.FullWidth; public static int GetFirstChildIndexSpanningPosition(SyntaxNode node, int position) { if (!node.FullSpan.IntersectsWith(position)) { throw new ArgumentException("Must be within node's FullSpan", nameof(position)); } return GetFirstChildIndexSpanningPosition(node.ChildNodesAndTokens(), position); } internal static int GetFirstChildIndexSpanningPosition(ChildSyntaxList list, int position) { int lo = 0; int hi = list.Count - 1; while (lo <= hi) { int r = lo + ((hi - lo) >> 1); var m = list[r]; if (position < m.Position) { hi = r - 1; } else { if (position == m.Position) { // If we hit a zero width node, move left to the first such node (or the // first one in the list) for (; r > 0 && list[r - 1].FullWidth == 0; r--) { ; } return r; } if (position >= m.EndPosition) { lo = r + 1; continue; } return r; } } throw ExceptionUtilities.Unreachable; } public SyntaxNodeOrToken GetNextSibling() { var parent = this.Parent; if (parent == null) { return default(SyntaxNodeOrToken); } var siblings = parent.ChildNodesAndTokens(); return siblings.Count < 8 ? GetNextSiblingFromStart(siblings) : GetNextSiblingWithSearch(siblings); } public SyntaxNodeOrToken GetPreviousSibling() { if (this.Parent != null) { // walk reverse in parent's child list until we find ourself // and then return the next child var returnNext = false; foreach (var child in this.Parent.ChildNodesAndTokens().Reverse()) { if (returnNext) { return child; } if (child == this) { returnNext = true; } } } return default(SyntaxNodeOrToken); } private SyntaxNodeOrToken GetNextSiblingFromStart(ChildSyntaxList siblings) { var returnNext = false; foreach (var sibling in siblings) { if (returnNext) { return sibling; } if (sibling == this) { returnNext = true; } } return default(SyntaxNodeOrToken); } private SyntaxNodeOrToken GetNextSiblingWithSearch(ChildSyntaxList siblings) { var firstIndex = GetFirstChildIndexSpanningPosition(siblings, _position); var count = siblings.Count; var returnNext = false; for (int i = firstIndex; i < count; i++) { if (returnNext) { return siblings[i]; } if (siblings[i] == this) { returnNext = true; } } return default(SyntaxNodeOrToken); } } }
-1
dotnet/roslyn
55,430
Fix LSP semantic tokens algorithm
This PR primarily accomplishes two tasks: 1) Overhauls the existing LSP semantic tokens edits processing algorithm to align with [Razor's](https://github.com/dotnet/aspnetcore-tooling/blob/main/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/Semantic/Services/SemanticTokensEditsDiffer.cs) (shoutout to Ryan and the rest of the Razor team for writing the original 😄). The main change here is going from calculating edits per token (i.e. five ints) to per int. The updated algorithm is much more efficient than our previous algorithm, and returns less edits back to the LSP client. 2) The interpretation of Roslyn's LongestCommonSubstring algorithm, which we use to calculate raw edits, was missing a critical piece. Namely, for insertions, we need to keep track of _where_ we should be inserting into the original token set. We don't keep track of this in the existing implementation, resulting in bugs such as #54671. Resolves #54671
allisonchou
2021-08-05T06:06:43Z
2021-08-06T23:44:44Z
b9200d03a76c74d404040d44b9bbe12b1d0a8ef2
f300a818940ea1acef66c946cfa83756729d5e59
Fix LSP semantic tokens algorithm. This PR primarily accomplishes two tasks: 1) Overhauls the existing LSP semantic tokens edits processing algorithm to align with [Razor's](https://github.com/dotnet/aspnetcore-tooling/blob/main/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/Semantic/Services/SemanticTokensEditsDiffer.cs) (shoutout to Ryan and the rest of the Razor team for writing the original 😄). The main change here is going from calculating edits per token (i.e. five ints) to per int. The updated algorithm is much more efficient than our previous algorithm, and returns less edits back to the LSP client. 2) The interpretation of Roslyn's LongestCommonSubstring algorithm, which we use to calculate raw edits, was missing a critical piece. Namely, for insertions, we need to keep track of _where_ we should be inserting into the original token set. We don't keep track of this in the existing implementation, resulting in bugs such as #54671. Resolves #54671
./src/Compilers/CSharp/Portable/Declarations/DeclarationTreeBuilder.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Linq; using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; using CoreInternalSyntax = Microsoft.CodeAnalysis.Syntax.InternalSyntax; namespace Microsoft.CodeAnalysis.CSharp { internal sealed class DeclarationTreeBuilder : CSharpSyntaxVisitor<SingleNamespaceOrTypeDeclaration> { private readonly SyntaxTree _syntaxTree; private readonly string _scriptClassName; private readonly bool _isSubmission; private DeclarationTreeBuilder(SyntaxTree syntaxTree, string scriptClassName, bool isSubmission) { _syntaxTree = syntaxTree; _scriptClassName = scriptClassName; _isSubmission = isSubmission; } public static RootSingleNamespaceDeclaration ForTree( SyntaxTree syntaxTree, string scriptClassName, bool isSubmission) { var builder = new DeclarationTreeBuilder(syntaxTree, scriptClassName, isSubmission); return (RootSingleNamespaceDeclaration)builder.Visit(syntaxTree.GetRoot()); } private ImmutableArray<SingleNamespaceOrTypeDeclaration> VisitNamespaceChildren( CSharpSyntaxNode node, SyntaxList<MemberDeclarationSyntax> members, CoreInternalSyntax.SyntaxList<Syntax.InternalSyntax.MemberDeclarationSyntax> internalMembers) { Debug.Assert( node.Kind() is SyntaxKind.NamespaceDeclaration or SyntaxKind.FileScopedNamespaceDeclaration || (node.Kind() == SyntaxKind.CompilationUnit && _syntaxTree.Options.Kind == SourceCodeKind.Regular)); if (members.Count == 0) { return ImmutableArray<SingleNamespaceOrTypeDeclaration>.Empty; } // We look for members that are not allowed in a namespace. // If there are any we create an implicit class to wrap them. bool hasGlobalMembers = false; bool acceptSimpleProgram = node.Kind() == SyntaxKind.CompilationUnit && _syntaxTree.Options.Kind == SourceCodeKind.Regular; bool hasAwaitExpressions = false; bool isIterator = false; bool hasReturnWithExpression = false; GlobalStatementSyntax firstGlobalStatement = null; bool hasNonEmptyGlobalSatement = false; var childrenBuilder = ArrayBuilder<SingleNamespaceOrTypeDeclaration>.GetInstance(); foreach (var member in members) { SingleNamespaceOrTypeDeclaration namespaceOrType = Visit(member); if (namespaceOrType != null) { childrenBuilder.Add(namespaceOrType); } else if (acceptSimpleProgram && member.IsKind(SyntaxKind.GlobalStatement)) { var global = (GlobalStatementSyntax)member; firstGlobalStatement ??= global; var topLevelStatement = global.Statement; if (!topLevelStatement.IsKind(SyntaxKind.EmptyStatement)) { hasNonEmptyGlobalSatement = true; } if (!hasAwaitExpressions) { hasAwaitExpressions = SyntaxFacts.HasAwaitOperations(topLevelStatement); } if (!isIterator) { isIterator = SyntaxFacts.HasYieldOperations(topLevelStatement); } if (!hasReturnWithExpression) { hasReturnWithExpression = SyntaxFacts.HasReturnWithExpression(topLevelStatement); } } else if (!hasGlobalMembers && member.Kind() != SyntaxKind.IncompleteMember) { hasGlobalMembers = true; } } // wrap all global statements in a compilation unit into a simple program type: if (firstGlobalStatement is object) { var diagnostics = ImmutableArray<Diagnostic>.Empty; if (!hasNonEmptyGlobalSatement) { var bag = DiagnosticBag.GetInstance(); bag.Add(ErrorCode.ERR_SimpleProgramIsEmpty, ((EmptyStatementSyntax)firstGlobalStatement.Statement).SemicolonToken.GetLocation()); diagnostics = bag.ToReadOnlyAndFree(); } childrenBuilder.Add(CreateSimpleProgram(firstGlobalStatement, hasAwaitExpressions, isIterator, hasReturnWithExpression, diagnostics)); } // wrap all members that are defined in a namespace or compilation unit into an implicit type: if (hasGlobalMembers) { //The implicit class is not static and has no extensions SingleTypeDeclaration.TypeDeclarationFlags declFlags = SingleTypeDeclaration.TypeDeclarationFlags.None; var memberNames = GetNonTypeMemberNames(internalMembers, ref declFlags, skipGlobalStatements: acceptSimpleProgram); var container = _syntaxTree.GetReference(node); childrenBuilder.Add(CreateImplicitClass(memberNames, container, declFlags)); } return childrenBuilder.ToImmutableAndFree(); } private static SingleNamespaceOrTypeDeclaration CreateImplicitClass(ImmutableSegmentedDictionary<string, VoidResult> memberNames, SyntaxReference container, SingleTypeDeclaration.TypeDeclarationFlags declFlags) { return new SingleTypeDeclaration( kind: DeclarationKind.ImplicitClass, name: TypeSymbol.ImplicitTypeName, arity: 0, modifiers: DeclarationModifiers.Internal | DeclarationModifiers.Partial | DeclarationModifiers.Sealed, declFlags: declFlags, syntaxReference: container, nameLocation: new SourceLocation(container), memberNames: memberNames, children: ImmutableArray<SingleTypeDeclaration>.Empty, diagnostics: ImmutableArray<Diagnostic>.Empty); } private static SingleNamespaceOrTypeDeclaration CreateSimpleProgram(GlobalStatementSyntax firstGlobalStatement, bool hasAwaitExpressions, bool isIterator, bool hasReturnWithExpression, ImmutableArray<Diagnostic> diagnostics) { return new SingleTypeDeclaration( kind: DeclarationKind.Class, name: WellKnownMemberNames.TopLevelStatementsEntryPointTypeName, arity: 0, modifiers: DeclarationModifiers.Partial, declFlags: (hasAwaitExpressions ? SingleTypeDeclaration.TypeDeclarationFlags.HasAwaitExpressions : SingleTypeDeclaration.TypeDeclarationFlags.None) | (isIterator ? SingleTypeDeclaration.TypeDeclarationFlags.IsIterator : SingleTypeDeclaration.TypeDeclarationFlags.None) | (hasReturnWithExpression ? SingleTypeDeclaration.TypeDeclarationFlags.HasReturnWithExpression : SingleTypeDeclaration.TypeDeclarationFlags.None) | SingleTypeDeclaration.TypeDeclarationFlags.IsSimpleProgram, syntaxReference: firstGlobalStatement.SyntaxTree.GetReference(firstGlobalStatement.Parent), nameLocation: new SourceLocation(firstGlobalStatement.GetFirstToken()), memberNames: ImmutableSegmentedDictionary<string, VoidResult>.Empty, children: ImmutableArray<SingleTypeDeclaration>.Empty, diagnostics: diagnostics); } /// <summary> /// Creates a root declaration that contains a Script class declaration (possibly in a namespace) and namespace declarations. /// Top-level declarations in script code are nested in Script class. /// </summary> private RootSingleNamespaceDeclaration CreateScriptRootDeclaration(CompilationUnitSyntax compilationUnit) { Debug.Assert(_syntaxTree.Options.Kind != SourceCodeKind.Regular); var members = compilationUnit.Members; var rootChildren = ArrayBuilder<SingleNamespaceOrTypeDeclaration>.GetInstance(); var scriptChildren = ArrayBuilder<SingleTypeDeclaration>.GetInstance(); foreach (var member in members) { var decl = Visit(member); if (decl != null) { // Although namespaces are not allowed in script code process them // here as if they were to improve error reporting. if (decl.Kind == DeclarationKind.Namespace) { rootChildren.Add(decl); } else { scriptChildren.Add((SingleTypeDeclaration)decl); } } } //Script class is not static and contains no extensions. SingleTypeDeclaration.TypeDeclarationFlags declFlags = SingleTypeDeclaration.TypeDeclarationFlags.None; var membernames = GetNonTypeMemberNames(((Syntax.InternalSyntax.CompilationUnitSyntax)(compilationUnit.Green)).Members, ref declFlags); rootChildren.Add( CreateScriptClass( compilationUnit, scriptChildren.ToImmutableAndFree(), membernames, declFlags)); return CreateRootSingleNamespaceDeclaration(compilationUnit, rootChildren.ToImmutableAndFree(), isForScript: true); } private static ImmutableArray<ReferenceDirective> GetReferenceDirectives(CompilationUnitSyntax compilationUnit) { IList<ReferenceDirectiveTriviaSyntax> directiveNodes = compilationUnit.GetReferenceDirectives( d => !d.File.ContainsDiagnostics && !string.IsNullOrEmpty(d.File.ValueText)); if (directiveNodes.Count == 0) { return ImmutableArray<ReferenceDirective>.Empty; } var directives = ArrayBuilder<ReferenceDirective>.GetInstance(directiveNodes.Count); foreach (var directiveNode in directiveNodes) { directives.Add(new ReferenceDirective(directiveNode.File.ValueText, new SourceLocation(directiveNode))); } return directives.ToImmutableAndFree(); } private SingleNamespaceOrTypeDeclaration CreateScriptClass( CompilationUnitSyntax parent, ImmutableArray<SingleTypeDeclaration> children, ImmutableSegmentedDictionary<string, VoidResult> memberNames, SingleTypeDeclaration.TypeDeclarationFlags declFlags) { Debug.Assert(parent.Kind() == SyntaxKind.CompilationUnit && _syntaxTree.Options.Kind != SourceCodeKind.Regular); // script type is represented by the parent node: var parentReference = _syntaxTree.GetReference(parent); var fullName = _scriptClassName.Split('.'); // Note: The symbol representing the merged declarations uses parentReference to enumerate non-type members. SingleNamespaceOrTypeDeclaration decl = new SingleTypeDeclaration( kind: _isSubmission ? DeclarationKind.Submission : DeclarationKind.Script, name: fullName.Last(), arity: 0, modifiers: DeclarationModifiers.Internal | DeclarationModifiers.Partial | DeclarationModifiers.Sealed, declFlags: declFlags, syntaxReference: parentReference, nameLocation: new SourceLocation(parentReference), memberNames: memberNames, children: children, diagnostics: ImmutableArray<Diagnostic>.Empty); for (int i = fullName.Length - 2; i >= 0; i--) { decl = SingleNamespaceDeclaration.Create( name: fullName[i], hasUsings: false, hasExternAliases: false, syntaxReference: parentReference, nameLocation: new SourceLocation(parentReference), children: ImmutableArray.Create(decl), diagnostics: ImmutableArray<Diagnostic>.Empty); } return decl; } public override SingleNamespaceOrTypeDeclaration VisitCompilationUnit(CompilationUnitSyntax compilationUnit) { if (_syntaxTree.Options.Kind != SourceCodeKind.Regular) { return CreateScriptRootDeclaration(compilationUnit); } var children = VisitNamespaceChildren(compilationUnit, compilationUnit.Members, ((Syntax.InternalSyntax.CompilationUnitSyntax)(compilationUnit.Green)).Members); return CreateRootSingleNamespaceDeclaration(compilationUnit, children, isForScript: false); } private RootSingleNamespaceDeclaration CreateRootSingleNamespaceDeclaration(CompilationUnitSyntax compilationUnit, ImmutableArray<SingleNamespaceOrTypeDeclaration> children, bool isForScript) { bool hasUsings = false; bool hasGlobalUsings = false; bool reportedGlobalUsingOutOfOrder = false; var diagnostics = DiagnosticBag.GetInstance(); foreach (var directive in compilationUnit.Usings) { if (directive.GlobalKeyword.IsKind(SyntaxKind.GlobalKeyword)) { hasGlobalUsings = true; if (hasUsings && !reportedGlobalUsingOutOfOrder) { reportedGlobalUsingOutOfOrder = true; diagnostics.Add(ErrorCode.ERR_GlobalUsingOutOfOrder, directive.GlobalKeyword.GetLocation()); } } else { hasUsings = true; } } return new RootSingleNamespaceDeclaration( hasGlobalUsings: hasGlobalUsings, hasUsings: hasUsings, hasExternAliases: compilationUnit.Externs.Any(), treeNode: _syntaxTree.GetReference(compilationUnit), children: children, referenceDirectives: isForScript ? GetReferenceDirectives(compilationUnit) : ImmutableArray<ReferenceDirective>.Empty, hasAssemblyAttributes: compilationUnit.AttributeLists.Any(), diagnostics: diagnostics.ToReadOnlyAndFree()); } public override SingleNamespaceOrTypeDeclaration VisitFileScopedNamespaceDeclaration(FileScopedNamespaceDeclarationSyntax node) => this.VisitBaseNamespaceDeclaration(node); public override SingleNamespaceOrTypeDeclaration VisitNamespaceDeclaration(NamespaceDeclarationSyntax node) => this.VisitBaseNamespaceDeclaration(node); private SingleNamespaceDeclaration VisitBaseNamespaceDeclaration(BaseNamespaceDeclarationSyntax node) { var children = VisitNamespaceChildren(node, node.Members, ((Syntax.InternalSyntax.BaseNamespaceDeclarationSyntax)node.Green).Members); bool hasUsings = node.Usings.Any(); bool hasExterns = node.Externs.Any(); NameSyntax name = node.Name; CSharpSyntaxNode currentNode = node; QualifiedNameSyntax dotted; while ((dotted = name as QualifiedNameSyntax) != null) { var ns = SingleNamespaceDeclaration.Create( name: dotted.Right.Identifier.ValueText, hasUsings: hasUsings, hasExternAliases: hasExterns, syntaxReference: _syntaxTree.GetReference(currentNode), nameLocation: new SourceLocation(dotted.Right), children: children, diagnostics: ImmutableArray<Diagnostic>.Empty); var nsDeclaration = new[] { ns }; children = nsDeclaration.AsImmutableOrNull<SingleNamespaceOrTypeDeclaration>(); currentNode = name = dotted.Left; hasUsings = false; hasExterns = false; } var diagnostics = DiagnosticBag.GetInstance(); if (node is FileScopedNamespaceDeclarationSyntax) { if (node.Parent is FileScopedNamespaceDeclarationSyntax) { // Happens when user writes: // namespace A.B; // namespace X.Y; diagnostics.Add(ErrorCode.ERR_MultipleFileScopedNamespace, node.Name.GetLocation()); } else if (node.Parent is NamespaceDeclarationSyntax) { // Happens with: // // namespace A.B // { // namespace X.Y; diagnostics.Add(ErrorCode.ERR_FileScopedAndNormalNamespace, node.Name.GetLocation()); } else { // Happens with cases like: // // namespace A.B { } // namespace X.Y; // // or even // // class C { } // namespace X.Y; Debug.Assert(node.Parent is CompilationUnitSyntax); var compilationUnit = (CompilationUnitSyntax)node.Parent; if (node != compilationUnit.Members[0]) { diagnostics.Add(ErrorCode.ERR_FileScopedNamespaceNotBeforeAllMembers, node.Name.GetLocation()); } } } else { Debug.Assert(node is NamespaceDeclarationSyntax); // namespace X.Y; // namespace A.B { } if (node.Parent is FileScopedNamespaceDeclarationSyntax) { diagnostics.Add(ErrorCode.ERR_FileScopedAndNormalNamespace, node.Name.GetLocation()); } } if (ContainsGeneric(node.Name)) { // We're not allowed to have generics. diagnostics.Add(ErrorCode.ERR_UnexpectedGenericName, node.Name.GetLocation()); } if (ContainsAlias(node.Name)) { diagnostics.Add(ErrorCode.ERR_UnexpectedAliasedName, node.Name.GetLocation()); } if (node.AttributeLists.Count > 0) { diagnostics.Add(ErrorCode.ERR_BadModifiersOnNamespace, node.AttributeLists[0].GetLocation()); } if (node.Modifiers.Count > 0) { diagnostics.Add(ErrorCode.ERR_BadModifiersOnNamespace, node.Modifiers[0].GetLocation()); } foreach (var directive in node.Usings) { if (directive.GlobalKeyword.IsKind(SyntaxKind.GlobalKeyword)) { diagnostics.Add(ErrorCode.ERR_GlobalUsingInNamespace, directive.GlobalKeyword.GetLocation()); break; } } // NOTE: *Something* has to happen for alias-qualified names. It turns out that we // just grab the part after the colons (via GetUnqualifiedName, below). This logic // must be kept in sync with NamespaceSymbol.GetNestedNamespace. return SingleNamespaceDeclaration.Create( name: name.GetUnqualifiedName().Identifier.ValueText, hasUsings: hasUsings, hasExternAliases: hasExterns, syntaxReference: _syntaxTree.GetReference(currentNode), nameLocation: new SourceLocation(name), children: children, diagnostics: diagnostics.ToReadOnlyAndFree()); } private static bool ContainsAlias(NameSyntax name) { switch (name.Kind()) { case SyntaxKind.GenericName: return false; case SyntaxKind.AliasQualifiedName: return true; case SyntaxKind.QualifiedName: var qualifiedName = (QualifiedNameSyntax)name; return ContainsAlias(qualifiedName.Left); } return false; } private static bool ContainsGeneric(NameSyntax name) { switch (name.Kind()) { case SyntaxKind.GenericName: return true; case SyntaxKind.AliasQualifiedName: return ContainsGeneric(((AliasQualifiedNameSyntax)name).Name); case SyntaxKind.QualifiedName: var qualifiedName = (QualifiedNameSyntax)name; return ContainsGeneric(qualifiedName.Left) || ContainsGeneric(qualifiedName.Right); } return false; } public override SingleNamespaceOrTypeDeclaration VisitClassDeclaration(ClassDeclarationSyntax node) { return VisitTypeDeclaration(node, DeclarationKind.Class); } public override SingleNamespaceOrTypeDeclaration VisitStructDeclaration(StructDeclarationSyntax node) { return VisitTypeDeclaration(node, DeclarationKind.Struct); } public override SingleNamespaceOrTypeDeclaration VisitInterfaceDeclaration(InterfaceDeclarationSyntax node) { return VisitTypeDeclaration(node, DeclarationKind.Interface); } public override SingleNamespaceOrTypeDeclaration VisitRecordDeclaration(RecordDeclarationSyntax node) { var declarationKind = node.Kind() switch { SyntaxKind.RecordDeclaration => DeclarationKind.Record, SyntaxKind.RecordStructDeclaration => DeclarationKind.RecordStruct, _ => throw ExceptionUtilities.UnexpectedValue(node.Kind()) }; return VisitTypeDeclaration(node, declarationKind); } private SingleNamespaceOrTypeDeclaration VisitTypeDeclaration(TypeDeclarationSyntax node, DeclarationKind kind) { SingleTypeDeclaration.TypeDeclarationFlags declFlags = node.AttributeLists.Any() ? SingleTypeDeclaration.TypeDeclarationFlags.HasAnyAttributes : SingleTypeDeclaration.TypeDeclarationFlags.None; if (node.BaseList != null) { declFlags |= SingleTypeDeclaration.TypeDeclarationFlags.HasBaseDeclarations; } var diagnostics = DiagnosticBag.GetInstance(); if (node.Arity == 0) { Symbol.ReportErrorIfHasConstraints(node.ConstraintClauses, diagnostics); } var memberNames = GetNonTypeMemberNames(((Syntax.InternalSyntax.TypeDeclarationSyntax)(node.Green)).Members, ref declFlags); // A record with parameters at least has a primary constructor if (((declFlags & SingleTypeDeclaration.TypeDeclarationFlags.HasAnyNontypeMembers) == 0) && node is RecordDeclarationSyntax { ParameterList: { } }) { declFlags |= SingleTypeDeclaration.TypeDeclarationFlags.HasAnyNontypeMembers; } var modifiers = node.Modifiers.ToDeclarationModifiers(diagnostics: diagnostics); return new SingleTypeDeclaration( kind: kind, name: node.Identifier.ValueText, modifiers: modifiers, arity: node.Arity, declFlags: declFlags, syntaxReference: _syntaxTree.GetReference(node), nameLocation: new SourceLocation(node.Identifier), memberNames: memberNames, children: VisitTypeChildren(node), diagnostics: diagnostics.ToReadOnlyAndFree()); } private ImmutableArray<SingleTypeDeclaration> VisitTypeChildren(TypeDeclarationSyntax node) { if (node.Members.Count == 0) { return ImmutableArray<SingleTypeDeclaration>.Empty; } var children = ArrayBuilder<SingleTypeDeclaration>.GetInstance(); foreach (var member in node.Members) { var typeDecl = Visit(member) as SingleTypeDeclaration; if (typeDecl != null) { children.Add(typeDecl); } } return children.ToImmutableAndFree(); } public override SingleNamespaceOrTypeDeclaration VisitDelegateDeclaration(DelegateDeclarationSyntax node) { var declFlags = node.AttributeLists.Any() ? SingleTypeDeclaration.TypeDeclarationFlags.HasAnyAttributes : SingleTypeDeclaration.TypeDeclarationFlags.None; var diagnostics = DiagnosticBag.GetInstance(); if (node.Arity == 0) { Symbol.ReportErrorIfHasConstraints(node.ConstraintClauses, diagnostics); } declFlags |= SingleTypeDeclaration.TypeDeclarationFlags.HasAnyNontypeMembers; var modifiers = node.Modifiers.ToDeclarationModifiers(diagnostics: diagnostics); return new SingleTypeDeclaration( kind: DeclarationKind.Delegate, name: node.Identifier.ValueText, modifiers: modifiers, declFlags: declFlags, arity: node.Arity, syntaxReference: _syntaxTree.GetReference(node), nameLocation: new SourceLocation(node.Identifier), memberNames: ImmutableSegmentedDictionary<string, VoidResult>.Empty, children: ImmutableArray<SingleTypeDeclaration>.Empty, diagnostics: diagnostics.ToReadOnlyAndFree()); } public override SingleNamespaceOrTypeDeclaration VisitEnumDeclaration(EnumDeclarationSyntax node) { var members = node.Members; SingleTypeDeclaration.TypeDeclarationFlags declFlags = node.AttributeLists.Any() ? SingleTypeDeclaration.TypeDeclarationFlags.HasAnyAttributes : SingleTypeDeclaration.TypeDeclarationFlags.None; if (node.BaseList != null) { declFlags |= SingleTypeDeclaration.TypeDeclarationFlags.HasBaseDeclarations; } ImmutableSegmentedDictionary<string, VoidResult> memberNames = GetEnumMemberNames(members, ref declFlags); var diagnostics = DiagnosticBag.GetInstance(); var modifiers = node.Modifiers.ToDeclarationModifiers(diagnostics: diagnostics); return new SingleTypeDeclaration( kind: DeclarationKind.Enum, name: node.Identifier.ValueText, arity: 0, modifiers: modifiers, declFlags: declFlags, syntaxReference: _syntaxTree.GetReference(node), nameLocation: new SourceLocation(node.Identifier), memberNames: memberNames, children: ImmutableArray<SingleTypeDeclaration>.Empty, diagnostics: diagnostics.ToReadOnlyAndFree()); } private static readonly ObjectPool<ImmutableSegmentedDictionary<string, VoidResult>.Builder> s_memberNameBuilderPool = new ObjectPool<ImmutableSegmentedDictionary<string, VoidResult>.Builder>(() => ImmutableSegmentedDictionary.CreateBuilder<string, VoidResult>()); private static ImmutableSegmentedDictionary<string, VoidResult> ToImmutableAndFree(ImmutableSegmentedDictionary<string, VoidResult>.Builder builder) { var result = builder.ToImmutable(); builder.Clear(); s_memberNameBuilderPool.Free(builder); return result; } private static ImmutableSegmentedDictionary<string, VoidResult> GetEnumMemberNames(SeparatedSyntaxList<EnumMemberDeclarationSyntax> members, ref SingleTypeDeclaration.TypeDeclarationFlags declFlags) { var cnt = members.Count; var memberNamesBuilder = s_memberNameBuilderPool.Allocate(); if (cnt != 0) { declFlags |= SingleTypeDeclaration.TypeDeclarationFlags.HasAnyNontypeMembers; } bool anyMemberHasAttributes = false; foreach (var member in members) { memberNamesBuilder.TryAdd(member.Identifier.ValueText); if (!anyMemberHasAttributes && member.AttributeLists.Any()) { anyMemberHasAttributes = true; } } if (anyMemberHasAttributes) { declFlags |= SingleTypeDeclaration.TypeDeclarationFlags.AnyMemberHasAttributes; } return ToImmutableAndFree(memberNamesBuilder); } private static ImmutableSegmentedDictionary<string, VoidResult> GetNonTypeMemberNames( CoreInternalSyntax.SyntaxList<Syntax.InternalSyntax.MemberDeclarationSyntax> members, ref SingleTypeDeclaration.TypeDeclarationFlags declFlags, bool skipGlobalStatements = false) { bool anyMethodHadExtensionSyntax = false; bool anyMemberHasAttributes = false; bool anyNonTypeMembers = false; var memberNameBuilder = s_memberNameBuilderPool.Allocate(); foreach (var member in members) { AddNonTypeMemberNames(member, memberNameBuilder, ref anyNonTypeMembers, skipGlobalStatements); // Check to see if any method contains a 'this' modifier on its first parameter. // This data is used to determine if a type needs to have its members materialized // as part of extension method lookup. if (!anyMethodHadExtensionSyntax && CheckMethodMemberForExtensionSyntax(member)) { anyMethodHadExtensionSyntax = true; } if (!anyMemberHasAttributes && CheckMemberForAttributes(member)) { anyMemberHasAttributes = true; } } if (anyMethodHadExtensionSyntax) { declFlags |= SingleTypeDeclaration.TypeDeclarationFlags.AnyMemberHasExtensionMethodSyntax; } if (anyMemberHasAttributes) { declFlags |= SingleTypeDeclaration.TypeDeclarationFlags.AnyMemberHasAttributes; } if (anyNonTypeMembers) { declFlags |= SingleTypeDeclaration.TypeDeclarationFlags.HasAnyNontypeMembers; } return ToImmutableAndFree(memberNameBuilder); } private static bool CheckMethodMemberForExtensionSyntax(Syntax.InternalSyntax.CSharpSyntaxNode member) { if (member.Kind == SyntaxKind.MethodDeclaration) { var methodDecl = (Syntax.InternalSyntax.MethodDeclarationSyntax)member; var paramList = methodDecl.parameterList; if (paramList != null) { var parameters = paramList.Parameters; if (parameters.Count != 0) { var firstParameter = parameters[0]; foreach (var modifier in firstParameter.Modifiers) { if (modifier.Kind == SyntaxKind.ThisKeyword) { return true; } } } } } return false; } private static bool CheckMemberForAttributes(Syntax.InternalSyntax.CSharpSyntaxNode member) { switch (member.Kind) { case SyntaxKind.CompilationUnit: return (((Syntax.InternalSyntax.CompilationUnitSyntax)member).AttributeLists).Any(); case SyntaxKind.ClassDeclaration: case SyntaxKind.StructDeclaration: case SyntaxKind.InterfaceDeclaration: case SyntaxKind.EnumDeclaration: case SyntaxKind.RecordDeclaration: case SyntaxKind.RecordStructDeclaration: return (((Syntax.InternalSyntax.BaseTypeDeclarationSyntax)member).AttributeLists).Any(); case SyntaxKind.DelegateDeclaration: return (((Syntax.InternalSyntax.DelegateDeclarationSyntax)member).AttributeLists).Any(); case SyntaxKind.FieldDeclaration: case SyntaxKind.EventFieldDeclaration: return (((Syntax.InternalSyntax.BaseFieldDeclarationSyntax)member).AttributeLists).Any(); case SyntaxKind.MethodDeclaration: case SyntaxKind.OperatorDeclaration: case SyntaxKind.ConversionOperatorDeclaration: case SyntaxKind.ConstructorDeclaration: case SyntaxKind.DestructorDeclaration: return (((Syntax.InternalSyntax.BaseMethodDeclarationSyntax)member).AttributeLists).Any(); case SyntaxKind.PropertyDeclaration: case SyntaxKind.EventDeclaration: case SyntaxKind.IndexerDeclaration: var baseProp = (Syntax.InternalSyntax.BasePropertyDeclarationSyntax)member; bool hasAttributes = baseProp.AttributeLists.Any(); if (!hasAttributes && baseProp.AccessorList != null) { foreach (var accessor in baseProp.AccessorList.Accessors) { hasAttributes |= accessor.AttributeLists.Any(); } } return hasAttributes; } return false; } private static void AddNonTypeMemberNames( Syntax.InternalSyntax.CSharpSyntaxNode member, ImmutableSegmentedDictionary<string, VoidResult>.Builder set, ref bool anyNonTypeMembers, bool skipGlobalStatements) { switch (member.Kind) { case SyntaxKind.FieldDeclaration: anyNonTypeMembers = true; CodeAnalysis.Syntax.InternalSyntax.SeparatedSyntaxList<Syntax.InternalSyntax.VariableDeclaratorSyntax> fieldDeclarators = ((Syntax.InternalSyntax.FieldDeclarationSyntax)member).Declaration.Variables; int numFieldDeclarators = fieldDeclarators.Count; for (int i = 0; i < numFieldDeclarators; i++) { set.TryAdd(fieldDeclarators[i].Identifier.ValueText); } break; case SyntaxKind.EventFieldDeclaration: anyNonTypeMembers = true; CoreInternalSyntax.SeparatedSyntaxList<Syntax.InternalSyntax.VariableDeclaratorSyntax> eventDeclarators = ((Syntax.InternalSyntax.EventFieldDeclarationSyntax)member).Declaration.Variables; int numEventDeclarators = eventDeclarators.Count; for (int i = 0; i < numEventDeclarators; i++) { set.TryAdd(eventDeclarators[i].Identifier.ValueText); } break; case SyntaxKind.MethodDeclaration: anyNonTypeMembers = true; // Member names are exposed via NamedTypeSymbol.MemberNames and are used primarily // as an acid test to determine whether a more in-depth search of a type is worthwhile. // We decided that it was reasonable to exclude explicit interface implementations // from the list of member names. var methodDecl = (Syntax.InternalSyntax.MethodDeclarationSyntax)member; if (methodDecl.ExplicitInterfaceSpecifier == null) { set.TryAdd(methodDecl.Identifier.ValueText); } break; case SyntaxKind.PropertyDeclaration: anyNonTypeMembers = true; // Handle in the same way as explicit method implementations var propertyDecl = (Syntax.InternalSyntax.PropertyDeclarationSyntax)member; if (propertyDecl.ExplicitInterfaceSpecifier == null) { set.TryAdd(propertyDecl.Identifier.ValueText); } break; case SyntaxKind.EventDeclaration: anyNonTypeMembers = true; // Handle in the same way as explicit method implementations var eventDecl = (Syntax.InternalSyntax.EventDeclarationSyntax)member; if (eventDecl.ExplicitInterfaceSpecifier == null) { set.TryAdd(eventDecl.Identifier.ValueText); } break; case SyntaxKind.ConstructorDeclaration: anyNonTypeMembers = true; set.TryAdd(((Syntax.InternalSyntax.ConstructorDeclarationSyntax)member).Modifiers.Any((int)SyntaxKind.StaticKeyword) ? WellKnownMemberNames.StaticConstructorName : WellKnownMemberNames.InstanceConstructorName); break; case SyntaxKind.DestructorDeclaration: anyNonTypeMembers = true; set.TryAdd(WellKnownMemberNames.DestructorName); break; case SyntaxKind.IndexerDeclaration: anyNonTypeMembers = true; set.TryAdd(WellKnownMemberNames.Indexer); break; case SyntaxKind.OperatorDeclaration: { anyNonTypeMembers = true; // Handle in the same way as explicit method implementations var opDecl = (Syntax.InternalSyntax.OperatorDeclarationSyntax)member; if (opDecl.ExplicitInterfaceSpecifier == null) { var name = OperatorFacts.OperatorNameFromDeclaration(opDecl); set.TryAdd(name); } } break; case SyntaxKind.ConversionOperatorDeclaration: { anyNonTypeMembers = true; // Handle in the same way as explicit method implementations var opDecl = (Syntax.InternalSyntax.ConversionOperatorDeclarationSyntax)member; if (opDecl.ExplicitInterfaceSpecifier == null) { var name = OperatorFacts.OperatorNameFromDeclaration(opDecl); set.TryAdd(name); } } break; case SyntaxKind.GlobalStatement: if (!skipGlobalStatements) { anyNonTypeMembers = true; } 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. #nullable disable using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Linq; using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; using CoreInternalSyntax = Microsoft.CodeAnalysis.Syntax.InternalSyntax; namespace Microsoft.CodeAnalysis.CSharp { internal sealed class DeclarationTreeBuilder : CSharpSyntaxVisitor<SingleNamespaceOrTypeDeclaration> { private readonly SyntaxTree _syntaxTree; private readonly string _scriptClassName; private readonly bool _isSubmission; private DeclarationTreeBuilder(SyntaxTree syntaxTree, string scriptClassName, bool isSubmission) { _syntaxTree = syntaxTree; _scriptClassName = scriptClassName; _isSubmission = isSubmission; } public static RootSingleNamespaceDeclaration ForTree( SyntaxTree syntaxTree, string scriptClassName, bool isSubmission) { var builder = new DeclarationTreeBuilder(syntaxTree, scriptClassName, isSubmission); return (RootSingleNamespaceDeclaration)builder.Visit(syntaxTree.GetRoot()); } private ImmutableArray<SingleNamespaceOrTypeDeclaration> VisitNamespaceChildren( CSharpSyntaxNode node, SyntaxList<MemberDeclarationSyntax> members, CoreInternalSyntax.SyntaxList<Syntax.InternalSyntax.MemberDeclarationSyntax> internalMembers) { Debug.Assert( node.Kind() is SyntaxKind.NamespaceDeclaration or SyntaxKind.FileScopedNamespaceDeclaration || (node.Kind() == SyntaxKind.CompilationUnit && _syntaxTree.Options.Kind == SourceCodeKind.Regular)); if (members.Count == 0) { return ImmutableArray<SingleNamespaceOrTypeDeclaration>.Empty; } // We look for members that are not allowed in a namespace. // If there are any we create an implicit class to wrap them. bool hasGlobalMembers = false; bool acceptSimpleProgram = node.Kind() == SyntaxKind.CompilationUnit && _syntaxTree.Options.Kind == SourceCodeKind.Regular; bool hasAwaitExpressions = false; bool isIterator = false; bool hasReturnWithExpression = false; GlobalStatementSyntax firstGlobalStatement = null; bool hasNonEmptyGlobalSatement = false; var childrenBuilder = ArrayBuilder<SingleNamespaceOrTypeDeclaration>.GetInstance(); foreach (var member in members) { SingleNamespaceOrTypeDeclaration namespaceOrType = Visit(member); if (namespaceOrType != null) { childrenBuilder.Add(namespaceOrType); } else if (acceptSimpleProgram && member.IsKind(SyntaxKind.GlobalStatement)) { var global = (GlobalStatementSyntax)member; firstGlobalStatement ??= global; var topLevelStatement = global.Statement; if (!topLevelStatement.IsKind(SyntaxKind.EmptyStatement)) { hasNonEmptyGlobalSatement = true; } if (!hasAwaitExpressions) { hasAwaitExpressions = SyntaxFacts.HasAwaitOperations(topLevelStatement); } if (!isIterator) { isIterator = SyntaxFacts.HasYieldOperations(topLevelStatement); } if (!hasReturnWithExpression) { hasReturnWithExpression = SyntaxFacts.HasReturnWithExpression(topLevelStatement); } } else if (!hasGlobalMembers && member.Kind() != SyntaxKind.IncompleteMember) { hasGlobalMembers = true; } } // wrap all global statements in a compilation unit into a simple program type: if (firstGlobalStatement is object) { var diagnostics = ImmutableArray<Diagnostic>.Empty; if (!hasNonEmptyGlobalSatement) { var bag = DiagnosticBag.GetInstance(); bag.Add(ErrorCode.ERR_SimpleProgramIsEmpty, ((EmptyStatementSyntax)firstGlobalStatement.Statement).SemicolonToken.GetLocation()); diagnostics = bag.ToReadOnlyAndFree(); } childrenBuilder.Add(CreateSimpleProgram(firstGlobalStatement, hasAwaitExpressions, isIterator, hasReturnWithExpression, diagnostics)); } // wrap all members that are defined in a namespace or compilation unit into an implicit type: if (hasGlobalMembers) { //The implicit class is not static and has no extensions SingleTypeDeclaration.TypeDeclarationFlags declFlags = SingleTypeDeclaration.TypeDeclarationFlags.None; var memberNames = GetNonTypeMemberNames(internalMembers, ref declFlags, skipGlobalStatements: acceptSimpleProgram); var container = _syntaxTree.GetReference(node); childrenBuilder.Add(CreateImplicitClass(memberNames, container, declFlags)); } return childrenBuilder.ToImmutableAndFree(); } private static SingleNamespaceOrTypeDeclaration CreateImplicitClass(ImmutableSegmentedDictionary<string, VoidResult> memberNames, SyntaxReference container, SingleTypeDeclaration.TypeDeclarationFlags declFlags) { return new SingleTypeDeclaration( kind: DeclarationKind.ImplicitClass, name: TypeSymbol.ImplicitTypeName, arity: 0, modifiers: DeclarationModifiers.Internal | DeclarationModifiers.Partial | DeclarationModifiers.Sealed, declFlags: declFlags, syntaxReference: container, nameLocation: new SourceLocation(container), memberNames: memberNames, children: ImmutableArray<SingleTypeDeclaration>.Empty, diagnostics: ImmutableArray<Diagnostic>.Empty); } private static SingleNamespaceOrTypeDeclaration CreateSimpleProgram(GlobalStatementSyntax firstGlobalStatement, bool hasAwaitExpressions, bool isIterator, bool hasReturnWithExpression, ImmutableArray<Diagnostic> diagnostics) { return new SingleTypeDeclaration( kind: DeclarationKind.Class, name: WellKnownMemberNames.TopLevelStatementsEntryPointTypeName, arity: 0, modifiers: DeclarationModifiers.Partial, declFlags: (hasAwaitExpressions ? SingleTypeDeclaration.TypeDeclarationFlags.HasAwaitExpressions : SingleTypeDeclaration.TypeDeclarationFlags.None) | (isIterator ? SingleTypeDeclaration.TypeDeclarationFlags.IsIterator : SingleTypeDeclaration.TypeDeclarationFlags.None) | (hasReturnWithExpression ? SingleTypeDeclaration.TypeDeclarationFlags.HasReturnWithExpression : SingleTypeDeclaration.TypeDeclarationFlags.None) | SingleTypeDeclaration.TypeDeclarationFlags.IsSimpleProgram, syntaxReference: firstGlobalStatement.SyntaxTree.GetReference(firstGlobalStatement.Parent), nameLocation: new SourceLocation(firstGlobalStatement.GetFirstToken()), memberNames: ImmutableSegmentedDictionary<string, VoidResult>.Empty, children: ImmutableArray<SingleTypeDeclaration>.Empty, diagnostics: diagnostics); } /// <summary> /// Creates a root declaration that contains a Script class declaration (possibly in a namespace) and namespace declarations. /// Top-level declarations in script code are nested in Script class. /// </summary> private RootSingleNamespaceDeclaration CreateScriptRootDeclaration(CompilationUnitSyntax compilationUnit) { Debug.Assert(_syntaxTree.Options.Kind != SourceCodeKind.Regular); var members = compilationUnit.Members; var rootChildren = ArrayBuilder<SingleNamespaceOrTypeDeclaration>.GetInstance(); var scriptChildren = ArrayBuilder<SingleTypeDeclaration>.GetInstance(); foreach (var member in members) { var decl = Visit(member); if (decl != null) { // Although namespaces are not allowed in script code process them // here as if they were to improve error reporting. if (decl.Kind == DeclarationKind.Namespace) { rootChildren.Add(decl); } else { scriptChildren.Add((SingleTypeDeclaration)decl); } } } //Script class is not static and contains no extensions. SingleTypeDeclaration.TypeDeclarationFlags declFlags = SingleTypeDeclaration.TypeDeclarationFlags.None; var membernames = GetNonTypeMemberNames(((Syntax.InternalSyntax.CompilationUnitSyntax)(compilationUnit.Green)).Members, ref declFlags); rootChildren.Add( CreateScriptClass( compilationUnit, scriptChildren.ToImmutableAndFree(), membernames, declFlags)); return CreateRootSingleNamespaceDeclaration(compilationUnit, rootChildren.ToImmutableAndFree(), isForScript: true); } private static ImmutableArray<ReferenceDirective> GetReferenceDirectives(CompilationUnitSyntax compilationUnit) { IList<ReferenceDirectiveTriviaSyntax> directiveNodes = compilationUnit.GetReferenceDirectives( d => !d.File.ContainsDiagnostics && !string.IsNullOrEmpty(d.File.ValueText)); if (directiveNodes.Count == 0) { return ImmutableArray<ReferenceDirective>.Empty; } var directives = ArrayBuilder<ReferenceDirective>.GetInstance(directiveNodes.Count); foreach (var directiveNode in directiveNodes) { directives.Add(new ReferenceDirective(directiveNode.File.ValueText, new SourceLocation(directiveNode))); } return directives.ToImmutableAndFree(); } private SingleNamespaceOrTypeDeclaration CreateScriptClass( CompilationUnitSyntax parent, ImmutableArray<SingleTypeDeclaration> children, ImmutableSegmentedDictionary<string, VoidResult> memberNames, SingleTypeDeclaration.TypeDeclarationFlags declFlags) { Debug.Assert(parent.Kind() == SyntaxKind.CompilationUnit && _syntaxTree.Options.Kind != SourceCodeKind.Regular); // script type is represented by the parent node: var parentReference = _syntaxTree.GetReference(parent); var fullName = _scriptClassName.Split('.'); // Note: The symbol representing the merged declarations uses parentReference to enumerate non-type members. SingleNamespaceOrTypeDeclaration decl = new SingleTypeDeclaration( kind: _isSubmission ? DeclarationKind.Submission : DeclarationKind.Script, name: fullName.Last(), arity: 0, modifiers: DeclarationModifiers.Internal | DeclarationModifiers.Partial | DeclarationModifiers.Sealed, declFlags: declFlags, syntaxReference: parentReference, nameLocation: new SourceLocation(parentReference), memberNames: memberNames, children: children, diagnostics: ImmutableArray<Diagnostic>.Empty); for (int i = fullName.Length - 2; i >= 0; i--) { decl = SingleNamespaceDeclaration.Create( name: fullName[i], hasUsings: false, hasExternAliases: false, syntaxReference: parentReference, nameLocation: new SourceLocation(parentReference), children: ImmutableArray.Create(decl), diagnostics: ImmutableArray<Diagnostic>.Empty); } return decl; } public override SingleNamespaceOrTypeDeclaration VisitCompilationUnit(CompilationUnitSyntax compilationUnit) { if (_syntaxTree.Options.Kind != SourceCodeKind.Regular) { return CreateScriptRootDeclaration(compilationUnit); } var children = VisitNamespaceChildren(compilationUnit, compilationUnit.Members, ((Syntax.InternalSyntax.CompilationUnitSyntax)(compilationUnit.Green)).Members); return CreateRootSingleNamespaceDeclaration(compilationUnit, children, isForScript: false); } private RootSingleNamespaceDeclaration CreateRootSingleNamespaceDeclaration(CompilationUnitSyntax compilationUnit, ImmutableArray<SingleNamespaceOrTypeDeclaration> children, bool isForScript) { bool hasUsings = false; bool hasGlobalUsings = false; bool reportedGlobalUsingOutOfOrder = false; var diagnostics = DiagnosticBag.GetInstance(); foreach (var directive in compilationUnit.Usings) { if (directive.GlobalKeyword.IsKind(SyntaxKind.GlobalKeyword)) { hasGlobalUsings = true; if (hasUsings && !reportedGlobalUsingOutOfOrder) { reportedGlobalUsingOutOfOrder = true; diagnostics.Add(ErrorCode.ERR_GlobalUsingOutOfOrder, directive.GlobalKeyword.GetLocation()); } } else { hasUsings = true; } } return new RootSingleNamespaceDeclaration( hasGlobalUsings: hasGlobalUsings, hasUsings: hasUsings, hasExternAliases: compilationUnit.Externs.Any(), treeNode: _syntaxTree.GetReference(compilationUnit), children: children, referenceDirectives: isForScript ? GetReferenceDirectives(compilationUnit) : ImmutableArray<ReferenceDirective>.Empty, hasAssemblyAttributes: compilationUnit.AttributeLists.Any(), diagnostics: diagnostics.ToReadOnlyAndFree()); } public override SingleNamespaceOrTypeDeclaration VisitFileScopedNamespaceDeclaration(FileScopedNamespaceDeclarationSyntax node) => this.VisitBaseNamespaceDeclaration(node); public override SingleNamespaceOrTypeDeclaration VisitNamespaceDeclaration(NamespaceDeclarationSyntax node) => this.VisitBaseNamespaceDeclaration(node); private SingleNamespaceDeclaration VisitBaseNamespaceDeclaration(BaseNamespaceDeclarationSyntax node) { var children = VisitNamespaceChildren(node, node.Members, ((Syntax.InternalSyntax.BaseNamespaceDeclarationSyntax)node.Green).Members); bool hasUsings = node.Usings.Any(); bool hasExterns = node.Externs.Any(); NameSyntax name = node.Name; CSharpSyntaxNode currentNode = node; QualifiedNameSyntax dotted; while ((dotted = name as QualifiedNameSyntax) != null) { var ns = SingleNamespaceDeclaration.Create( name: dotted.Right.Identifier.ValueText, hasUsings: hasUsings, hasExternAliases: hasExterns, syntaxReference: _syntaxTree.GetReference(currentNode), nameLocation: new SourceLocation(dotted.Right), children: children, diagnostics: ImmutableArray<Diagnostic>.Empty); var nsDeclaration = new[] { ns }; children = nsDeclaration.AsImmutableOrNull<SingleNamespaceOrTypeDeclaration>(); currentNode = name = dotted.Left; hasUsings = false; hasExterns = false; } var diagnostics = DiagnosticBag.GetInstance(); if (node is FileScopedNamespaceDeclarationSyntax) { if (node.Parent is FileScopedNamespaceDeclarationSyntax) { // Happens when user writes: // namespace A.B; // namespace X.Y; diagnostics.Add(ErrorCode.ERR_MultipleFileScopedNamespace, node.Name.GetLocation()); } else if (node.Parent is NamespaceDeclarationSyntax) { // Happens with: // // namespace A.B // { // namespace X.Y; diagnostics.Add(ErrorCode.ERR_FileScopedAndNormalNamespace, node.Name.GetLocation()); } else { // Happens with cases like: // // namespace A.B { } // namespace X.Y; // // or even // // class C { } // namespace X.Y; Debug.Assert(node.Parent is CompilationUnitSyntax); var compilationUnit = (CompilationUnitSyntax)node.Parent; if (node != compilationUnit.Members[0]) { diagnostics.Add(ErrorCode.ERR_FileScopedNamespaceNotBeforeAllMembers, node.Name.GetLocation()); } } } else { Debug.Assert(node is NamespaceDeclarationSyntax); // namespace X.Y; // namespace A.B { } if (node.Parent is FileScopedNamespaceDeclarationSyntax) { diagnostics.Add(ErrorCode.ERR_FileScopedAndNormalNamespace, node.Name.GetLocation()); } } if (ContainsGeneric(node.Name)) { // We're not allowed to have generics. diagnostics.Add(ErrorCode.ERR_UnexpectedGenericName, node.Name.GetLocation()); } if (ContainsAlias(node.Name)) { diagnostics.Add(ErrorCode.ERR_UnexpectedAliasedName, node.Name.GetLocation()); } if (node.AttributeLists.Count > 0) { diagnostics.Add(ErrorCode.ERR_BadModifiersOnNamespace, node.AttributeLists[0].GetLocation()); } if (node.Modifiers.Count > 0) { diagnostics.Add(ErrorCode.ERR_BadModifiersOnNamespace, node.Modifiers[0].GetLocation()); } foreach (var directive in node.Usings) { if (directive.GlobalKeyword.IsKind(SyntaxKind.GlobalKeyword)) { diagnostics.Add(ErrorCode.ERR_GlobalUsingInNamespace, directive.GlobalKeyword.GetLocation()); break; } } // NOTE: *Something* has to happen for alias-qualified names. It turns out that we // just grab the part after the colons (via GetUnqualifiedName, below). This logic // must be kept in sync with NamespaceSymbol.GetNestedNamespace. return SingleNamespaceDeclaration.Create( name: name.GetUnqualifiedName().Identifier.ValueText, hasUsings: hasUsings, hasExternAliases: hasExterns, syntaxReference: _syntaxTree.GetReference(currentNode), nameLocation: new SourceLocation(name), children: children, diagnostics: diagnostics.ToReadOnlyAndFree()); } private static bool ContainsAlias(NameSyntax name) { switch (name.Kind()) { case SyntaxKind.GenericName: return false; case SyntaxKind.AliasQualifiedName: return true; case SyntaxKind.QualifiedName: var qualifiedName = (QualifiedNameSyntax)name; return ContainsAlias(qualifiedName.Left); } return false; } private static bool ContainsGeneric(NameSyntax name) { switch (name.Kind()) { case SyntaxKind.GenericName: return true; case SyntaxKind.AliasQualifiedName: return ContainsGeneric(((AliasQualifiedNameSyntax)name).Name); case SyntaxKind.QualifiedName: var qualifiedName = (QualifiedNameSyntax)name; return ContainsGeneric(qualifiedName.Left) || ContainsGeneric(qualifiedName.Right); } return false; } public override SingleNamespaceOrTypeDeclaration VisitClassDeclaration(ClassDeclarationSyntax node) { return VisitTypeDeclaration(node, DeclarationKind.Class); } public override SingleNamespaceOrTypeDeclaration VisitStructDeclaration(StructDeclarationSyntax node) { return VisitTypeDeclaration(node, DeclarationKind.Struct); } public override SingleNamespaceOrTypeDeclaration VisitInterfaceDeclaration(InterfaceDeclarationSyntax node) { return VisitTypeDeclaration(node, DeclarationKind.Interface); } public override SingleNamespaceOrTypeDeclaration VisitRecordDeclaration(RecordDeclarationSyntax node) { var declarationKind = node.Kind() switch { SyntaxKind.RecordDeclaration => DeclarationKind.Record, SyntaxKind.RecordStructDeclaration => DeclarationKind.RecordStruct, _ => throw ExceptionUtilities.UnexpectedValue(node.Kind()) }; return VisitTypeDeclaration(node, declarationKind); } private SingleNamespaceOrTypeDeclaration VisitTypeDeclaration(TypeDeclarationSyntax node, DeclarationKind kind) { SingleTypeDeclaration.TypeDeclarationFlags declFlags = node.AttributeLists.Any() ? SingleTypeDeclaration.TypeDeclarationFlags.HasAnyAttributes : SingleTypeDeclaration.TypeDeclarationFlags.None; if (node.BaseList != null) { declFlags |= SingleTypeDeclaration.TypeDeclarationFlags.HasBaseDeclarations; } var diagnostics = DiagnosticBag.GetInstance(); if (node.Arity == 0) { Symbol.ReportErrorIfHasConstraints(node.ConstraintClauses, diagnostics); } var memberNames = GetNonTypeMemberNames(((Syntax.InternalSyntax.TypeDeclarationSyntax)(node.Green)).Members, ref declFlags); // A record with parameters at least has a primary constructor if (((declFlags & SingleTypeDeclaration.TypeDeclarationFlags.HasAnyNontypeMembers) == 0) && node is RecordDeclarationSyntax { ParameterList: { } }) { declFlags |= SingleTypeDeclaration.TypeDeclarationFlags.HasAnyNontypeMembers; } var modifiers = node.Modifiers.ToDeclarationModifiers(diagnostics: diagnostics); return new SingleTypeDeclaration( kind: kind, name: node.Identifier.ValueText, modifiers: modifiers, arity: node.Arity, declFlags: declFlags, syntaxReference: _syntaxTree.GetReference(node), nameLocation: new SourceLocation(node.Identifier), memberNames: memberNames, children: VisitTypeChildren(node), diagnostics: diagnostics.ToReadOnlyAndFree()); } private ImmutableArray<SingleTypeDeclaration> VisitTypeChildren(TypeDeclarationSyntax node) { if (node.Members.Count == 0) { return ImmutableArray<SingleTypeDeclaration>.Empty; } var children = ArrayBuilder<SingleTypeDeclaration>.GetInstance(); foreach (var member in node.Members) { var typeDecl = Visit(member) as SingleTypeDeclaration; if (typeDecl != null) { children.Add(typeDecl); } } return children.ToImmutableAndFree(); } public override SingleNamespaceOrTypeDeclaration VisitDelegateDeclaration(DelegateDeclarationSyntax node) { var declFlags = node.AttributeLists.Any() ? SingleTypeDeclaration.TypeDeclarationFlags.HasAnyAttributes : SingleTypeDeclaration.TypeDeclarationFlags.None; var diagnostics = DiagnosticBag.GetInstance(); if (node.Arity == 0) { Symbol.ReportErrorIfHasConstraints(node.ConstraintClauses, diagnostics); } declFlags |= SingleTypeDeclaration.TypeDeclarationFlags.HasAnyNontypeMembers; var modifiers = node.Modifiers.ToDeclarationModifiers(diagnostics: diagnostics); return new SingleTypeDeclaration( kind: DeclarationKind.Delegate, name: node.Identifier.ValueText, modifiers: modifiers, declFlags: declFlags, arity: node.Arity, syntaxReference: _syntaxTree.GetReference(node), nameLocation: new SourceLocation(node.Identifier), memberNames: ImmutableSegmentedDictionary<string, VoidResult>.Empty, children: ImmutableArray<SingleTypeDeclaration>.Empty, diagnostics: diagnostics.ToReadOnlyAndFree()); } public override SingleNamespaceOrTypeDeclaration VisitEnumDeclaration(EnumDeclarationSyntax node) { var members = node.Members; SingleTypeDeclaration.TypeDeclarationFlags declFlags = node.AttributeLists.Any() ? SingleTypeDeclaration.TypeDeclarationFlags.HasAnyAttributes : SingleTypeDeclaration.TypeDeclarationFlags.None; if (node.BaseList != null) { declFlags |= SingleTypeDeclaration.TypeDeclarationFlags.HasBaseDeclarations; } ImmutableSegmentedDictionary<string, VoidResult> memberNames = GetEnumMemberNames(members, ref declFlags); var diagnostics = DiagnosticBag.GetInstance(); var modifiers = node.Modifiers.ToDeclarationModifiers(diagnostics: diagnostics); return new SingleTypeDeclaration( kind: DeclarationKind.Enum, name: node.Identifier.ValueText, arity: 0, modifiers: modifiers, declFlags: declFlags, syntaxReference: _syntaxTree.GetReference(node), nameLocation: new SourceLocation(node.Identifier), memberNames: memberNames, children: ImmutableArray<SingleTypeDeclaration>.Empty, diagnostics: diagnostics.ToReadOnlyAndFree()); } private static readonly ObjectPool<ImmutableSegmentedDictionary<string, VoidResult>.Builder> s_memberNameBuilderPool = new ObjectPool<ImmutableSegmentedDictionary<string, VoidResult>.Builder>(() => ImmutableSegmentedDictionary.CreateBuilder<string, VoidResult>()); private static ImmutableSegmentedDictionary<string, VoidResult> ToImmutableAndFree(ImmutableSegmentedDictionary<string, VoidResult>.Builder builder) { var result = builder.ToImmutable(); builder.Clear(); s_memberNameBuilderPool.Free(builder); return result; } private static ImmutableSegmentedDictionary<string, VoidResult> GetEnumMemberNames(SeparatedSyntaxList<EnumMemberDeclarationSyntax> members, ref SingleTypeDeclaration.TypeDeclarationFlags declFlags) { var cnt = members.Count; var memberNamesBuilder = s_memberNameBuilderPool.Allocate(); if (cnt != 0) { declFlags |= SingleTypeDeclaration.TypeDeclarationFlags.HasAnyNontypeMembers; } bool anyMemberHasAttributes = false; foreach (var member in members) { memberNamesBuilder.TryAdd(member.Identifier.ValueText); if (!anyMemberHasAttributes && member.AttributeLists.Any()) { anyMemberHasAttributes = true; } } if (anyMemberHasAttributes) { declFlags |= SingleTypeDeclaration.TypeDeclarationFlags.AnyMemberHasAttributes; } return ToImmutableAndFree(memberNamesBuilder); } private static ImmutableSegmentedDictionary<string, VoidResult> GetNonTypeMemberNames( CoreInternalSyntax.SyntaxList<Syntax.InternalSyntax.MemberDeclarationSyntax> members, ref SingleTypeDeclaration.TypeDeclarationFlags declFlags, bool skipGlobalStatements = false) { bool anyMethodHadExtensionSyntax = false; bool anyMemberHasAttributes = false; bool anyNonTypeMembers = false; var memberNameBuilder = s_memberNameBuilderPool.Allocate(); foreach (var member in members) { AddNonTypeMemberNames(member, memberNameBuilder, ref anyNonTypeMembers, skipGlobalStatements); // Check to see if any method contains a 'this' modifier on its first parameter. // This data is used to determine if a type needs to have its members materialized // as part of extension method lookup. if (!anyMethodHadExtensionSyntax && CheckMethodMemberForExtensionSyntax(member)) { anyMethodHadExtensionSyntax = true; } if (!anyMemberHasAttributes && CheckMemberForAttributes(member)) { anyMemberHasAttributes = true; } } if (anyMethodHadExtensionSyntax) { declFlags |= SingleTypeDeclaration.TypeDeclarationFlags.AnyMemberHasExtensionMethodSyntax; } if (anyMemberHasAttributes) { declFlags |= SingleTypeDeclaration.TypeDeclarationFlags.AnyMemberHasAttributes; } if (anyNonTypeMembers) { declFlags |= SingleTypeDeclaration.TypeDeclarationFlags.HasAnyNontypeMembers; } return ToImmutableAndFree(memberNameBuilder); } private static bool CheckMethodMemberForExtensionSyntax(Syntax.InternalSyntax.CSharpSyntaxNode member) { if (member.Kind == SyntaxKind.MethodDeclaration) { var methodDecl = (Syntax.InternalSyntax.MethodDeclarationSyntax)member; var paramList = methodDecl.parameterList; if (paramList != null) { var parameters = paramList.Parameters; if (parameters.Count != 0) { var firstParameter = parameters[0]; foreach (var modifier in firstParameter.Modifiers) { if (modifier.Kind == SyntaxKind.ThisKeyword) { return true; } } } } } return false; } private static bool CheckMemberForAttributes(Syntax.InternalSyntax.CSharpSyntaxNode member) { switch (member.Kind) { case SyntaxKind.CompilationUnit: return (((Syntax.InternalSyntax.CompilationUnitSyntax)member).AttributeLists).Any(); case SyntaxKind.ClassDeclaration: case SyntaxKind.StructDeclaration: case SyntaxKind.InterfaceDeclaration: case SyntaxKind.EnumDeclaration: case SyntaxKind.RecordDeclaration: case SyntaxKind.RecordStructDeclaration: return (((Syntax.InternalSyntax.BaseTypeDeclarationSyntax)member).AttributeLists).Any(); case SyntaxKind.DelegateDeclaration: return (((Syntax.InternalSyntax.DelegateDeclarationSyntax)member).AttributeLists).Any(); case SyntaxKind.FieldDeclaration: case SyntaxKind.EventFieldDeclaration: return (((Syntax.InternalSyntax.BaseFieldDeclarationSyntax)member).AttributeLists).Any(); case SyntaxKind.MethodDeclaration: case SyntaxKind.OperatorDeclaration: case SyntaxKind.ConversionOperatorDeclaration: case SyntaxKind.ConstructorDeclaration: case SyntaxKind.DestructorDeclaration: return (((Syntax.InternalSyntax.BaseMethodDeclarationSyntax)member).AttributeLists).Any(); case SyntaxKind.PropertyDeclaration: case SyntaxKind.EventDeclaration: case SyntaxKind.IndexerDeclaration: var baseProp = (Syntax.InternalSyntax.BasePropertyDeclarationSyntax)member; bool hasAttributes = baseProp.AttributeLists.Any(); if (!hasAttributes && baseProp.AccessorList != null) { foreach (var accessor in baseProp.AccessorList.Accessors) { hasAttributes |= accessor.AttributeLists.Any(); } } return hasAttributes; } return false; } private static void AddNonTypeMemberNames( Syntax.InternalSyntax.CSharpSyntaxNode member, ImmutableSegmentedDictionary<string, VoidResult>.Builder set, ref bool anyNonTypeMembers, bool skipGlobalStatements) { switch (member.Kind) { case SyntaxKind.FieldDeclaration: anyNonTypeMembers = true; CodeAnalysis.Syntax.InternalSyntax.SeparatedSyntaxList<Syntax.InternalSyntax.VariableDeclaratorSyntax> fieldDeclarators = ((Syntax.InternalSyntax.FieldDeclarationSyntax)member).Declaration.Variables; int numFieldDeclarators = fieldDeclarators.Count; for (int i = 0; i < numFieldDeclarators; i++) { set.TryAdd(fieldDeclarators[i].Identifier.ValueText); } break; case SyntaxKind.EventFieldDeclaration: anyNonTypeMembers = true; CoreInternalSyntax.SeparatedSyntaxList<Syntax.InternalSyntax.VariableDeclaratorSyntax> eventDeclarators = ((Syntax.InternalSyntax.EventFieldDeclarationSyntax)member).Declaration.Variables; int numEventDeclarators = eventDeclarators.Count; for (int i = 0; i < numEventDeclarators; i++) { set.TryAdd(eventDeclarators[i].Identifier.ValueText); } break; case SyntaxKind.MethodDeclaration: anyNonTypeMembers = true; // Member names are exposed via NamedTypeSymbol.MemberNames and are used primarily // as an acid test to determine whether a more in-depth search of a type is worthwhile. // We decided that it was reasonable to exclude explicit interface implementations // from the list of member names. var methodDecl = (Syntax.InternalSyntax.MethodDeclarationSyntax)member; if (methodDecl.ExplicitInterfaceSpecifier == null) { set.TryAdd(methodDecl.Identifier.ValueText); } break; case SyntaxKind.PropertyDeclaration: anyNonTypeMembers = true; // Handle in the same way as explicit method implementations var propertyDecl = (Syntax.InternalSyntax.PropertyDeclarationSyntax)member; if (propertyDecl.ExplicitInterfaceSpecifier == null) { set.TryAdd(propertyDecl.Identifier.ValueText); } break; case SyntaxKind.EventDeclaration: anyNonTypeMembers = true; // Handle in the same way as explicit method implementations var eventDecl = (Syntax.InternalSyntax.EventDeclarationSyntax)member; if (eventDecl.ExplicitInterfaceSpecifier == null) { set.TryAdd(eventDecl.Identifier.ValueText); } break; case SyntaxKind.ConstructorDeclaration: anyNonTypeMembers = true; set.TryAdd(((Syntax.InternalSyntax.ConstructorDeclarationSyntax)member).Modifiers.Any((int)SyntaxKind.StaticKeyword) ? WellKnownMemberNames.StaticConstructorName : WellKnownMemberNames.InstanceConstructorName); break; case SyntaxKind.DestructorDeclaration: anyNonTypeMembers = true; set.TryAdd(WellKnownMemberNames.DestructorName); break; case SyntaxKind.IndexerDeclaration: anyNonTypeMembers = true; set.TryAdd(WellKnownMemberNames.Indexer); break; case SyntaxKind.OperatorDeclaration: { anyNonTypeMembers = true; // Handle in the same way as explicit method implementations var opDecl = (Syntax.InternalSyntax.OperatorDeclarationSyntax)member; if (opDecl.ExplicitInterfaceSpecifier == null) { var name = OperatorFacts.OperatorNameFromDeclaration(opDecl); set.TryAdd(name); } } break; case SyntaxKind.ConversionOperatorDeclaration: { anyNonTypeMembers = true; // Handle in the same way as explicit method implementations var opDecl = (Syntax.InternalSyntax.ConversionOperatorDeclarationSyntax)member; if (opDecl.ExplicitInterfaceSpecifier == null) { var name = OperatorFacts.OperatorNameFromDeclaration(opDecl); set.TryAdd(name); } } break; case SyntaxKind.GlobalStatement: if (!skipGlobalStatements) { anyNonTypeMembers = true; } break; } } } }
-1
dotnet/roslyn
55,430
Fix LSP semantic tokens algorithm
This PR primarily accomplishes two tasks: 1) Overhauls the existing LSP semantic tokens edits processing algorithm to align with [Razor's](https://github.com/dotnet/aspnetcore-tooling/blob/main/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/Semantic/Services/SemanticTokensEditsDiffer.cs) (shoutout to Ryan and the rest of the Razor team for writing the original 😄). The main change here is going from calculating edits per token (i.e. five ints) to per int. The updated algorithm is much more efficient than our previous algorithm, and returns less edits back to the LSP client. 2) The interpretation of Roslyn's LongestCommonSubstring algorithm, which we use to calculate raw edits, was missing a critical piece. Namely, for insertions, we need to keep track of _where_ we should be inserting into the original token set. We don't keep track of this in the existing implementation, resulting in bugs such as #54671. Resolves #54671
allisonchou
2021-08-05T06:06:43Z
2021-08-06T23:44:44Z
b9200d03a76c74d404040d44b9bbe12b1d0a8ef2
f300a818940ea1acef66c946cfa83756729d5e59
Fix LSP semantic tokens algorithm. This PR primarily accomplishes two tasks: 1) Overhauls the existing LSP semantic tokens edits processing algorithm to align with [Razor's](https://github.com/dotnet/aspnetcore-tooling/blob/main/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/Semantic/Services/SemanticTokensEditsDiffer.cs) (shoutout to Ryan and the rest of the Razor team for writing the original 😄). The main change here is going from calculating edits per token (i.e. five ints) to per int. The updated algorithm is much more efficient than our previous algorithm, and returns less edits back to the LSP client. 2) The interpretation of Roslyn's LongestCommonSubstring algorithm, which we use to calculate raw edits, was missing a critical piece. Namely, for insertions, we need to keep track of _where_ we should be inserting into the original token set. We don't keep track of this in the existing implementation, resulting in bugs such as #54671. Resolves #54671
./src/EditorFeatures/TestUtilities/BraceHighlighting/AbstractBraceHighlightingTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Linq; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Editor.Implementation.BraceMatching; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.Editor.Tagging; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Microsoft.CodeAnalysis.Shared.TestHooks; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.Text; using Microsoft.CodeAnalysis.Text.Shared.Extensions; using Microsoft.VisualStudio.Text; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.UnitTests.BraceHighlighting { [UseExportProvider] public abstract class AbstractBraceHighlightingTests { protected async Task TestBraceHighlightingAsync( string markup, ParseOptions options = null, bool swapAnglesWithBrackets = false) { MarkupTestFile.GetPositionAndSpans(markup, out var text, out int cursorPosition, out var expectedSpans); // needed because markup test file can't support [|[|] to indicate selecting // just an open bracket. if (swapAnglesWithBrackets) { text = text.Replace("<", "[").Replace(">", "]"); } using (var workspace = CreateWorkspace(text, options)) { WpfTestRunner.RequireWpfFact($"{nameof(AbstractBraceHighlightingTests)}.{nameof(TestBraceHighlightingAsync)} creates asynchronous taggers"); var provider = new BraceHighlightingViewTaggerProvider( workspace.GetService<IThreadingContext>(), GetBraceMatchingService(workspace), AsynchronousOperationListenerProvider.NullProvider); var testDocument = workspace.Documents.First(); var buffer = testDocument.GetTextBuffer(); var document = buffer.CurrentSnapshot.GetRelatedDocumentsWithChanges().FirstOrDefault(); var context = new TaggerContext<BraceHighlightTag>( document, buffer.CurrentSnapshot, new SnapshotPoint(buffer.CurrentSnapshot, cursorPosition)); await provider.GetTestAccessor().ProduceTagsAsync(context); var expectedHighlights = expectedSpans.Select(ts => ts.ToSpan()).OrderBy(s => s.Start).ToList(); var actualHighlights = context.tagSpans.Select(ts => ts.Span.Span).OrderBy(s => s.Start).ToList(); Assert.Equal(expectedHighlights, actualHighlights); } } internal virtual IBraceMatchingService GetBraceMatchingService(TestWorkspace workspace) => workspace.GetService<IBraceMatchingService>(); protected abstract TestWorkspace CreateWorkspace(string markup, ParseOptions options); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Linq; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Editor.Implementation.BraceMatching; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.Editor.Tagging; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Microsoft.CodeAnalysis.Shared.TestHooks; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.Text; using Microsoft.CodeAnalysis.Text.Shared.Extensions; using Microsoft.VisualStudio.Text; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.UnitTests.BraceHighlighting { [UseExportProvider] public abstract class AbstractBraceHighlightingTests { protected async Task TestBraceHighlightingAsync( string markup, ParseOptions options = null, bool swapAnglesWithBrackets = false) { MarkupTestFile.GetPositionAndSpans(markup, out var text, out int cursorPosition, out var expectedSpans); // needed because markup test file can't support [|[|] to indicate selecting // just an open bracket. if (swapAnglesWithBrackets) { text = text.Replace("<", "[").Replace(">", "]"); } using (var workspace = CreateWorkspace(text, options)) { WpfTestRunner.RequireWpfFact($"{nameof(AbstractBraceHighlightingTests)}.{nameof(TestBraceHighlightingAsync)} creates asynchronous taggers"); var provider = new BraceHighlightingViewTaggerProvider( workspace.GetService<IThreadingContext>(), GetBraceMatchingService(workspace), AsynchronousOperationListenerProvider.NullProvider); var testDocument = workspace.Documents.First(); var buffer = testDocument.GetTextBuffer(); var document = buffer.CurrentSnapshot.GetRelatedDocumentsWithChanges().FirstOrDefault(); var context = new TaggerContext<BraceHighlightTag>( document, buffer.CurrentSnapshot, new SnapshotPoint(buffer.CurrentSnapshot, cursorPosition)); await provider.GetTestAccessor().ProduceTagsAsync(context); var expectedHighlights = expectedSpans.Select(ts => ts.ToSpan()).OrderBy(s => s.Start).ToList(); var actualHighlights = context.tagSpans.Select(ts => ts.Span.Span).OrderBy(s => s.Start).ToList(); Assert.Equal(expectedHighlights, actualHighlights); } } internal virtual IBraceMatchingService GetBraceMatchingService(TestWorkspace workspace) => workspace.GetService<IBraceMatchingService>(); protected abstract TestWorkspace CreateWorkspace(string markup, ParseOptions options); } }
-1
dotnet/roslyn
55,430
Fix LSP semantic tokens algorithm
This PR primarily accomplishes two tasks: 1) Overhauls the existing LSP semantic tokens edits processing algorithm to align with [Razor's](https://github.com/dotnet/aspnetcore-tooling/blob/main/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/Semantic/Services/SemanticTokensEditsDiffer.cs) (shoutout to Ryan and the rest of the Razor team for writing the original 😄). The main change here is going from calculating edits per token (i.e. five ints) to per int. The updated algorithm is much more efficient than our previous algorithm, and returns less edits back to the LSP client. 2) The interpretation of Roslyn's LongestCommonSubstring algorithm, which we use to calculate raw edits, was missing a critical piece. Namely, for insertions, we need to keep track of _where_ we should be inserting into the original token set. We don't keep track of this in the existing implementation, resulting in bugs such as #54671. Resolves #54671
allisonchou
2021-08-05T06:06:43Z
2021-08-06T23:44:44Z
b9200d03a76c74d404040d44b9bbe12b1d0a8ef2
f300a818940ea1acef66c946cfa83756729d5e59
Fix LSP semantic tokens algorithm. This PR primarily accomplishes two tasks: 1) Overhauls the existing LSP semantic tokens edits processing algorithm to align with [Razor's](https://github.com/dotnet/aspnetcore-tooling/blob/main/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/Semantic/Services/SemanticTokensEditsDiffer.cs) (shoutout to Ryan and the rest of the Razor team for writing the original 😄). The main change here is going from calculating edits per token (i.e. five ints) to per int. The updated algorithm is much more efficient than our previous algorithm, and returns less edits back to the LSP client. 2) The interpretation of Roslyn's LongestCommonSubstring algorithm, which we use to calculate raw edits, was missing a critical piece. Namely, for insertions, we need to keep track of _where_ we should be inserting into the original token set. We don't keep track of this in the existing implementation, resulting in bugs such as #54671. Resolves #54671
./src/Analyzers/Core/Analyzers/PopulateSwitch/AbstractPopulateSwitchExpressionDiagnosticAnalyzer.cs
// Licensed to the .NET Foundation under one or more agreements. // 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 Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Operations; namespace Microsoft.CodeAnalysis.PopulateSwitch { internal abstract class AbstractPopulateSwitchExpressionDiagnosticAnalyzer<TSwitchSyntax> : AbstractPopulateSwitchDiagnosticAnalyzer<ISwitchExpressionOperation, TSwitchSyntax> where TSwitchSyntax : SyntaxNode { protected AbstractPopulateSwitchExpressionDiagnosticAnalyzer() : base(IDEDiagnosticIds.PopulateSwitchExpressionDiagnosticId, EnforceOnBuildValues.PopulateSwitchExpression) { } protected sealed override OperationKind OperationKind => OperationKind.SwitchExpression; protected sealed override ICollection<ISymbol> GetMissingEnumMembers(ISwitchExpressionOperation operation) => PopulateSwitchExpressionHelpers.GetMissingEnumMembers(operation); protected sealed override bool HasDefaultCase(ISwitchExpressionOperation operation) => PopulateSwitchExpressionHelpers.HasDefaultCase(operation); } }
// Licensed to the .NET Foundation under one or more agreements. // 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 Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Operations; namespace Microsoft.CodeAnalysis.PopulateSwitch { internal abstract class AbstractPopulateSwitchExpressionDiagnosticAnalyzer<TSwitchSyntax> : AbstractPopulateSwitchDiagnosticAnalyzer<ISwitchExpressionOperation, TSwitchSyntax> where TSwitchSyntax : SyntaxNode { protected AbstractPopulateSwitchExpressionDiagnosticAnalyzer() : base(IDEDiagnosticIds.PopulateSwitchExpressionDiagnosticId, EnforceOnBuildValues.PopulateSwitchExpression) { } protected sealed override OperationKind OperationKind => OperationKind.SwitchExpression; protected sealed override ICollection<ISymbol> GetMissingEnumMembers(ISwitchExpressionOperation operation) => PopulateSwitchExpressionHelpers.GetMissingEnumMembers(operation); protected sealed override bool HasDefaultCase(ISwitchExpressionOperation operation) => PopulateSwitchExpressionHelpers.HasDefaultCase(operation); } }
-1
dotnet/roslyn
55,430
Fix LSP semantic tokens algorithm
This PR primarily accomplishes two tasks: 1) Overhauls the existing LSP semantic tokens edits processing algorithm to align with [Razor's](https://github.com/dotnet/aspnetcore-tooling/blob/main/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/Semantic/Services/SemanticTokensEditsDiffer.cs) (shoutout to Ryan and the rest of the Razor team for writing the original 😄). The main change here is going from calculating edits per token (i.e. five ints) to per int. The updated algorithm is much more efficient than our previous algorithm, and returns less edits back to the LSP client. 2) The interpretation of Roslyn's LongestCommonSubstring algorithm, which we use to calculate raw edits, was missing a critical piece. Namely, for insertions, we need to keep track of _where_ we should be inserting into the original token set. We don't keep track of this in the existing implementation, resulting in bugs such as #54671. Resolves #54671
allisonchou
2021-08-05T06:06:43Z
2021-08-06T23:44:44Z
b9200d03a76c74d404040d44b9bbe12b1d0a8ef2
f300a818940ea1acef66c946cfa83756729d5e59
Fix LSP semantic tokens algorithm. This PR primarily accomplishes two tasks: 1) Overhauls the existing LSP semantic tokens edits processing algorithm to align with [Razor's](https://github.com/dotnet/aspnetcore-tooling/blob/main/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/Semantic/Services/SemanticTokensEditsDiffer.cs) (shoutout to Ryan and the rest of the Razor team for writing the original 😄). The main change here is going from calculating edits per token (i.e. five ints) to per int. The updated algorithm is much more efficient than our previous algorithm, and returns less edits back to the LSP client. 2) The interpretation of Roslyn's LongestCommonSubstring algorithm, which we use to calculate raw edits, was missing a critical piece. Namely, for insertions, we need to keep track of _where_ we should be inserting into the original token set. We don't keep track of this in the existing implementation, resulting in bugs such as #54671. Resolves #54671
./src/EditorFeatures/CSharpTest/EmbeddedLanguages/RegularExpressions/CSharpRegexParserTests_ReferenceTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Text.RegularExpressions; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests.EmbeddedLanguages.RegularExpressions { // All these tests came from the example at: // https://docs.microsoft.com/en-us/dotnet/standard/base-types/regular-expression-language-quick-reference public partial class CSharpRegexParserTests { [Fact] public void ReferenceTest0() { Test(@"@""[aeiou]""", @"<Tree> <CompilationUnit> <Sequence> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <Text> <TextToken>aeiou</TextToken> </Text> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..17)"" Text=""[aeiou]"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest1() { Test(@"@""(?<duplicateWord>\w+)\s\k<duplicateWord>\W(?<nextWord>\w+)""", @"<Tree> <CompilationUnit> <Sequence> <CaptureGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <CaptureNameToken value=""duplicateWord"">duplicateWord</CaptureNameToken> <GreaterThanToken>&gt;</GreaterThanToken> <Sequence> <OneOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>w</TextToken> </CharacterClassEscape> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> </Sequence> <CloseParenToken>)</CloseParenToken> </CaptureGrouping> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>s</TextToken> </CharacterClassEscape> <KCaptureEscape> <BackslashToken>\</BackslashToken> <TextToken>k</TextToken> <LessThanToken>&lt;</LessThanToken> <CaptureNameToken value=""duplicateWord"">duplicateWord</CaptureNameToken> <GreaterThanToken>&gt;</GreaterThanToken> </KCaptureEscape> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>W</TextToken> </CharacterClassEscape> <CaptureGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <CaptureNameToken value=""nextWord"">nextWord</CaptureNameToken> <GreaterThanToken>&gt;</GreaterThanToken> <Sequence> <OneOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>w</TextToken> </CharacterClassEscape> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> </Sequence> <CloseParenToken>)</CloseParenToken> </CaptureGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..68)"" Text=""(?&lt;duplicateWord&gt;\w+)\s\k&lt;duplicateWord&gt;\W(?&lt;nextWord&gt;\w+)"" /> <Capture Name=""1"" Span=""[10..31)"" Text=""(?&lt;duplicateWord&gt;\w+)"" /> <Capture Name=""2"" Span=""[52..68)"" Text=""(?&lt;nextWord&gt;\w+)"" /> <Capture Name=""duplicateWord"" Span=""[10..31)"" Text=""(?&lt;duplicateWord&gt;\w+)"" /> <Capture Name=""nextWord"" Span=""[52..68)"" Text=""(?&lt;nextWord&gt;\w+)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest2() { Test(@"@""((?<One>abc)\d+)?(?<Two>xyz)(.*)""", @"<Tree> <CompilationUnit> <Sequence> <ZeroOrOneQuantifier> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <CaptureGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <CaptureNameToken value=""One"">One</CaptureNameToken> <GreaterThanToken>&gt;</GreaterThanToken> <Sequence> <Text> <TextToken>abc</TextToken> </Text> </Sequence> <CloseParenToken>)</CloseParenToken> </CaptureGrouping> <OneOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>d</TextToken> </CharacterClassEscape> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <QuestionToken>?</QuestionToken> </ZeroOrOneQuantifier> <CaptureGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <CaptureNameToken value=""Two"">Two</CaptureNameToken> <GreaterThanToken>&gt;</GreaterThanToken> <Sequence> <Text> <TextToken>xyz</TextToken> </Text> </Sequence> <CloseParenToken>)</CloseParenToken> </CaptureGrouping> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <ZeroOrMoreQuantifier> <Wildcard> <DotToken>.</DotToken> </Wildcard> <AsteriskToken>*</AsteriskToken> </ZeroOrMoreQuantifier> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..42)"" Text=""((?&lt;One&gt;abc)\d+)?(?&lt;Two&gt;xyz)(.*)"" /> <Capture Name=""1"" Span=""[10..26)"" Text=""((?&lt;One&gt;abc)\d+)"" /> <Capture Name=""2"" Span=""[38..42)"" Text=""(.*)"" /> <Capture Name=""3"" Span=""[11..22)"" Text=""(?&lt;One&gt;abc)"" /> <Capture Name=""4"" Span=""[27..38)"" Text=""(?&lt;Two&gt;xyz)"" /> <Capture Name=""One"" Span=""[11..22)"" Text=""(?&lt;One&gt;abc)"" /> <Capture Name=""Two"" Span=""[27..38)"" Text=""(?&lt;Two&gt;xyz)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest3() { Test(@"@""(\w+)\s(\1)""", @"<Tree> <CompilationUnit> <Sequence> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <OneOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>w</TextToken> </CharacterClassEscape> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>s</TextToken> </CharacterClassEscape> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <BackreferenceEscape> <BackslashToken>\</BackslashToken> <NumberToken value=""1"">1</NumberToken> </BackreferenceEscape> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..21)"" Text=""(\w+)\s(\1)"" /> <Capture Name=""1"" Span=""[10..15)"" Text=""(\w+)"" /> <Capture Name=""2"" Span=""[17..21)"" Text=""(\1)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest4() { Test(@"@""\Bqu\w+""", @"<Tree> <CompilationUnit> <Sequence> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>B</TextToken> </AnchorEscape> <Text> <TextToken>qu</TextToken> </Text> <OneOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>w</TextToken> </CharacterClassEscape> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..17)"" Text=""\Bqu\w+"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest5() { Test(@"@""\bare\w*\b""", @"<Tree> <CompilationUnit> <Sequence> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>b</TextToken> </AnchorEscape> <Text> <TextToken>are</TextToken> </Text> <ZeroOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>w</TextToken> </CharacterClassEscape> <AsteriskToken>*</AsteriskToken> </ZeroOrMoreQuantifier> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>b</TextToken> </AnchorEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..20)"" Text=""\bare\w*\b"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest6() { Test(@"@""\G(\w+\s?\w*),?""", @"<Tree> <CompilationUnit> <Sequence> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>G</TextToken> </AnchorEscape> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <OneOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>w</TextToken> </CharacterClassEscape> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> <ZeroOrOneQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>s</TextToken> </CharacterClassEscape> <QuestionToken>?</QuestionToken> </ZeroOrOneQuantifier> <ZeroOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>w</TextToken> </CharacterClassEscape> <AsteriskToken>*</AsteriskToken> </ZeroOrMoreQuantifier> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <ZeroOrOneQuantifier> <Text> <TextToken>,</TextToken> </Text> <QuestionToken>?</QuestionToken> </ZeroOrOneQuantifier> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..25)"" Text=""\G(\w+\s?\w*),?"" /> <Capture Name=""1"" Span=""[12..23)"" Text=""(\w+\s?\w*)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest7() { Test(@"@""\D+(?<digit>\d+)\D+(?<digit>\d+)?""", @"<Tree> <CompilationUnit> <Sequence> <OneOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>D</TextToken> </CharacterClassEscape> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> <CaptureGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <CaptureNameToken value=""digit"">digit</CaptureNameToken> <GreaterThanToken>&gt;</GreaterThanToken> <Sequence> <OneOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>d</TextToken> </CharacterClassEscape> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> </Sequence> <CloseParenToken>)</CloseParenToken> </CaptureGrouping> <OneOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>D</TextToken> </CharacterClassEscape> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> <ZeroOrOneQuantifier> <CaptureGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <CaptureNameToken value=""digit"">digit</CaptureNameToken> <GreaterThanToken>&gt;</GreaterThanToken> <Sequence> <OneOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>d</TextToken> </CharacterClassEscape> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> </Sequence> <CloseParenToken>)</CloseParenToken> </CaptureGrouping> <QuestionToken>?</QuestionToken> </ZeroOrOneQuantifier> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..43)"" Text=""\D+(?&lt;digit&gt;\d+)\D+(?&lt;digit&gt;\d+)?"" /> <Capture Name=""1"" Span=""[13..26)"" Text=""(?&lt;digit&gt;\d+)"" /> <Capture Name=""digit"" Span=""[13..26)"" Text=""(?&lt;digit&gt;\d+)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest8() { Test(@"@""(\s\d{4}(-(\d{4}&#124;present))?,?)+""", @"<Tree> <CompilationUnit> <Sequence> <OneOrMoreQuantifier> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>s</TextToken> </CharacterClassEscape> <ExactNumericQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>d</TextToken> </CharacterClassEscape> <OpenBraceToken>{</OpenBraceToken> <NumberToken value=""4"">4</NumberToken> <CloseBraceToken>}</CloseBraceToken> </ExactNumericQuantifier> <ZeroOrOneQuantifier> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <Text> <TextToken>-</TextToken> </Text> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <ExactNumericQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>d</TextToken> </CharacterClassEscape> <OpenBraceToken>{</OpenBraceToken> <NumberToken value=""4"">4</NumberToken> <CloseBraceToken>}</CloseBraceToken> </ExactNumericQuantifier> <Text> <TextToken>&amp;#124;present</TextToken> </Text> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <QuestionToken>?</QuestionToken> </ZeroOrOneQuantifier> <ZeroOrOneQuantifier> <Text> <TextToken>,</TextToken> </Text> <QuestionToken>?</QuestionToken> </ZeroOrOneQuantifier> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..46)"" Text=""(\s\d{4}(-(\d{4}&amp;#124;present))?,?)+"" /> <Capture Name=""1"" Span=""[10..45)"" Text=""(\s\d{4}(-(\d{4}&amp;#124;present))?,?)"" /> <Capture Name=""2"" Span=""[18..41)"" Text=""(-(\d{4}&amp;#124;present))"" /> <Capture Name=""3"" Span=""[20..40)"" Text=""(\d{4}&amp;#124;present)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest9() { Test(@"@""^((\w+(\s?)){2,}),\s(\w+\s\w+),(\s\d{4}(-(\d{4}|present))?,?)+""", @"<Tree> <CompilationUnit> <Sequence> <StartAnchor> <CaretToken>^</CaretToken> </StartAnchor> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <OpenRangeNumericQuantifier> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <OneOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>w</TextToken> </CharacterClassEscape> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <ZeroOrOneQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>s</TextToken> </CharacterClassEscape> <QuestionToken>?</QuestionToken> </ZeroOrOneQuantifier> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <OpenBraceToken>{</OpenBraceToken> <NumberToken value=""2"">2</NumberToken> <CommaToken>,</CommaToken> <CloseBraceToken>}</CloseBraceToken> </OpenRangeNumericQuantifier> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <Text> <TextToken>,</TextToken> </Text> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>s</TextToken> </CharacterClassEscape> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <OneOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>w</TextToken> </CharacterClassEscape> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>s</TextToken> </CharacterClassEscape> <OneOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>w</TextToken> </CharacterClassEscape> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <Text> <TextToken>,</TextToken> </Text> <OneOrMoreQuantifier> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>s</TextToken> </CharacterClassEscape> <ExactNumericQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>d</TextToken> </CharacterClassEscape> <OpenBraceToken>{</OpenBraceToken> <NumberToken value=""4"">4</NumberToken> <CloseBraceToken>}</CloseBraceToken> </ExactNumericQuantifier> <ZeroOrOneQuantifier> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <Text> <TextToken>-</TextToken> </Text> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Alternation> <Sequence> <ExactNumericQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>d</TextToken> </CharacterClassEscape> <OpenBraceToken>{</OpenBraceToken> <NumberToken value=""4"">4</NumberToken> <CloseBraceToken>}</CloseBraceToken> </ExactNumericQuantifier> </Sequence> <BarToken>|</BarToken> <Sequence> <Text> <TextToken>present</TextToken> </Text> </Sequence> </Alternation> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <QuestionToken>?</QuestionToken> </ZeroOrOneQuantifier> <ZeroOrOneQuantifier> <Text> <TextToken>,</TextToken> </Text> <QuestionToken>?</QuestionToken> </ZeroOrOneQuantifier> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..72)"" Text=""^((\w+(\s?)){2,}),\s(\w+\s\w+),(\s\d{4}(-(\d{4}|present))?,?)+"" /> <Capture Name=""1"" Span=""[11..27)"" Text=""((\w+(\s?)){2,})"" /> <Capture Name=""2"" Span=""[12..22)"" Text=""(\w+(\s?))"" /> <Capture Name=""3"" Span=""[16..21)"" Text=""(\s?)"" /> <Capture Name=""4"" Span=""[30..40)"" Text=""(\w+\s\w+)"" /> <Capture Name=""5"" Span=""[41..71)"" Text=""(\s\d{4}(-(\d{4}|present))?,?)"" /> <Capture Name=""6"" Span=""[49..67)"" Text=""(-(\d{4}|present))"" /> <Capture Name=""7"" Span=""[51..66)"" Text=""(\d{4}|present)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest10() { Test(@"@""^[0-9-[2468]]+$""", @"<Tree> <CompilationUnit> <Sequence> <StartAnchor> <CaretToken>^</CaretToken> </StartAnchor> <OneOrMoreQuantifier> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <CharacterClassRange> <Text> <TextToken>0</TextToken> </Text> <MinusToken>-</MinusToken> <Text> <TextToken>9</TextToken> </Text> </CharacterClassRange> <CharacterClassSubtraction> <MinusToken>-</MinusToken> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <Text> <TextToken>2468</TextToken> </Text> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> </CharacterClassSubtraction> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> <EndAnchor> <DollarToken>$</DollarToken> </EndAnchor> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..25)"" Text=""^[0-9-[2468]]+$"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest11() { Test(@"@""[a-z-[0-9]]""", @"<Tree> <CompilationUnit> <Sequence> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <CharacterClassRange> <Text> <TextToken>a</TextToken> </Text> <MinusToken>-</MinusToken> <Text> <TextToken>z</TextToken> </Text> </CharacterClassRange> <CharacterClassSubtraction> <MinusToken>-</MinusToken> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <CharacterClassRange> <Text> <TextToken>0</TextToken> </Text> <MinusToken>-</MinusToken> <Text> <TextToken>9</TextToken> </Text> </CharacterClassRange> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> </CharacterClassSubtraction> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..21)"" Text=""[a-z-[0-9]]"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest12() { Test(@"@""[\p{IsBasicLatin}-[\x00-\x7F]]""", @"<Tree> <CompilationUnit> <Sequence> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <CategoryEscape> <BackslashToken>\</BackslashToken> <TextToken>p</TextToken> <OpenBraceToken>{</OpenBraceToken> <EscapeCategoryToken>IsBasicLatin</EscapeCategoryToken> <CloseBraceToken>}</CloseBraceToken> </CategoryEscape> <CharacterClassSubtraction> <MinusToken>-</MinusToken> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <CharacterClassRange> <HexEscape> <BackslashToken>\</BackslashToken> <TextToken>x</TextToken> <TextToken>00</TextToken> </HexEscape> <MinusToken>-</MinusToken> <HexEscape> <BackslashToken>\</BackslashToken> <TextToken>x</TextToken> <TextToken>7F</TextToken> </HexEscape> </CharacterClassRange> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> </CharacterClassSubtraction> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..40)"" Text=""[\p{IsBasicLatin}-[\x00-\x7F]]"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest13() { Test(@"@""[\u0000-\uFFFF-[\s\p{P}\p{IsGreek}\x85]]""", @"<Tree> <CompilationUnit> <Sequence> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <CharacterClassRange> <UnicodeEscape> <BackslashToken>\</BackslashToken> <TextToken>u</TextToken> <TextToken>0000</TextToken> </UnicodeEscape> <MinusToken>-</MinusToken> <UnicodeEscape> <BackslashToken>\</BackslashToken> <TextToken>u</TextToken> <TextToken>FFFF</TextToken> </UnicodeEscape> </CharacterClassRange> <CharacterClassSubtraction> <MinusToken>-</MinusToken> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>s</TextToken> </CharacterClassEscape> <CategoryEscape> <BackslashToken>\</BackslashToken> <TextToken>p</TextToken> <OpenBraceToken>{</OpenBraceToken> <EscapeCategoryToken>P</EscapeCategoryToken> <CloseBraceToken>}</CloseBraceToken> </CategoryEscape> <CategoryEscape> <BackslashToken>\</BackslashToken> <TextToken>p</TextToken> <OpenBraceToken>{</OpenBraceToken> <EscapeCategoryToken>IsGreek</EscapeCategoryToken> <CloseBraceToken>}</CloseBraceToken> </CategoryEscape> <HexEscape> <BackslashToken>\</BackslashToken> <TextToken>x</TextToken> <TextToken>85</TextToken> </HexEscape> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> </CharacterClassSubtraction> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..50)"" Text=""[\u0000-\uFFFF-[\s\p{P}\p{IsGreek}\x85]]"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest14() { Test(@"@""[a-z-[d-w-[m-o]]]""", @"<Tree> <CompilationUnit> <Sequence> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <CharacterClassRange> <Text> <TextToken>a</TextToken> </Text> <MinusToken>-</MinusToken> <Text> <TextToken>z</TextToken> </Text> </CharacterClassRange> <CharacterClassSubtraction> <MinusToken>-</MinusToken> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <CharacterClassRange> <Text> <TextToken>d</TextToken> </Text> <MinusToken>-</MinusToken> <Text> <TextToken>w</TextToken> </Text> </CharacterClassRange> <CharacterClassSubtraction> <MinusToken>-</MinusToken> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <CharacterClassRange> <Text> <TextToken>m</TextToken> </Text> <MinusToken>-</MinusToken> <Text> <TextToken>o</TextToken> </Text> </CharacterClassRange> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> </CharacterClassSubtraction> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> </CharacterClassSubtraction> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..27)"" Text=""[a-z-[d-w-[m-o]]]"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest15() { Test(@"@""((\w+(\s?)){2,}""", $@"<Tree> <CompilationUnit> <Sequence> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <OpenRangeNumericQuantifier> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <OneOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>w</TextToken> </CharacterClassEscape> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <ZeroOrOneQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>s</TextToken> </CharacterClassEscape> <QuestionToken>?</QuestionToken> </ZeroOrOneQuantifier> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <OpenBraceToken>{{</OpenBraceToken> <NumberToken value=""2"">2</NumberToken> <CommaToken>,</CommaToken> <CloseBraceToken>}}</CloseBraceToken> </OpenRangeNumericQuantifier> </Sequence> <CloseParenToken /> </SimpleGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Not_enough_close_parens}"" Span=""[25..25)"" Text="""" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..25)"" Text=""((\w+(\s?)){{2,}}"" /> <Capture Name=""1"" Span=""[10..25)"" Text=""((\w+(\s?)){{2,}}"" /> <Capture Name=""2"" Span=""[11..21)"" Text=""(\w+(\s?))"" /> <Capture Name=""3"" Span=""[15..20)"" Text=""(\s?)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest16() { Test(@"@""[a-z-[djp]]""", @"<Tree> <CompilationUnit> <Sequence> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <CharacterClassRange> <Text> <TextToken>a</TextToken> </Text> <MinusToken>-</MinusToken> <Text> <TextToken>z</TextToken> </Text> </CharacterClassRange> <CharacterClassSubtraction> <MinusToken>-</MinusToken> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <Text> <TextToken>djp</TextToken> </Text> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> </CharacterClassSubtraction> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..21)"" Text=""[a-z-[djp]]"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest17() { Test(@"@""^[^<>]*(((?'Open'<)[^<>]*)+((?'Close-Open'>)[^<>]*)+)*(?(Open)(?!))$""", @"<Tree> <CompilationUnit> <Sequence> <StartAnchor> <CaretToken>^</CaretToken> </StartAnchor> <ZeroOrMoreQuantifier> <NegatedCharacterClass> <OpenBracketToken>[</OpenBracketToken> <CaretToken>^</CaretToken> <Sequence> <Text> <TextToken>&lt;&gt;</TextToken> </Text> </Sequence> <CloseBracketToken>]</CloseBracketToken> </NegatedCharacterClass> <AsteriskToken>*</AsteriskToken> </ZeroOrMoreQuantifier> <ZeroOrMoreQuantifier> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <OneOrMoreQuantifier> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <CaptureGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <SingleQuoteToken>'</SingleQuoteToken> <CaptureNameToken value=""Open"">Open</CaptureNameToken> <SingleQuoteToken>'</SingleQuoteToken> <Sequence> <Text> <TextToken>&lt;</TextToken> </Text> </Sequence> <CloseParenToken>)</CloseParenToken> </CaptureGrouping> <ZeroOrMoreQuantifier> <NegatedCharacterClass> <OpenBracketToken>[</OpenBracketToken> <CaretToken>^</CaretToken> <Sequence> <Text> <TextToken>&lt;&gt;</TextToken> </Text> </Sequence> <CloseBracketToken>]</CloseBracketToken> </NegatedCharacterClass> <AsteriskToken>*</AsteriskToken> </ZeroOrMoreQuantifier> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> <OneOrMoreQuantifier> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <BalancingGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <SingleQuoteToken>'</SingleQuoteToken> <CaptureNameToken value=""Close"">Close</CaptureNameToken> <MinusToken>-</MinusToken> <CaptureNameToken value=""Open"">Open</CaptureNameToken> <SingleQuoteToken>'</SingleQuoteToken> <Sequence> <Text> <TextToken>&gt;</TextToken> </Text> </Sequence> <CloseParenToken>)</CloseParenToken> </BalancingGrouping> <ZeroOrMoreQuantifier> <NegatedCharacterClass> <OpenBracketToken>[</OpenBracketToken> <CaretToken>^</CaretToken> <Sequence> <Text> <TextToken>&lt;&gt;</TextToken> </Text> </Sequence> <CloseBracketToken>]</CloseBracketToken> </NegatedCharacterClass> <AsteriskToken>*</AsteriskToken> </ZeroOrMoreQuantifier> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <AsteriskToken>*</AsteriskToken> </ZeroOrMoreQuantifier> <ConditionalCaptureGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <OpenParenToken>(</OpenParenToken> <CaptureNameToken value=""Open"">Open</CaptureNameToken> <CloseParenToken>)</CloseParenToken> <Sequence> <NegativeLookaheadGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <ExclamationToken>!</ExclamationToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </NegativeLookaheadGrouping> </Sequence> <CloseParenToken>)</CloseParenToken> </ConditionalCaptureGrouping> <EndAnchor> <DollarToken>$</DollarToken> </EndAnchor> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..78)"" Text=""^[^&lt;&gt;]*(((?'Open'&lt;)[^&lt;&gt;]*)+((?'Close-Open'&gt;)[^&lt;&gt;]*)+)*(?(Open)(?!))$"" /> <Capture Name=""1"" Span=""[17..63)"" Text=""(((?'Open'&lt;)[^&lt;&gt;]*)+((?'Close-Open'&gt;)[^&lt;&gt;]*)+)"" /> <Capture Name=""2"" Span=""[18..36)"" Text=""((?'Open'&lt;)[^&lt;&gt;]*)"" /> <Capture Name=""3"" Span=""[37..61)"" Text=""((?'Close-Open'&gt;)[^&lt;&gt;]*)"" /> <Capture Name=""4"" Span=""[19..29)"" Text=""(?'Open'&lt;)"" /> <Capture Name=""5"" Span=""[38..54)"" Text=""(?'Close-Open'&gt;)"" /> <Capture Name=""Close"" Span=""[38..54)"" Text=""(?'Close-Open'&gt;)"" /> <Capture Name=""Open"" Span=""[19..29)"" Text=""(?'Open'&lt;)"" /> </Captures> </Tree>", RegexOptions.None, allowIndexOutOfRange: true); } [Fact] public void ReferenceTest18() { Test(@"@""((?'Close-Open'>)[^<>]*)+""", $@"<Tree> <CompilationUnit> <Sequence> <OneOrMoreQuantifier> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <BalancingGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <SingleQuoteToken>'</SingleQuoteToken> <CaptureNameToken value=""Close"">Close</CaptureNameToken> <MinusToken>-</MinusToken> <CaptureNameToken value=""Open"">Open</CaptureNameToken> <SingleQuoteToken>'</SingleQuoteToken> <Sequence> <Text> <TextToken>&gt;</TextToken> </Text> </Sequence> <CloseParenToken>)</CloseParenToken> </BalancingGrouping> <ZeroOrMoreQuantifier> <NegatedCharacterClass> <OpenBracketToken>[</OpenBracketToken> <CaretToken>^</CaretToken> <Sequence> <Text> <TextToken>&lt;&gt;</TextToken> </Text> </Sequence> <CloseBracketToken>]</CloseBracketToken> </NegatedCharacterClass> <AsteriskToken>*</AsteriskToken> </ZeroOrMoreQuantifier> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{string.Format(FeaturesResources.Reference_to_undefined_group_name_0, "Open")}"" Span=""[20..24)"" Text=""Open"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..35)"" Text=""((?'Close-Open'&gt;)[^&lt;&gt;]*)+"" /> <Capture Name=""1"" Span=""[10..34)"" Text=""((?'Close-Open'&gt;)[^&lt;&gt;]*)"" /> <Capture Name=""2"" Span=""[11..27)"" Text=""(?'Close-Open'&gt;)"" /> <Capture Name=""Close"" Span=""[11..27)"" Text=""(?'Close-Open'&gt;)"" /> </Captures> </Tree>", RegexOptions.None, allowIndexOutOfRange: true); } [Fact] public void ReferenceTest19() { Test(@"@""(\w)\1+.\b""", @"<Tree> <CompilationUnit> <Sequence> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>w</TextToken> </CharacterClassEscape> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <OneOrMoreQuantifier> <BackreferenceEscape> <BackslashToken>\</BackslashToken> <NumberToken value=""1"">1</NumberToken> </BackreferenceEscape> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> <Wildcard> <DotToken>.</DotToken> </Wildcard> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>b</TextToken> </AnchorEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..20)"" Text=""(\w)\1+.\b"" /> <Capture Name=""1"" Span=""[10..14)"" Text=""(\w)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest20() { Test(@"@""\d{4}\b""", @"<Tree> <CompilationUnit> <Sequence> <ExactNumericQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>d</TextToken> </CharacterClassEscape> <OpenBraceToken>{</OpenBraceToken> <NumberToken value=""4"">4</NumberToken> <CloseBraceToken>}</CloseBraceToken> </ExactNumericQuantifier> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>b</TextToken> </AnchorEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..17)"" Text=""\d{4}\b"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest21() { Test(@"@""\d{1,2},""", @"<Tree> <CompilationUnit> <Sequence> <ClosedRangeNumericQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>d</TextToken> </CharacterClassEscape> <OpenBraceToken>{</OpenBraceToken> <NumberToken value=""1"">1</NumberToken> <CommaToken>,</CommaToken> <NumberToken value=""2"">2</NumberToken> <CloseBraceToken>}</CloseBraceToken> </ClosedRangeNumericQuantifier> <Text> <TextToken>,</TextToken> </Text> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..18)"" Text=""\d{1,2},"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest22() { Test(@"@""(?<!(Saturday|Sunday) )\b\w+ \d{1,2}, \d{4}\b""", @"<Tree> <CompilationUnit> <Sequence> <NegativeLookbehindGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <ExclamationToken>!</ExclamationToken> <Sequence> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Alternation> <Sequence> <Text> <TextToken>Saturday</TextToken> </Text> </Sequence> <BarToken>|</BarToken> <Sequence> <Text> <TextToken>Sunday</TextToken> </Text> </Sequence> </Alternation> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <Text> <TextToken> </TextToken> </Text> </Sequence> <CloseParenToken>)</CloseParenToken> </NegativeLookbehindGrouping> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>b</TextToken> </AnchorEscape> <OneOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>w</TextToken> </CharacterClassEscape> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> <Text> <TextToken> </TextToken> </Text> <ClosedRangeNumericQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>d</TextToken> </CharacterClassEscape> <OpenBraceToken>{</OpenBraceToken> <NumberToken value=""1"">1</NumberToken> <CommaToken>,</CommaToken> <NumberToken value=""2"">2</NumberToken> <CloseBraceToken>}</CloseBraceToken> </ClosedRangeNumericQuantifier> <Text> <TextToken>, </TextToken> </Text> <ExactNumericQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>d</TextToken> </CharacterClassEscape> <OpenBraceToken>{</OpenBraceToken> <NumberToken value=""4"">4</NumberToken> <CloseBraceToken>}</CloseBraceToken> </ExactNumericQuantifier> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>b</TextToken> </AnchorEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..55)"" Text=""(?&lt;!(Saturday|Sunday) )\b\w+ \d{1,2}, \d{4}\b"" /> <Capture Name=""1"" Span=""[14..31)"" Text=""(Saturday|Sunday)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest23() { Test(@"@""(?<=\b20)\d{2}\b""", @"<Tree> <CompilationUnit> <Sequence> <PositiveLookbehindGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <EqualsToken>=</EqualsToken> <Sequence> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>b</TextToken> </AnchorEscape> <Text> <TextToken>20</TextToken> </Text> </Sequence> <CloseParenToken>)</CloseParenToken> </PositiveLookbehindGrouping> <ExactNumericQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>d</TextToken> </CharacterClassEscape> <OpenBraceToken>{</OpenBraceToken> <NumberToken value=""2"">2</NumberToken> <CloseBraceToken>}</CloseBraceToken> </ExactNumericQuantifier> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>b</TextToken> </AnchorEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..26)"" Text=""(?&lt;=\b20)\d{2}\b"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest24() { Test(@"@""\b\w+\b(?!\p{P})""", @"<Tree> <CompilationUnit> <Sequence> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>b</TextToken> </AnchorEscape> <OneOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>w</TextToken> </CharacterClassEscape> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>b</TextToken> </AnchorEscape> <NegativeLookaheadGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <ExclamationToken>!</ExclamationToken> <Sequence> <CategoryEscape> <BackslashToken>\</BackslashToken> <TextToken>p</TextToken> <OpenBraceToken>{</OpenBraceToken> <EscapeCategoryToken>P</EscapeCategoryToken> <CloseBraceToken>}</CloseBraceToken> </CategoryEscape> </Sequence> <CloseParenToken>)</CloseParenToken> </NegativeLookaheadGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..26)"" Text=""\b\w+\b(?!\p{P})"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest25() { Test(@"@""(((?'Open'<)[^<>]*)+((?'Close-Open'>)[^<>]*)+)*""", @"<Tree> <CompilationUnit> <Sequence> <ZeroOrMoreQuantifier> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <OneOrMoreQuantifier> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <CaptureGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <SingleQuoteToken>'</SingleQuoteToken> <CaptureNameToken value=""Open"">Open</CaptureNameToken> <SingleQuoteToken>'</SingleQuoteToken> <Sequence> <Text> <TextToken>&lt;</TextToken> </Text> </Sequence> <CloseParenToken>)</CloseParenToken> </CaptureGrouping> <ZeroOrMoreQuantifier> <NegatedCharacterClass> <OpenBracketToken>[</OpenBracketToken> <CaretToken>^</CaretToken> <Sequence> <Text> <TextToken>&lt;&gt;</TextToken> </Text> </Sequence> <CloseBracketToken>]</CloseBracketToken> </NegatedCharacterClass> <AsteriskToken>*</AsteriskToken> </ZeroOrMoreQuantifier> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> <OneOrMoreQuantifier> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <BalancingGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <SingleQuoteToken>'</SingleQuoteToken> <CaptureNameToken value=""Close"">Close</CaptureNameToken> <MinusToken>-</MinusToken> <CaptureNameToken value=""Open"">Open</CaptureNameToken> <SingleQuoteToken>'</SingleQuoteToken> <Sequence> <Text> <TextToken>&gt;</TextToken> </Text> </Sequence> <CloseParenToken>)</CloseParenToken> </BalancingGrouping> <ZeroOrMoreQuantifier> <NegatedCharacterClass> <OpenBracketToken>[</OpenBracketToken> <CaretToken>^</CaretToken> <Sequence> <Text> <TextToken>&lt;&gt;</TextToken> </Text> </Sequence> <CloseBracketToken>]</CloseBracketToken> </NegatedCharacterClass> <AsteriskToken>*</AsteriskToken> </ZeroOrMoreQuantifier> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <AsteriskToken>*</AsteriskToken> </ZeroOrMoreQuantifier> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..57)"" Text=""(((?'Open'&lt;)[^&lt;&gt;]*)+((?'Close-Open'&gt;)[^&lt;&gt;]*)+)*"" /> <Capture Name=""1"" Span=""[10..56)"" Text=""(((?'Open'&lt;)[^&lt;&gt;]*)+((?'Close-Open'&gt;)[^&lt;&gt;]*)+)"" /> <Capture Name=""2"" Span=""[11..29)"" Text=""((?'Open'&lt;)[^&lt;&gt;]*)"" /> <Capture Name=""3"" Span=""[30..54)"" Text=""((?'Close-Open'&gt;)[^&lt;&gt;]*)"" /> <Capture Name=""4"" Span=""[12..22)"" Text=""(?'Open'&lt;)"" /> <Capture Name=""5"" Span=""[31..47)"" Text=""(?'Close-Open'&gt;)"" /> <Capture Name=""Close"" Span=""[31..47)"" Text=""(?'Close-Open'&gt;)"" /> <Capture Name=""Open"" Span=""[12..22)"" Text=""(?'Open'&lt;)"" /> </Captures> </Tree>", RegexOptions.None, allowIndexOutOfRange: true); } [Fact] public void ReferenceTest26() { Test(@"@""\b(?!un)\w+\b""", @"<Tree> <CompilationUnit> <Sequence> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>b</TextToken> </AnchorEscape> <NegativeLookaheadGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <ExclamationToken>!</ExclamationToken> <Sequence> <Text> <TextToken>un</TextToken> </Text> </Sequence> <CloseParenToken>)</CloseParenToken> </NegativeLookaheadGrouping> <OneOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>w</TextToken> </CharacterClassEscape> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>b</TextToken> </AnchorEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..23)"" Text=""\b(?!un)\w+\b"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest27() { Test(@"@""\b(?ix: d \w+)\s""", @"<Tree> <CompilationUnit> <Sequence> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>b</TextToken> </AnchorEscape> <NestedOptionsGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <OptionsToken>ix</OptionsToken> <ColonToken>:</ColonToken> <Sequence> <Text> <TextToken> <Trivia> <WhitespaceTrivia> </WhitespaceTrivia> </Trivia>d</TextToken> </Text> <OneOrMoreQuantifier> <CharacterClassEscape> <BackslashToken> <Trivia> <WhitespaceTrivia> </WhitespaceTrivia> </Trivia>\</BackslashToken> <TextToken>w</TextToken> </CharacterClassEscape> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> </Sequence> <CloseParenToken>)</CloseParenToken> </NestedOptionsGrouping> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>s</TextToken> </CharacterClassEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..26)"" Text=""\b(?ix: d \w+)\s"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest28() { Test(@"@""(?:\w+)""", @"<Tree> <CompilationUnit> <Sequence> <NonCapturingGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <ColonToken>:</ColonToken> <Sequence> <OneOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>w</TextToken> </CharacterClassEscape> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> </Sequence> <CloseParenToken>)</CloseParenToken> </NonCapturingGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..17)"" Text=""(?:\w+)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest29() { Test(@"@""(?:\b(?:\w+)\W*)+""", @"<Tree> <CompilationUnit> <Sequence> <OneOrMoreQuantifier> <NonCapturingGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <ColonToken>:</ColonToken> <Sequence> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>b</TextToken> </AnchorEscape> <NonCapturingGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <ColonToken>:</ColonToken> <Sequence> <OneOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>w</TextToken> </CharacterClassEscape> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> </Sequence> <CloseParenToken>)</CloseParenToken> </NonCapturingGrouping> <ZeroOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>W</TextToken> </CharacterClassEscape> <AsteriskToken>*</AsteriskToken> </ZeroOrMoreQuantifier> </Sequence> <CloseParenToken>)</CloseParenToken> </NonCapturingGrouping> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..27)"" Text=""(?:\b(?:\w+)\W*)+"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest30() { Test(@"@""(?:\b(?:\w+)\W*)+\.""", @"<Tree> <CompilationUnit> <Sequence> <OneOrMoreQuantifier> <NonCapturingGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <ColonToken>:</ColonToken> <Sequence> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>b</TextToken> </AnchorEscape> <NonCapturingGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <ColonToken>:</ColonToken> <Sequence> <OneOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>w</TextToken> </CharacterClassEscape> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> </Sequence> <CloseParenToken>)</CloseParenToken> </NonCapturingGrouping> <ZeroOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>W</TextToken> </CharacterClassEscape> <AsteriskToken>*</AsteriskToken> </ZeroOrMoreQuantifier> </Sequence> <CloseParenToken>)</CloseParenToken> </NonCapturingGrouping> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken>.</TextToken> </SimpleEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..29)"" Text=""(?:\b(?:\w+)\W*)+\."" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest31() { Test(@"@""(?'Close-Open'>)""", $@"<Tree> <CompilationUnit> <Sequence> <BalancingGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <SingleQuoteToken>'</SingleQuoteToken> <CaptureNameToken value=""Close"">Close</CaptureNameToken> <MinusToken>-</MinusToken> <CaptureNameToken value=""Open"">Open</CaptureNameToken> <SingleQuoteToken>'</SingleQuoteToken> <Sequence> <Text> <TextToken>&gt;</TextToken> </Text> </Sequence> <CloseParenToken>)</CloseParenToken> </BalancingGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{string.Format(FeaturesResources.Reference_to_undefined_group_name_0, "Open")}"" Span=""[19..23)"" Text=""Open"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..26)"" Text=""(?'Close-Open'&gt;)"" /> <Capture Name=""1"" Span=""[10..26)"" Text=""(?'Close-Open'&gt;)"" /> <Capture Name=""Close"" Span=""[10..26)"" Text=""(?'Close-Open'&gt;)"" /> </Captures> </Tree>", RegexOptions.None, allowIndexOutOfRange: true); } [Fact] public void ReferenceTest32() { Test(@"@""[^<>]*""", @"<Tree> <CompilationUnit> <Sequence> <ZeroOrMoreQuantifier> <NegatedCharacterClass> <OpenBracketToken>[</OpenBracketToken> <CaretToken>^</CaretToken> <Sequence> <Text> <TextToken>&lt;&gt;</TextToken> </Text> </Sequence> <CloseBracketToken>]</CloseBracketToken> </NegatedCharacterClass> <AsteriskToken>*</AsteriskToken> </ZeroOrMoreQuantifier> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..16)"" Text=""[^&lt;&gt;]*"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest33() { Test(@"@""\b\w+(?=\sis\b)""", @"<Tree> <CompilationUnit> <Sequence> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>b</TextToken> </AnchorEscape> <OneOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>w</TextToken> </CharacterClassEscape> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> <PositiveLookaheadGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <EqualsToken>=</EqualsToken> <Sequence> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>s</TextToken> </CharacterClassEscape> <Text> <TextToken>is</TextToken> </Text> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>b</TextToken> </AnchorEscape> </Sequence> <CloseParenToken>)</CloseParenToken> </PositiveLookaheadGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..25)"" Text=""\b\w+(?=\sis\b)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest34() { Test(@"@""[a-z-[m]]""", @"<Tree> <CompilationUnit> <Sequence> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <CharacterClassRange> <Text> <TextToken>a</TextToken> </Text> <MinusToken>-</MinusToken> <Text> <TextToken>z</TextToken> </Text> </CharacterClassRange> <CharacterClassSubtraction> <MinusToken>-</MinusToken> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <Text> <TextToken>m</TextToken> </Text> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> </CharacterClassSubtraction> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..19)"" Text=""[a-z-[m]]"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest35() { Test(@"@""^\D\d{1,5}\D*$""", @"<Tree> <CompilationUnit> <Sequence> <StartAnchor> <CaretToken>^</CaretToken> </StartAnchor> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>D</TextToken> </CharacterClassEscape> <ClosedRangeNumericQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>d</TextToken> </CharacterClassEscape> <OpenBraceToken>{</OpenBraceToken> <NumberToken value=""1"">1</NumberToken> <CommaToken>,</CommaToken> <NumberToken value=""5"">5</NumberToken> <CloseBraceToken>}</CloseBraceToken> </ClosedRangeNumericQuantifier> <ZeroOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>D</TextToken> </CharacterClassEscape> <AsteriskToken>*</AsteriskToken> </ZeroOrMoreQuantifier> <EndAnchor> <DollarToken>$</DollarToken> </EndAnchor> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..24)"" Text=""^\D\d{1,5}\D*$"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest36() { Test(@"@""[^0-9]""", @"<Tree> <CompilationUnit> <Sequence> <NegatedCharacterClass> <OpenBracketToken>[</OpenBracketToken> <CaretToken>^</CaretToken> <Sequence> <CharacterClassRange> <Text> <TextToken>0</TextToken> </Text> <MinusToken>-</MinusToken> <Text> <TextToken>9</TextToken> </Text> </CharacterClassRange> </Sequence> <CloseBracketToken>]</CloseBracketToken> </NegatedCharacterClass> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..16)"" Text=""[^0-9]"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest37() { Test(@"@""(\p{IsGreek}+(\s)?)+""", @"<Tree> <CompilationUnit> <Sequence> <OneOrMoreQuantifier> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <OneOrMoreQuantifier> <CategoryEscape> <BackslashToken>\</BackslashToken> <TextToken>p</TextToken> <OpenBraceToken>{</OpenBraceToken> <EscapeCategoryToken>IsGreek</EscapeCategoryToken> <CloseBraceToken>}</CloseBraceToken> </CategoryEscape> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> <ZeroOrOneQuantifier> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>s</TextToken> </CharacterClassEscape> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <QuestionToken>?</QuestionToken> </ZeroOrOneQuantifier> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..30)"" Text=""(\p{IsGreek}+(\s)?)+"" /> <Capture Name=""1"" Span=""[10..29)"" Text=""(\p{IsGreek}+(\s)?)"" /> <Capture Name=""2"" Span=""[23..27)"" Text=""(\s)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest38() { Test(@"@""\b(\p{IsGreek}+(\s)?)+\p{Pd}\s(\p{IsBasicLatin}+(\s)?)+""", @"<Tree> <CompilationUnit> <Sequence> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>b</TextToken> </AnchorEscape> <OneOrMoreQuantifier> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <OneOrMoreQuantifier> <CategoryEscape> <BackslashToken>\</BackslashToken> <TextToken>p</TextToken> <OpenBraceToken>{</OpenBraceToken> <EscapeCategoryToken>IsGreek</EscapeCategoryToken> <CloseBraceToken>}</CloseBraceToken> </CategoryEscape> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> <ZeroOrOneQuantifier> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>s</TextToken> </CharacterClassEscape> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <QuestionToken>?</QuestionToken> </ZeroOrOneQuantifier> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> <CategoryEscape> <BackslashToken>\</BackslashToken> <TextToken>p</TextToken> <OpenBraceToken>{</OpenBraceToken> <EscapeCategoryToken>Pd</EscapeCategoryToken> <CloseBraceToken>}</CloseBraceToken> </CategoryEscape> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>s</TextToken> </CharacterClassEscape> <OneOrMoreQuantifier> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <OneOrMoreQuantifier> <CategoryEscape> <BackslashToken>\</BackslashToken> <TextToken>p</TextToken> <OpenBraceToken>{</OpenBraceToken> <EscapeCategoryToken>IsBasicLatin</EscapeCategoryToken> <CloseBraceToken>}</CloseBraceToken> </CategoryEscape> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> <ZeroOrOneQuantifier> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>s</TextToken> </CharacterClassEscape> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <QuestionToken>?</QuestionToken> </ZeroOrOneQuantifier> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..65)"" Text=""\b(\p{IsGreek}+(\s)?)+\p{Pd}\s(\p{IsBasicLatin}+(\s)?)+"" /> <Capture Name=""1"" Span=""[12..31)"" Text=""(\p{IsGreek}+(\s)?)"" /> <Capture Name=""2"" Span=""[25..29)"" Text=""(\s)"" /> <Capture Name=""3"" Span=""[40..64)"" Text=""(\p{IsBasicLatin}+(\s)?)"" /> <Capture Name=""4"" Span=""[58..62)"" Text=""(\s)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest39() { Test(@"@""\b.*[.?!;:](\s|\z)""", @"<Tree> <CompilationUnit> <Sequence> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>b</TextToken> </AnchorEscape> <ZeroOrMoreQuantifier> <Wildcard> <DotToken>.</DotToken> </Wildcard> <AsteriskToken>*</AsteriskToken> </ZeroOrMoreQuantifier> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <Text> <TextToken>.?!;:</TextToken> </Text> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Alternation> <Sequence> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>s</TextToken> </CharacterClassEscape> </Sequence> <BarToken>|</BarToken> <Sequence> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>z</TextToken> </AnchorEscape> </Sequence> </Alternation> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..28)"" Text=""\b.*[.?!;:](\s|\z)"" /> <Capture Name=""1"" Span=""[21..28)"" Text=""(\s|\z)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest40() { Test(@"@""^.+""", @"<Tree> <CompilationUnit> <Sequence> <StartAnchor> <CaretToken>^</CaretToken> </StartAnchor> <OneOrMoreQuantifier> <Wildcard> <DotToken>.</DotToken> </Wildcard> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..13)"" Text=""^.+"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest41() { Test(@"@""[^o]""", @"<Tree> <CompilationUnit> <Sequence> <NegatedCharacterClass> <OpenBracketToken>[</OpenBracketToken> <CaretToken>^</CaretToken> <Sequence> <Text> <TextToken>o</TextToken> </Text> </Sequence> <CloseBracketToken>]</CloseBracketToken> </NegatedCharacterClass> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..14)"" Text=""[^o]"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest42() { Test(@"@""\bth[^o]\w+\b""", @"<Tree> <CompilationUnit> <Sequence> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>b</TextToken> </AnchorEscape> <Text> <TextToken>th</TextToken> </Text> <NegatedCharacterClass> <OpenBracketToken>[</OpenBracketToken> <CaretToken>^</CaretToken> <Sequence> <Text> <TextToken>o</TextToken> </Text> </Sequence> <CloseBracketToken>]</CloseBracketToken> </NegatedCharacterClass> <OneOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>w</TextToken> </CharacterClassEscape> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>b</TextToken> </AnchorEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..23)"" Text=""\bth[^o]\w+\b"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest43() { Test(@"@""(\P{Sc})+""", @"<Tree> <CompilationUnit> <Sequence> <OneOrMoreQuantifier> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <CategoryEscape> <BackslashToken>\</BackslashToken> <TextToken>P</TextToken> <OpenBraceToken>{</OpenBraceToken> <EscapeCategoryToken>Sc</EscapeCategoryToken> <CloseBraceToken>}</CloseBraceToken> </CategoryEscape> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..19)"" Text=""(\P{Sc})+"" /> <Capture Name=""1"" Span=""[10..18)"" Text=""(\P{Sc})"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest44() { Test(@"@""[^\p{P}\d]""", @"<Tree> <CompilationUnit> <Sequence> <NegatedCharacterClass> <OpenBracketToken>[</OpenBracketToken> <CaretToken>^</CaretToken> <Sequence> <CategoryEscape> <BackslashToken>\</BackslashToken> <TextToken>p</TextToken> <OpenBraceToken>{</OpenBraceToken> <EscapeCategoryToken>P</EscapeCategoryToken> <CloseBraceToken>}</CloseBraceToken> </CategoryEscape> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>d</TextToken> </CharacterClassEscape> </Sequence> <CloseBracketToken>]</CloseBracketToken> </NegatedCharacterClass> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..20)"" Text=""[^\p{P}\d]"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest45() { Test(@"@""\b[A-Z]\w*\b""", @"<Tree> <CompilationUnit> <Sequence> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>b</TextToken> </AnchorEscape> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <CharacterClassRange> <Text> <TextToken>A</TextToken> </Text> <MinusToken>-</MinusToken> <Text> <TextToken>Z</TextToken> </Text> </CharacterClassRange> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> <ZeroOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>w</TextToken> </CharacterClassEscape> <AsteriskToken>*</AsteriskToken> </ZeroOrMoreQuantifier> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>b</TextToken> </AnchorEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..22)"" Text=""\b[A-Z]\w*\b"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest46() { Test(@"@""\S+?""", @"<Tree> <CompilationUnit> <Sequence> <LazyQuantifier> <OneOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>S</TextToken> </CharacterClassEscape> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> <QuestionToken>?</QuestionToken> </LazyQuantifier> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..14)"" Text=""\S+?"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest47() { Test(@"@""y\s""", @"<Tree> <CompilationUnit> <Sequence> <Text> <TextToken>y</TextToken> </Text> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>s</TextToken> </CharacterClassEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..13)"" Text=""y\s"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest48() { Test(@"@""gr[ae]y\s\S+?[\s\p{P}]""", @"<Tree> <CompilationUnit> <Sequence> <Text> <TextToken>gr</TextToken> </Text> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <Text> <TextToken>ae</TextToken> </Text> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> <Text> <TextToken>y</TextToken> </Text> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>s</TextToken> </CharacterClassEscape> <LazyQuantifier> <OneOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>S</TextToken> </CharacterClassEscape> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> <QuestionToken>?</QuestionToken> </LazyQuantifier> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>s</TextToken> </CharacterClassEscape> <CategoryEscape> <BackslashToken>\</BackslashToken> <TextToken>p</TextToken> <OpenBraceToken>{</OpenBraceToken> <EscapeCategoryToken>P</EscapeCategoryToken> <CloseBraceToken>}</CloseBraceToken> </CategoryEscape> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..32)"" Text=""gr[ae]y\s\S+?[\s\p{P}]"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest49() { Test(@"@""[\s\p{P}]""", @"<Tree> <CompilationUnit> <Sequence> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>s</TextToken> </CharacterClassEscape> <CategoryEscape> <BackslashToken>\</BackslashToken> <TextToken>p</TextToken> <OpenBraceToken>{</OpenBraceToken> <EscapeCategoryToken>P</EscapeCategoryToken> <CloseBraceToken>}</CloseBraceToken> </CategoryEscape> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..19)"" Text=""[\s\p{P}]"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest50() { Test(@"@""[\p{P}\d]""", @"<Tree> <CompilationUnit> <Sequence> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <CategoryEscape> <BackslashToken>\</BackslashToken> <TextToken>p</TextToken> <OpenBraceToken>{</OpenBraceToken> <EscapeCategoryToken>P</EscapeCategoryToken> <CloseBraceToken>}</CloseBraceToken> </CategoryEscape> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>d</TextToken> </CharacterClassEscape> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..19)"" Text=""[\p{P}\d]"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest51() { Test(@"@""[^aeiou]""", @"<Tree> <CompilationUnit> <Sequence> <NegatedCharacterClass> <OpenBracketToken>[</OpenBracketToken> <CaretToken>^</CaretToken> <Sequence> <Text> <TextToken>aeiou</TextToken> </Text> </Sequence> <CloseBracketToken>]</CloseBracketToken> </NegatedCharacterClass> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..18)"" Text=""[^aeiou]"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest52() { Test(@"@""(\w)\1""", @"<Tree> <CompilationUnit> <Sequence> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>w</TextToken> </CharacterClassEscape> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <BackreferenceEscape> <BackslashToken>\</BackslashToken> <NumberToken value=""1"">1</NumberToken> </BackreferenceEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..16)"" Text=""(\w)\1"" /> <Capture Name=""1"" Span=""[10..14)"" Text=""(\w)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest53() { Test(@"@""[^\p{Ll}\p{Lu}\p{Lt}\p{Lo}\p{Nd}\p{Pc}\p{Lm}] """, @"<Tree> <CompilationUnit> <Sequence> <NegatedCharacterClass> <OpenBracketToken>[</OpenBracketToken> <CaretToken>^</CaretToken> <Sequence> <CategoryEscape> <BackslashToken>\</BackslashToken> <TextToken>p</TextToken> <OpenBraceToken>{</OpenBraceToken> <EscapeCategoryToken>Ll</EscapeCategoryToken> <CloseBraceToken>}</CloseBraceToken> </CategoryEscape> <CategoryEscape> <BackslashToken>\</BackslashToken> <TextToken>p</TextToken> <OpenBraceToken>{</OpenBraceToken> <EscapeCategoryToken>Lu</EscapeCategoryToken> <CloseBraceToken>}</CloseBraceToken> </CategoryEscape> <CategoryEscape> <BackslashToken>\</BackslashToken> <TextToken>p</TextToken> <OpenBraceToken>{</OpenBraceToken> <EscapeCategoryToken>Lt</EscapeCategoryToken> <CloseBraceToken>}</CloseBraceToken> </CategoryEscape> <CategoryEscape> <BackslashToken>\</BackslashToken> <TextToken>p</TextToken> <OpenBraceToken>{</OpenBraceToken> <EscapeCategoryToken>Lo</EscapeCategoryToken> <CloseBraceToken>}</CloseBraceToken> </CategoryEscape> <CategoryEscape> <BackslashToken>\</BackslashToken> <TextToken>p</TextToken> <OpenBraceToken>{</OpenBraceToken> <EscapeCategoryToken>Nd</EscapeCategoryToken> <CloseBraceToken>}</CloseBraceToken> </CategoryEscape> <CategoryEscape> <BackslashToken>\</BackslashToken> <TextToken>p</TextToken> <OpenBraceToken>{</OpenBraceToken> <EscapeCategoryToken>Pc</EscapeCategoryToken> <CloseBraceToken>}</CloseBraceToken> </CategoryEscape> <CategoryEscape> <BackslashToken>\</BackslashToken> <TextToken>p</TextToken> <OpenBraceToken>{</OpenBraceToken> <EscapeCategoryToken>Lm</EscapeCategoryToken> <CloseBraceToken>}</CloseBraceToken> </CategoryEscape> </Sequence> <CloseBracketToken>]</CloseBracketToken> </NegatedCharacterClass> <Text> <TextToken> </TextToken> </Text> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..56)"" Text=""[^\p{Ll}\p{Lu}\p{Lt}\p{Lo}\p{Nd}\p{Pc}\p{Lm}] "" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest54() { Test(@"@""[^a-zA-Z_0-9]""", @"<Tree> <CompilationUnit> <Sequence> <NegatedCharacterClass> <OpenBracketToken>[</OpenBracketToken> <CaretToken>^</CaretToken> <Sequence> <CharacterClassRange> <Text> <TextToken>a</TextToken> </Text> <MinusToken>-</MinusToken> <Text> <TextToken>z</TextToken> </Text> </CharacterClassRange> <CharacterClassRange> <Text> <TextToken>A</TextToken> </Text> <MinusToken>-</MinusToken> <Text> <TextToken>Z</TextToken> </Text> </CharacterClassRange> <Text> <TextToken>_</TextToken> </Text> <CharacterClassRange> <Text> <TextToken>0</TextToken> </Text> <MinusToken>-</MinusToken> <Text> <TextToken>9</TextToken> </Text> </CharacterClassRange> </Sequence> <CloseBracketToken>]</CloseBracketToken> </NegatedCharacterClass> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..23)"" Text=""[^a-zA-Z_0-9]"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest55() { Test(@"@""\P{Nd}""", @"<Tree> <CompilationUnit> <Sequence> <CategoryEscape> <BackslashToken>\</BackslashToken> <TextToken>P</TextToken> <OpenBraceToken>{</OpenBraceToken> <EscapeCategoryToken>Nd</EscapeCategoryToken> <CloseBraceToken>}</CloseBraceToken> </CategoryEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..16)"" Text=""\P{Nd}"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest56() { Test(@"@""(\(?\d{3}\)?[\s-])?""", @"<Tree> <CompilationUnit> <Sequence> <ZeroOrOneQuantifier> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <ZeroOrOneQuantifier> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken>(</TextToken> </SimpleEscape> <QuestionToken>?</QuestionToken> </ZeroOrOneQuantifier> <ExactNumericQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>d</TextToken> </CharacterClassEscape> <OpenBraceToken>{</OpenBraceToken> <NumberToken value=""3"">3</NumberToken> <CloseBraceToken>}</CloseBraceToken> </ExactNumericQuantifier> <ZeroOrOneQuantifier> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken>)</TextToken> </SimpleEscape> <QuestionToken>?</QuestionToken> </ZeroOrOneQuantifier> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>s</TextToken> </CharacterClassEscape> <Text> <TextToken>-</TextToken> </Text> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <QuestionToken>?</QuestionToken> </ZeroOrOneQuantifier> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..29)"" Text=""(\(?\d{3}\)?[\s-])?"" /> <Capture Name=""1"" Span=""[10..28)"" Text=""(\(?\d{3}\)?[\s-])"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest57() { Test(@"@""^(\(?\d{3}\)?[\s-])?\d{3}-\d{4}$""", @"<Tree> <CompilationUnit> <Sequence> <StartAnchor> <CaretToken>^</CaretToken> </StartAnchor> <ZeroOrOneQuantifier> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <ZeroOrOneQuantifier> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken>(</TextToken> </SimpleEscape> <QuestionToken>?</QuestionToken> </ZeroOrOneQuantifier> <ExactNumericQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>d</TextToken> </CharacterClassEscape> <OpenBraceToken>{</OpenBraceToken> <NumberToken value=""3"">3</NumberToken> <CloseBraceToken>}</CloseBraceToken> </ExactNumericQuantifier> <ZeroOrOneQuantifier> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken>)</TextToken> </SimpleEscape> <QuestionToken>?</QuestionToken> </ZeroOrOneQuantifier> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>s</TextToken> </CharacterClassEscape> <Text> <TextToken>-</TextToken> </Text> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <QuestionToken>?</QuestionToken> </ZeroOrOneQuantifier> <ExactNumericQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>d</TextToken> </CharacterClassEscape> <OpenBraceToken>{</OpenBraceToken> <NumberToken value=""3"">3</NumberToken> <CloseBraceToken>}</CloseBraceToken> </ExactNumericQuantifier> <Text> <TextToken>-</TextToken> </Text> <ExactNumericQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>d</TextToken> </CharacterClassEscape> <OpenBraceToken>{</OpenBraceToken> <NumberToken value=""4"">4</NumberToken> <CloseBraceToken>}</CloseBraceToken> </ExactNumericQuantifier> <EndAnchor> <DollarToken>$</DollarToken> </EndAnchor> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..42)"" Text=""^(\(?\d{3}\)?[\s-])?\d{3}-\d{4}$"" /> <Capture Name=""1"" Span=""[11..29)"" Text=""(\(?\d{3}\)?[\s-])"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest58() { Test(@"@""[0-9]""", @"<Tree> <CompilationUnit> <Sequence> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <CharacterClassRange> <Text> <TextToken>0</TextToken> </Text> <MinusToken>-</MinusToken> <Text> <TextToken>9</TextToken> </Text> </CharacterClassRange> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..15)"" Text=""[0-9]"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest59() { Test(@"@""\p{Nd}""", @"<Tree> <CompilationUnit> <Sequence> <CategoryEscape> <BackslashToken>\</BackslashToken> <TextToken>p</TextToken> <OpenBraceToken>{</OpenBraceToken> <EscapeCategoryToken>Nd</EscapeCategoryToken> <CloseBraceToken>}</CloseBraceToken> </CategoryEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..16)"" Text=""\p{Nd}"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest60() { Test(@"@""\b(\S+)\s?""", @"<Tree> <CompilationUnit> <Sequence> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>b</TextToken> </AnchorEscape> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <OneOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>S</TextToken> </CharacterClassEscape> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <ZeroOrOneQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>s</TextToken> </CharacterClassEscape> <QuestionToken>?</QuestionToken> </ZeroOrOneQuantifier> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..20)"" Text=""\b(\S+)\s?"" /> <Capture Name=""1"" Span=""[12..17)"" Text=""(\S+)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest61() { Test(@"@""[^ \f\n\r\t\v]""", @"<Tree> <CompilationUnit> <Sequence> <NegatedCharacterClass> <OpenBracketToken>[</OpenBracketToken> <CaretToken>^</CaretToken> <Sequence> <Text> <TextToken> </TextToken> </Text> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken>f</TextToken> </SimpleEscape> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken>n</TextToken> </SimpleEscape> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken>r</TextToken> </SimpleEscape> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken>t</TextToken> </SimpleEscape> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken>v</TextToken> </SimpleEscape> </Sequence> <CloseBracketToken>]</CloseBracketToken> </NegatedCharacterClass> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..24)"" Text=""[^ \f\n\r\t\v]"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest62() { Test(@"@""[^\f\n\r\t\v\x85\p{Z}]""", @"<Tree> <CompilationUnit> <Sequence> <NegatedCharacterClass> <OpenBracketToken>[</OpenBracketToken> <CaretToken>^</CaretToken> <Sequence> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken>f</TextToken> </SimpleEscape> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken>n</TextToken> </SimpleEscape> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken>r</TextToken> </SimpleEscape> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken>t</TextToken> </SimpleEscape> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken>v</TextToken> </SimpleEscape> <HexEscape> <BackslashToken>\</BackslashToken> <TextToken>x</TextToken> <TextToken>85</TextToken> </HexEscape> <CategoryEscape> <BackslashToken>\</BackslashToken> <TextToken>p</TextToken> <OpenBraceToken>{</OpenBraceToken> <EscapeCategoryToken>Z</EscapeCategoryToken> <CloseBraceToken>}</CloseBraceToken> </CategoryEscape> </Sequence> <CloseBracketToken>]</CloseBracketToken> </NegatedCharacterClass> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..32)"" Text=""[^\f\n\r\t\v\x85\p{Z}]"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest63() { Test(@"@""(\s|$)""", @"<Tree> <CompilationUnit> <Sequence> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Alternation> <Sequence> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>s</TextToken> </CharacterClassEscape> </Sequence> <BarToken>|</BarToken> <Sequence> <EndAnchor> <DollarToken>$</DollarToken> </EndAnchor> </Sequence> </Alternation> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..16)"" Text=""(\s|$)"" /> <Capture Name=""1"" Span=""[10..16)"" Text=""(\s|$)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest64() { Test(@"@""\b\w+(e)?s(\s|$)""", @"<Tree> <CompilationUnit> <Sequence> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>b</TextToken> </AnchorEscape> <OneOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>w</TextToken> </CharacterClassEscape> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> <ZeroOrOneQuantifier> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <Text> <TextToken>e</TextToken> </Text> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <QuestionToken>?</QuestionToken> </ZeroOrOneQuantifier> <Text> <TextToken>s</TextToken> </Text> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Alternation> <Sequence> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>s</TextToken> </CharacterClassEscape> </Sequence> <BarToken>|</BarToken> <Sequence> <EndAnchor> <DollarToken>$</DollarToken> </EndAnchor> </Sequence> </Alternation> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..26)"" Text=""\b\w+(e)?s(\s|$)"" /> <Capture Name=""1"" Span=""[15..18)"" Text=""(e)"" /> <Capture Name=""2"" Span=""[20..26)"" Text=""(\s|$)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest65() { Test(@"@""[ \f\n\r\t\v]""", @"<Tree> <CompilationUnit> <Sequence> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <Text> <TextToken> </TextToken> </Text> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken>f</TextToken> </SimpleEscape> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken>n</TextToken> </SimpleEscape> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken>r</TextToken> </SimpleEscape> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken>t</TextToken> </SimpleEscape> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken>v</TextToken> </SimpleEscape> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..23)"" Text=""[ \f\n\r\t\v]"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest66() { Test(@"@""(\W){1,2}""", @"<Tree> <CompilationUnit> <Sequence> <ClosedRangeNumericQuantifier> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>W</TextToken> </CharacterClassEscape> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <OpenBraceToken>{</OpenBraceToken> <NumberToken value=""1"">1</NumberToken> <CommaToken>,</CommaToken> <NumberToken value=""2"">2</NumberToken> <CloseBraceToken>}</CloseBraceToken> </ClosedRangeNumericQuantifier> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..19)"" Text=""(\W){1,2}"" /> <Capture Name=""1"" Span=""[10..14)"" Text=""(\W)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest67() { Test(@"@""(\w+)""", @"<Tree> <CompilationUnit> <Sequence> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <OneOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>w</TextToken> </CharacterClassEscape> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..15)"" Text=""(\w+)"" /> <Capture Name=""1"" Span=""[10..15)"" Text=""(\w+)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest68() { Test(@"@""\b""", @"<Tree> <CompilationUnit> <Sequence> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>b</TextToken> </AnchorEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..12)"" Text=""\b"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest69() { Test(@"@""\b(\w+)(\W){1,2}""", @"<Tree> <CompilationUnit> <Sequence> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>b</TextToken> </AnchorEscape> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <OneOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>w</TextToken> </CharacterClassEscape> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <ClosedRangeNumericQuantifier> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>W</TextToken> </CharacterClassEscape> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <OpenBraceToken>{</OpenBraceToken> <NumberToken value=""1"">1</NumberToken> <CommaToken>,</CommaToken> <NumberToken value=""2"">2</NumberToken> <CloseBraceToken>}</CloseBraceToken> </ClosedRangeNumericQuantifier> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..26)"" Text=""\b(\w+)(\W){1,2}"" /> <Capture Name=""1"" Span=""[12..17)"" Text=""(\w+)"" /> <Capture Name=""2"" Span=""[17..21)"" Text=""(\W)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest70() { Test(@"@""(?>(\w)\1+).\b""", @"<Tree> <CompilationUnit> <Sequence> <AtomicGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <GreaterThanToken>&gt;</GreaterThanToken> <Sequence> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>w</TextToken> </CharacterClassEscape> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <OneOrMoreQuantifier> <BackreferenceEscape> <BackslashToken>\</BackslashToken> <NumberToken value=""1"">1</NumberToken> </BackreferenceEscape> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> </Sequence> <CloseParenToken>)</CloseParenToken> </AtomicGrouping> <Wildcard> <DotToken>.</DotToken> </Wildcard> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>b</TextToken> </AnchorEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..24)"" Text=""(?&gt;(\w)\1+).\b"" /> <Capture Name=""1"" Span=""[13..17)"" Text=""(\w)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest71() { Test(@"@""(\b(\w+)\W+)+""", @"<Tree> <CompilationUnit> <Sequence> <OneOrMoreQuantifier> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>b</TextToken> </AnchorEscape> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <OneOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>w</TextToken> </CharacterClassEscape> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <OneOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>W</TextToken> </CharacterClassEscape> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..23)"" Text=""(\b(\w+)\W+)+"" /> <Capture Name=""1"" Span=""[10..22)"" Text=""(\b(\w+)\W+)"" /> <Capture Name=""2"" Span=""[13..18)"" Text=""(\w+)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest72() { Test(@"@""(\w)\1+.\b""", @"<Tree> <CompilationUnit> <Sequence> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>w</TextToken> </CharacterClassEscape> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <OneOrMoreQuantifier> <BackreferenceEscape> <BackslashToken>\</BackslashToken> <NumberToken value=""1"">1</NumberToken> </BackreferenceEscape> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> <Wildcard> <DotToken>.</DotToken> </Wildcard> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>b</TextToken> </AnchorEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..20)"" Text=""(\w)\1+.\b"" /> <Capture Name=""1"" Span=""[10..14)"" Text=""(\w)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest73() { Test(@"@""\p{Sc}*(\s?\d+[.,]?\d*)\p{Sc}*""", @"<Tree> <CompilationUnit> <Sequence> <ZeroOrMoreQuantifier> <CategoryEscape> <BackslashToken>\</BackslashToken> <TextToken>p</TextToken> <OpenBraceToken>{</OpenBraceToken> <EscapeCategoryToken>Sc</EscapeCategoryToken> <CloseBraceToken>}</CloseBraceToken> </CategoryEscape> <AsteriskToken>*</AsteriskToken> </ZeroOrMoreQuantifier> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <ZeroOrOneQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>s</TextToken> </CharacterClassEscape> <QuestionToken>?</QuestionToken> </ZeroOrOneQuantifier> <OneOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>d</TextToken> </CharacterClassEscape> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> <ZeroOrOneQuantifier> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <Text> <TextToken>.,</TextToken> </Text> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> <QuestionToken>?</QuestionToken> </ZeroOrOneQuantifier> <ZeroOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>d</TextToken> </CharacterClassEscape> <AsteriskToken>*</AsteriskToken> </ZeroOrMoreQuantifier> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <ZeroOrMoreQuantifier> <CategoryEscape> <BackslashToken>\</BackslashToken> <TextToken>p</TextToken> <OpenBraceToken>{</OpenBraceToken> <EscapeCategoryToken>Sc</EscapeCategoryToken> <CloseBraceToken>}</CloseBraceToken> </CategoryEscape> <AsteriskToken>*</AsteriskToken> </ZeroOrMoreQuantifier> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..40)"" Text=""\p{Sc}*(\s?\d+[.,]?\d*)\p{Sc}*"" /> <Capture Name=""1"" Span=""[17..33)"" Text=""(\s?\d+[.,]?\d*)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest74() { Test(@"@""p{Sc}*(?<amount>\s?\d+[.,]?\d*)\p{Sc}*""", @"<Tree> <CompilationUnit> <Sequence> <Text> <TextToken>p{Sc</TextToken> </Text> <ZeroOrMoreQuantifier> <Text> <TextToken>}</TextToken> </Text> <AsteriskToken>*</AsteriskToken> </ZeroOrMoreQuantifier> <CaptureGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <CaptureNameToken value=""amount"">amount</CaptureNameToken> <GreaterThanToken>&gt;</GreaterThanToken> <Sequence> <ZeroOrOneQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>s</TextToken> </CharacterClassEscape> <QuestionToken>?</QuestionToken> </ZeroOrOneQuantifier> <OneOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>d</TextToken> </CharacterClassEscape> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> <ZeroOrOneQuantifier> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <Text> <TextToken>.,</TextToken> </Text> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> <QuestionToken>?</QuestionToken> </ZeroOrOneQuantifier> <ZeroOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>d</TextToken> </CharacterClassEscape> <AsteriskToken>*</AsteriskToken> </ZeroOrMoreQuantifier> </Sequence> <CloseParenToken>)</CloseParenToken> </CaptureGrouping> <ZeroOrMoreQuantifier> <CategoryEscape> <BackslashToken>\</BackslashToken> <TextToken>p</TextToken> <OpenBraceToken>{</OpenBraceToken> <EscapeCategoryToken>Sc</EscapeCategoryToken> <CloseBraceToken>}</CloseBraceToken> </CategoryEscape> <AsteriskToken>*</AsteriskToken> </ZeroOrMoreQuantifier> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..48)"" Text=""p{Sc}*(?&lt;amount&gt;\s?\d+[.,]?\d*)\p{Sc}*"" /> <Capture Name=""1"" Span=""[16..41)"" Text=""(?&lt;amount&gt;\s?\d+[.,]?\d*)"" /> <Capture Name=""amount"" Span=""[16..41)"" Text=""(?&lt;amount&gt;\s?\d+[.,]?\d*)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest75() { Test(@"@""^(\w+\s?)+$""", @"<Tree> <CompilationUnit> <Sequence> <StartAnchor> <CaretToken>^</CaretToken> </StartAnchor> <OneOrMoreQuantifier> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <OneOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>w</TextToken> </CharacterClassEscape> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> <ZeroOrOneQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>s</TextToken> </CharacterClassEscape> <QuestionToken>?</QuestionToken> </ZeroOrOneQuantifier> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> <EndAnchor> <DollarToken>$</DollarToken> </EndAnchor> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..21)"" Text=""^(\w+\s?)+$"" /> <Capture Name=""1"" Span=""[11..19)"" Text=""(\w+\s?)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest76() { Test(@"@""(?ix) d \w+ \s""", @"<Tree> <CompilationUnit> <Sequence> <SimpleOptionsGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <OptionsToken>ix</OptionsToken> <CloseParenToken>)</CloseParenToken> </SimpleOptionsGrouping> <Text> <TextToken> <Trivia> <WhitespaceTrivia> </WhitespaceTrivia> </Trivia>d</TextToken> </Text> <OneOrMoreQuantifier> <CharacterClassEscape> <BackslashToken> <Trivia> <WhitespaceTrivia> </WhitespaceTrivia> </Trivia>\</BackslashToken> <TextToken>w</TextToken> </CharacterClassEscape> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> <CharacterClassEscape> <BackslashToken> <Trivia> <WhitespaceTrivia> </WhitespaceTrivia> </Trivia>\</BackslashToken> <TextToken>s</TextToken> </CharacterClassEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..24)"" Text=""(?ix) d \w+ \s"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest77() { Test(@"@""\b(?ix: d \w+)\s""", @"<Tree> <CompilationUnit> <Sequence> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>b</TextToken> </AnchorEscape> <NestedOptionsGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <OptionsToken>ix</OptionsToken> <ColonToken>:</ColonToken> <Sequence> <Text> <TextToken> <Trivia> <WhitespaceTrivia> </WhitespaceTrivia> </Trivia>d</TextToken> </Text> <OneOrMoreQuantifier> <CharacterClassEscape> <BackslashToken> <Trivia> <WhitespaceTrivia> </WhitespaceTrivia> </Trivia>\</BackslashToken> <TextToken>w</TextToken> </CharacterClassEscape> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> </Sequence> <CloseParenToken>)</CloseParenToken> </NestedOptionsGrouping> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>s</TextToken> </CharacterClassEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..26)"" Text=""\b(?ix: d \w+)\s"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest78() { Test(@"@""\bthe\w*\b""", @"<Tree> <CompilationUnit> <Sequence> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>b</TextToken> </AnchorEscape> <Text> <TextToken>the</TextToken> </Text> <ZeroOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>w</TextToken> </CharacterClassEscape> <AsteriskToken>*</AsteriskToken> </ZeroOrMoreQuantifier> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>b</TextToken> </AnchorEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..20)"" Text=""\bthe\w*\b"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest79() { Test(@"@""\b(?i:t)he\w*\b""", @"<Tree> <CompilationUnit> <Sequence> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>b</TextToken> </AnchorEscape> <NestedOptionsGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <OptionsToken>i</OptionsToken> <ColonToken>:</ColonToken> <Sequence> <Text> <TextToken>t</TextToken> </Text> </Sequence> <CloseParenToken>)</CloseParenToken> </NestedOptionsGrouping> <Text> <TextToken>he</TextToken> </Text> <ZeroOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>w</TextToken> </CharacterClassEscape> <AsteriskToken>*</AsteriskToken> </ZeroOrMoreQuantifier> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>b</TextToken> </AnchorEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..25)"" Text=""\b(?i:t)he\w*\b"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest80() { Test(@"@""^(\w+)\s(\d+)$""", @"<Tree> <CompilationUnit> <Sequence> <StartAnchor> <CaretToken>^</CaretToken> </StartAnchor> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <OneOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>w</TextToken> </CharacterClassEscape> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>s</TextToken> </CharacterClassEscape> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <OneOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>d</TextToken> </CharacterClassEscape> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <EndAnchor> <DollarToken>$</DollarToken> </EndAnchor> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..24)"" Text=""^(\w+)\s(\d+)$"" /> <Capture Name=""1"" Span=""[11..16)"" Text=""(\w+)"" /> <Capture Name=""2"" Span=""[18..23)"" Text=""(\d+)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest81() { Test(@"@""^(\w+)\s(\d+)\r*$""", @"<Tree> <CompilationUnit> <Sequence> <StartAnchor> <CaretToken>^</CaretToken> </StartAnchor> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <OneOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>w</TextToken> </CharacterClassEscape> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>s</TextToken> </CharacterClassEscape> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <OneOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>d</TextToken> </CharacterClassEscape> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <ZeroOrMoreQuantifier> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken>r</TextToken> </SimpleEscape> <AsteriskToken>*</AsteriskToken> </ZeroOrMoreQuantifier> <EndAnchor> <DollarToken>$</DollarToken> </EndAnchor> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..27)"" Text=""^(\w+)\s(\d+)\r*$"" /> <Capture Name=""1"" Span=""[11..16)"" Text=""(\w+)"" /> <Capture Name=""2"" Span=""[18..23)"" Text=""(\d+)"" /> </Captures> </Tree>", RegexOptions.Multiline); } [Fact] public void ReferenceTest82() { Test(@"@""(?m)^(\w+)\s(\d+)\r*$""", @"<Tree> <CompilationUnit> <Sequence> <SimpleOptionsGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <OptionsToken>m</OptionsToken> <CloseParenToken>)</CloseParenToken> </SimpleOptionsGrouping> <StartAnchor> <CaretToken>^</CaretToken> </StartAnchor> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <OneOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>w</TextToken> </CharacterClassEscape> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>s</TextToken> </CharacterClassEscape> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <OneOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>d</TextToken> </CharacterClassEscape> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <ZeroOrMoreQuantifier> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken>r</TextToken> </SimpleEscape> <AsteriskToken>*</AsteriskToken> </ZeroOrMoreQuantifier> <EndAnchor> <DollarToken>$</DollarToken> </EndAnchor> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..31)"" Text=""(?m)^(\w+)\s(\d+)\r*$"" /> <Capture Name=""1"" Span=""[15..20)"" Text=""(\w+)"" /> <Capture Name=""2"" Span=""[22..27)"" Text=""(\d+)"" /> </Captures> </Tree>", RegexOptions.Multiline); } [Fact] public void ReferenceTest83() { Test(@"@""(?s)^.+""", @"<Tree> <CompilationUnit> <Sequence> <SimpleOptionsGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <OptionsToken>s</OptionsToken> <CloseParenToken>)</CloseParenToken> </SimpleOptionsGrouping> <StartAnchor> <CaretToken>^</CaretToken> </StartAnchor> <OneOrMoreQuantifier> <Wildcard> <DotToken>.</DotToken> </Wildcard> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..17)"" Text=""(?s)^.+"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest84() { Test(@"@""\b(\d{2}-)*(?(1)\d{7}|\d{3}-\d{2}-\d{4})\b""", @"<Tree> <CompilationUnit> <Sequence> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>b</TextToken> </AnchorEscape> <ZeroOrMoreQuantifier> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <ExactNumericQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>d</TextToken> </CharacterClassEscape> <OpenBraceToken>{</OpenBraceToken> <NumberToken value=""2"">2</NumberToken> <CloseBraceToken>}</CloseBraceToken> </ExactNumericQuantifier> <Text> <TextToken>-</TextToken> </Text> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <AsteriskToken>*</AsteriskToken> </ZeroOrMoreQuantifier> <ConditionalCaptureGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <OpenParenToken>(</OpenParenToken> <NumberToken value=""1"">1</NumberToken> <CloseParenToken>)</CloseParenToken> <Alternation> <Sequence> <ExactNumericQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>d</TextToken> </CharacterClassEscape> <OpenBraceToken>{</OpenBraceToken> <NumberToken value=""7"">7</NumberToken> <CloseBraceToken>}</CloseBraceToken> </ExactNumericQuantifier> </Sequence> <BarToken>|</BarToken> <Sequence> <ExactNumericQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>d</TextToken> </CharacterClassEscape> <OpenBraceToken>{</OpenBraceToken> <NumberToken value=""3"">3</NumberToken> <CloseBraceToken>}</CloseBraceToken> </ExactNumericQuantifier> <Text> <TextToken>-</TextToken> </Text> <ExactNumericQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>d</TextToken> </CharacterClassEscape> <OpenBraceToken>{</OpenBraceToken> <NumberToken value=""2"">2</NumberToken> <CloseBraceToken>}</CloseBraceToken> </ExactNumericQuantifier> <Text> <TextToken>-</TextToken> </Text> <ExactNumericQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>d</TextToken> </CharacterClassEscape> <OpenBraceToken>{</OpenBraceToken> <NumberToken value=""4"">4</NumberToken> <CloseBraceToken>}</CloseBraceToken> </ExactNumericQuantifier> </Sequence> </Alternation> <CloseParenToken>)</CloseParenToken> </ConditionalCaptureGrouping> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>b</TextToken> </AnchorEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..52)"" Text=""\b(\d{2}-)*(?(1)\d{7}|\d{3}-\d{2}-\d{4})\b"" /> <Capture Name=""1"" Span=""[12..20)"" Text=""(\d{2}-)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest85() { Test(@"@""\b\(?((\w+),?\s?)+[\.!?]\)?""", @"<Tree> <CompilationUnit> <Sequence> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>b</TextToken> </AnchorEscape> <ZeroOrOneQuantifier> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken>(</TextToken> </SimpleEscape> <QuestionToken>?</QuestionToken> </ZeroOrOneQuantifier> <OneOrMoreQuantifier> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <OneOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>w</TextToken> </CharacterClassEscape> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <ZeroOrOneQuantifier> <Text> <TextToken>,</TextToken> </Text> <QuestionToken>?</QuestionToken> </ZeroOrOneQuantifier> <ZeroOrOneQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>s</TextToken> </CharacterClassEscape> <QuestionToken>?</QuestionToken> </ZeroOrOneQuantifier> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken>.</TextToken> </SimpleEscape> <Text> <TextToken>!?</TextToken> </Text> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> <ZeroOrOneQuantifier> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken>)</TextToken> </SimpleEscape> <QuestionToken>?</QuestionToken> </ZeroOrOneQuantifier> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..37)"" Text=""\b\(?((\w+),?\s?)+[\.!?]\)?"" /> <Capture Name=""1"" Span=""[15..27)"" Text=""((\w+),?\s?)"" /> <Capture Name=""2"" Span=""[16..21)"" Text=""(\w+)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest86() { Test(@"@""(?n)\b\(?((?>\w+),?\s?)+[\.!?]\)?""", @"<Tree> <CompilationUnit> <Sequence> <SimpleOptionsGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <OptionsToken>n</OptionsToken> <CloseParenToken>)</CloseParenToken> </SimpleOptionsGrouping> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>b</TextToken> </AnchorEscape> <ZeroOrOneQuantifier> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken>(</TextToken> </SimpleEscape> <QuestionToken>?</QuestionToken> </ZeroOrOneQuantifier> <OneOrMoreQuantifier> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <AtomicGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <GreaterThanToken>&gt;</GreaterThanToken> <Sequence> <OneOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>w</TextToken> </CharacterClassEscape> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> </Sequence> <CloseParenToken>)</CloseParenToken> </AtomicGrouping> <ZeroOrOneQuantifier> <Text> <TextToken>,</TextToken> </Text> <QuestionToken>?</QuestionToken> </ZeroOrOneQuantifier> <ZeroOrOneQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>s</TextToken> </CharacterClassEscape> <QuestionToken>?</QuestionToken> </ZeroOrOneQuantifier> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken>.</TextToken> </SimpleEscape> <Text> <TextToken>!?</TextToken> </Text> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> <ZeroOrOneQuantifier> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken>)</TextToken> </SimpleEscape> <QuestionToken>?</QuestionToken> </ZeroOrOneQuantifier> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..43)"" Text=""(?n)\b\(?((?&gt;\w+),?\s?)+[\.!?]\)?"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest87() { Test(@"@""\b\(?(?n:(?>\w+),?\s?)+[\.!?]\)?""", @"<Tree> <CompilationUnit> <Sequence> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>b</TextToken> </AnchorEscape> <ZeroOrOneQuantifier> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken>(</TextToken> </SimpleEscape> <QuestionToken>?</QuestionToken> </ZeroOrOneQuantifier> <OneOrMoreQuantifier> <NestedOptionsGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <OptionsToken>n</OptionsToken> <ColonToken>:</ColonToken> <Sequence> <AtomicGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <GreaterThanToken>&gt;</GreaterThanToken> <Sequence> <OneOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>w</TextToken> </CharacterClassEscape> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> </Sequence> <CloseParenToken>)</CloseParenToken> </AtomicGrouping> <ZeroOrOneQuantifier> <Text> <TextToken>,</TextToken> </Text> <QuestionToken>?</QuestionToken> </ZeroOrOneQuantifier> <ZeroOrOneQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>s</TextToken> </CharacterClassEscape> <QuestionToken>?</QuestionToken> </ZeroOrOneQuantifier> </Sequence> <CloseParenToken>)</CloseParenToken> </NestedOptionsGrouping> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken>.</TextToken> </SimpleEscape> <Text> <TextToken>!?</TextToken> </Text> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> <ZeroOrOneQuantifier> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken>)</TextToken> </SimpleEscape> <QuestionToken>?</QuestionToken> </ZeroOrOneQuantifier> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..42)"" Text=""\b\(?(?n:(?&gt;\w+),?\s?)+[\.!?]\)?"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest88() { Test(@"@""\b\(?((?>\w+),?\s?)+[\.!?]\)?""", @"<Tree> <CompilationUnit> <Sequence> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>b</TextToken> </AnchorEscape> <ZeroOrOneQuantifier> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken>(</TextToken> </SimpleEscape> <QuestionToken>?</QuestionToken> </ZeroOrOneQuantifier> <OneOrMoreQuantifier> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <AtomicGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <GreaterThanToken>&gt;</GreaterThanToken> <Sequence> <OneOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>w</TextToken> </CharacterClassEscape> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> </Sequence> <CloseParenToken>)</CloseParenToken> </AtomicGrouping> <ZeroOrOneQuantifier> <Text> <TextToken>,</TextToken> </Text> <QuestionToken>?</QuestionToken> </ZeroOrOneQuantifier> <ZeroOrOneQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>s</TextToken> </CharacterClassEscape> <QuestionToken>?</QuestionToken> </ZeroOrOneQuantifier> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken>.</TextToken> </SimpleEscape> <Text> <TextToken>!?</TextToken> </Text> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> <ZeroOrOneQuantifier> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken>)</TextToken> </SimpleEscape> <QuestionToken>?</QuestionToken> </ZeroOrOneQuantifier> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..39)"" Text=""\b\(?((?&gt;\w+),?\s?)+[\.!?]\)?"" /> <Capture Name=""1"" Span=""[15..29)"" Text=""((?&gt;\w+),?\s?)"" /> </Captures> </Tree>", RegexOptions.IgnorePatternWhitespace); } [Fact] public void ReferenceTest89() { Test(@"@""(?x)\b \(? ( (?>\w+) ,?\s? )+ [\.!?] \)? # Matches an entire sentence.""", @"<Tree> <CompilationUnit> <Sequence> <SimpleOptionsGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <OptionsToken>x</OptionsToken> <CloseParenToken>)</CloseParenToken> </SimpleOptionsGrouping> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>b</TextToken> </AnchorEscape> <ZeroOrOneQuantifier> <SimpleEscape> <BackslashToken> <Trivia> <WhitespaceTrivia> </WhitespaceTrivia> </Trivia>\</BackslashToken> <TextToken>(</TextToken> </SimpleEscape> <QuestionToken>?</QuestionToken> </ZeroOrOneQuantifier> <OneOrMoreQuantifier> <SimpleGrouping> <OpenParenToken> <Trivia> <WhitespaceTrivia> </WhitespaceTrivia> </Trivia>(</OpenParenToken> <Sequence> <AtomicGrouping> <OpenParenToken> <Trivia> <WhitespaceTrivia> </WhitespaceTrivia> </Trivia>(</OpenParenToken> <QuestionToken>?</QuestionToken> <GreaterThanToken>&gt;</GreaterThanToken> <Sequence> <OneOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>w</TextToken> </CharacterClassEscape> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> </Sequence> <CloseParenToken>)</CloseParenToken> </AtomicGrouping> <ZeroOrOneQuantifier> <Text> <TextToken> <Trivia> <WhitespaceTrivia> </WhitespaceTrivia> </Trivia>,</TextToken> </Text> <QuestionToken>?</QuestionToken> </ZeroOrOneQuantifier> <ZeroOrOneQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>s</TextToken> </CharacterClassEscape> <QuestionToken>?</QuestionToken> </ZeroOrOneQuantifier> </Sequence> <CloseParenToken> <Trivia> <WhitespaceTrivia> </WhitespaceTrivia> </Trivia>)</CloseParenToken> </SimpleGrouping> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> <CharacterClass> <OpenBracketToken> <Trivia> <WhitespaceTrivia> </WhitespaceTrivia> </Trivia>[</OpenBracketToken> <Sequence> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken>.</TextToken> </SimpleEscape> <Text> <TextToken>!?</TextToken> </Text> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> <ZeroOrOneQuantifier> <SimpleEscape> <BackslashToken> <Trivia> <WhitespaceTrivia> </WhitespaceTrivia> </Trivia>\</BackslashToken> <TextToken>)</TextToken> </SimpleEscape> <QuestionToken>?</QuestionToken> </ZeroOrOneQuantifier> </Sequence> <EndOfFile> <Trivia> <WhitespaceTrivia> </WhitespaceTrivia> <CommentTrivia># Matches an entire sentence.</CommentTrivia> </Trivia> </EndOfFile> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..81)"" Text=""(?x)\b \(? ( (?&gt;\w+) ,?\s? )+ [\.!?] \)? # Matches an entire sentence."" /> <Capture Name=""1"" Span=""[21..38)"" Text=""( (?&gt;\w+) ,?\s? )"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest90() { Test(@"@""\bb\w+\s""", @"<Tree> <CompilationUnit> <Sequence> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>b</TextToken> </AnchorEscape> <Text> <TextToken>b</TextToken> </Text> <OneOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>w</TextToken> </CharacterClassEscape> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>s</TextToken> </CharacterClassEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..18)"" Text=""\bb\w+\s"" /> </Captures> </Tree>", RegexOptions.RightToLeft); } [Fact] public void ReferenceTest91() { Test(@"@""(?<=\d{1,2}\s)\w+,?\s\d{4}""", @"<Tree> <CompilationUnit> <Sequence> <PositiveLookbehindGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <EqualsToken>=</EqualsToken> <Sequence> <ClosedRangeNumericQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>d</TextToken> </CharacterClassEscape> <OpenBraceToken>{</OpenBraceToken> <NumberToken value=""1"">1</NumberToken> <CommaToken>,</CommaToken> <NumberToken value=""2"">2</NumberToken> <CloseBraceToken>}</CloseBraceToken> </ClosedRangeNumericQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>s</TextToken> </CharacterClassEscape> </Sequence> <CloseParenToken>)</CloseParenToken> </PositiveLookbehindGrouping> <OneOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>w</TextToken> </CharacterClassEscape> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> <ZeroOrOneQuantifier> <Text> <TextToken>,</TextToken> </Text> <QuestionToken>?</QuestionToken> </ZeroOrOneQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>s</TextToken> </CharacterClassEscape> <ExactNumericQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>d</TextToken> </CharacterClassEscape> <OpenBraceToken>{</OpenBraceToken> <NumberToken value=""4"">4</NumberToken> <CloseBraceToken>}</CloseBraceToken> </ExactNumericQuantifier> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..36)"" Text=""(?&lt;=\d{1,2}\s)\w+,?\s\d{4}"" /> </Captures> </Tree>", RegexOptions.RightToLeft); } [Fact] public void ReferenceTest92() { Test(@"@""\b(\w+\s*)+""", @"<Tree> <CompilationUnit> <Sequence> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>b</TextToken> </AnchorEscape> <OneOrMoreQuantifier> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <OneOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>w</TextToken> </CharacterClassEscape> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> <ZeroOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>s</TextToken> </CharacterClassEscape> <AsteriskToken>*</AsteriskToken> </ZeroOrMoreQuantifier> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..21)"" Text=""\b(\w+\s*)+"" /> <Capture Name=""1"" Span=""[12..20)"" Text=""(\w+\s*)"" /> </Captures> </Tree>", RegexOptions.ECMAScript); } [Fact] public void ReferenceTest93() { Test(@"@""((a+)(\1) ?)+""", @"<Tree> <CompilationUnit> <Sequence> <OneOrMoreQuantifier> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <OneOrMoreQuantifier> <Text> <TextToken>a</TextToken> </Text> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <BackreferenceEscape> <BackslashToken>\</BackslashToken> <NumberToken value=""1"">1</NumberToken> </BackreferenceEscape> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <ZeroOrOneQuantifier> <Text> <TextToken> </TextToken> </Text> <QuestionToken>?</QuestionToken> </ZeroOrOneQuantifier> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..23)"" Text=""((a+)(\1) ?)+"" /> <Capture Name=""1"" Span=""[10..22)"" Text=""((a+)(\1) ?)"" /> <Capture Name=""2"" Span=""[11..15)"" Text=""(a+)"" /> <Capture Name=""3"" Span=""[15..19)"" Text=""(\1)"" /> </Captures> </Tree>", RegexOptions.ECMAScript); } [Fact] public void ReferenceTest94() { Test(@"@""\b(D\w+)\s(d\w+)\b""", @"<Tree> <CompilationUnit> <Sequence> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>b</TextToken> </AnchorEscape> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <Text> <TextToken>D</TextToken> </Text> <OneOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>w</TextToken> </CharacterClassEscape> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>s</TextToken> </CharacterClassEscape> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <Text> <TextToken>d</TextToken> </Text> <OneOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>w</TextToken> </CharacterClassEscape> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>b</TextToken> </AnchorEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..28)"" Text=""\b(D\w+)\s(d\w+)\b"" /> <Capture Name=""1"" Span=""[12..18)"" Text=""(D\w+)"" /> <Capture Name=""2"" Span=""[20..26)"" Text=""(d\w+)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest95() { Test(@"@""\b(D\w+)(?ixn) \s (d\w+) \b""", @"<Tree> <CompilationUnit> <Sequence> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>b</TextToken> </AnchorEscape> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <Text> <TextToken>D</TextToken> </Text> <OneOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>w</TextToken> </CharacterClassEscape> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <SimpleOptionsGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <OptionsToken>ixn</OptionsToken> <CloseParenToken>)</CloseParenToken> </SimpleOptionsGrouping> <CharacterClassEscape> <BackslashToken> <Trivia> <WhitespaceTrivia> </WhitespaceTrivia> </Trivia>\</BackslashToken> <TextToken>s</TextToken> </CharacterClassEscape> <SimpleGrouping> <OpenParenToken> <Trivia> <WhitespaceTrivia> </WhitespaceTrivia> </Trivia>(</OpenParenToken> <Sequence> <Text> <TextToken>d</TextToken> </Text> <OneOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>w</TextToken> </CharacterClassEscape> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <AnchorEscape> <BackslashToken> <Trivia> <WhitespaceTrivia> </WhitespaceTrivia> </Trivia>\</BackslashToken> <TextToken>b</TextToken> </AnchorEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..37)"" Text=""\b(D\w+)(?ixn) \s (d\w+) \b"" /> <Capture Name=""1"" Span=""[12..18)"" Text=""(D\w+)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest96() { Test(@"@""\b((?# case-sensitive comparison)D\w+)\s((?#case-insensitive comparison)d\w+)\b""", @"<Tree> <CompilationUnit> <Sequence> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>b</TextToken> </AnchorEscape> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <Text> <TextToken> <Trivia> <CommentTrivia>(?# case-sensitive comparison)</CommentTrivia> </Trivia>D</TextToken> </Text> <OneOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>w</TextToken> </CharacterClassEscape> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>s</TextToken> </CharacterClassEscape> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <Text> <TextToken> <Trivia> <CommentTrivia>(?#case-insensitive comparison)</CommentTrivia> </Trivia>d</TextToken> </Text> <OneOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>w</TextToken> </CharacterClassEscape> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>b</TextToken> </AnchorEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..89)"" Text=""\b((?# case-sensitive comparison)D\w+)\s((?#case-insensitive comparison)d\w+)\b"" /> <Capture Name=""1"" Span=""[12..48)"" Text=""((?# case-sensitive comparison)D\w+)"" /> <Capture Name=""2"" Span=""[50..87)"" Text=""((?#case-insensitive comparison)d\w+)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest97() { Test(@"@""\b\(?((?>\w+),?\s?)+[\.!?]\)?""", @"<Tree> <CompilationUnit> <Sequence> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>b</TextToken> </AnchorEscape> <ZeroOrOneQuantifier> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken>(</TextToken> </SimpleEscape> <QuestionToken>?</QuestionToken> </ZeroOrOneQuantifier> <OneOrMoreQuantifier> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <AtomicGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <GreaterThanToken>&gt;</GreaterThanToken> <Sequence> <OneOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>w</TextToken> </CharacterClassEscape> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> </Sequence> <CloseParenToken>)</CloseParenToken> </AtomicGrouping> <ZeroOrOneQuantifier> <Text> <TextToken>,</TextToken> </Text> <QuestionToken>?</QuestionToken> </ZeroOrOneQuantifier> <ZeroOrOneQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>s</TextToken> </CharacterClassEscape> <QuestionToken>?</QuestionToken> </ZeroOrOneQuantifier> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken>.</TextToken> </SimpleEscape> <Text> <TextToken>!?</TextToken> </Text> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> <ZeroOrOneQuantifier> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken>)</TextToken> </SimpleEscape> <QuestionToken>?</QuestionToken> </ZeroOrOneQuantifier> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..39)"" Text=""\b\(?((?&gt;\w+),?\s?)+[\.!?]\)?"" /> <Capture Name=""1"" Span=""[15..29)"" Text=""((?&gt;\w+),?\s?)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest98() { Test(@"@""\b(?<n2>\d{2}-)*(?(n2)\d{7}|\d{3}-\d{2}-\d{4})\b""", @"<Tree> <CompilationUnit> <Sequence> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>b</TextToken> </AnchorEscape> <ZeroOrMoreQuantifier> <CaptureGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <CaptureNameToken value=""n2"">n2</CaptureNameToken> <GreaterThanToken>&gt;</GreaterThanToken> <Sequence> <ExactNumericQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>d</TextToken> </CharacterClassEscape> <OpenBraceToken>{</OpenBraceToken> <NumberToken value=""2"">2</NumberToken> <CloseBraceToken>}</CloseBraceToken> </ExactNumericQuantifier> <Text> <TextToken>-</TextToken> </Text> </Sequence> <CloseParenToken>)</CloseParenToken> </CaptureGrouping> <AsteriskToken>*</AsteriskToken> </ZeroOrMoreQuantifier> <ConditionalCaptureGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <OpenParenToken>(</OpenParenToken> <CaptureNameToken value=""n2"">n2</CaptureNameToken> <CloseParenToken>)</CloseParenToken> <Alternation> <Sequence> <ExactNumericQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>d</TextToken> </CharacterClassEscape> <OpenBraceToken>{</OpenBraceToken> <NumberToken value=""7"">7</NumberToken> <CloseBraceToken>}</CloseBraceToken> </ExactNumericQuantifier> </Sequence> <BarToken>|</BarToken> <Sequence> <ExactNumericQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>d</TextToken> </CharacterClassEscape> <OpenBraceToken>{</OpenBraceToken> <NumberToken value=""3"">3</NumberToken> <CloseBraceToken>}</CloseBraceToken> </ExactNumericQuantifier> <Text> <TextToken>-</TextToken> </Text> <ExactNumericQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>d</TextToken> </CharacterClassEscape> <OpenBraceToken>{</OpenBraceToken> <NumberToken value=""2"">2</NumberToken> <CloseBraceToken>}</CloseBraceToken> </ExactNumericQuantifier> <Text> <TextToken>-</TextToken> </Text> <ExactNumericQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>d</TextToken> </CharacterClassEscape> <OpenBraceToken>{</OpenBraceToken> <NumberToken value=""4"">4</NumberToken> <CloseBraceToken>}</CloseBraceToken> </ExactNumericQuantifier> </Sequence> </Alternation> <CloseParenToken>)</CloseParenToken> </ConditionalCaptureGrouping> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>b</TextToken> </AnchorEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..58)"" Text=""\b(?&lt;n2&gt;\d{2}-)*(?(n2)\d{7}|\d{3}-\d{2}-\d{4})\b"" /> <Capture Name=""1"" Span=""[12..25)"" Text=""(?&lt;n2&gt;\d{2}-)"" /> <Capture Name=""n2"" Span=""[12..25)"" Text=""(?&lt;n2&gt;\d{2}-)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest99() { Test(@"@""\b(\d{2}-\d{7}|\d{3}-\d{2}-\d{4})\b""", @"<Tree> <CompilationUnit> <Sequence> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>b</TextToken> </AnchorEscape> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Alternation> <Sequence> <ExactNumericQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>d</TextToken> </CharacterClassEscape> <OpenBraceToken>{</OpenBraceToken> <NumberToken value=""2"">2</NumberToken> <CloseBraceToken>}</CloseBraceToken> </ExactNumericQuantifier> <Text> <TextToken>-</TextToken> </Text> <ExactNumericQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>d</TextToken> </CharacterClassEscape> <OpenBraceToken>{</OpenBraceToken> <NumberToken value=""7"">7</NumberToken> <CloseBraceToken>}</CloseBraceToken> </ExactNumericQuantifier> </Sequence> <BarToken>|</BarToken> <Sequence> <ExactNumericQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>d</TextToken> </CharacterClassEscape> <OpenBraceToken>{</OpenBraceToken> <NumberToken value=""3"">3</NumberToken> <CloseBraceToken>}</CloseBraceToken> </ExactNumericQuantifier> <Text> <TextToken>-</TextToken> </Text> <ExactNumericQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>d</TextToken> </CharacterClassEscape> <OpenBraceToken>{</OpenBraceToken> <NumberToken value=""2"">2</NumberToken> <CloseBraceToken>}</CloseBraceToken> </ExactNumericQuantifier> <Text> <TextToken>-</TextToken> </Text> <ExactNumericQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>d</TextToken> </CharacterClassEscape> <OpenBraceToken>{</OpenBraceToken> <NumberToken value=""4"">4</NumberToken> <CloseBraceToken>}</CloseBraceToken> </ExactNumericQuantifier> </Sequence> </Alternation> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>b</TextToken> </AnchorEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..45)"" Text=""\b(\d{2}-\d{7}|\d{3}-\d{2}-\d{4})\b"" /> <Capture Name=""1"" Span=""[12..43)"" Text=""(\d{2}-\d{7}|\d{3}-\d{2}-\d{4})"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest100() { Test(@"@""\bgr(a|e)y\b""", @"<Tree> <CompilationUnit> <Sequence> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>b</TextToken> </AnchorEscape> <Text> <TextToken>gr</TextToken> </Text> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Alternation> <Sequence> <Text> <TextToken>a</TextToken> </Text> </Sequence> <BarToken>|</BarToken> <Sequence> <Text> <TextToken>e</TextToken> </Text> </Sequence> </Alternation> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <Text> <TextToken>y</TextToken> </Text> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>b</TextToken> </AnchorEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..22)"" Text=""\bgr(a|e)y\b"" /> <Capture Name=""1"" Span=""[14..19)"" Text=""(a|e)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest101() { Test(@"@""(?>(\w)\1+).\b""", @"<Tree> <CompilationUnit> <Sequence> <AtomicGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <GreaterThanToken>&gt;</GreaterThanToken> <Sequence> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>w</TextToken> </CharacterClassEscape> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <OneOrMoreQuantifier> <BackreferenceEscape> <BackslashToken>\</BackslashToken> <NumberToken value=""1"">1</NumberToken> </BackreferenceEscape> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> </Sequence> <CloseParenToken>)</CloseParenToken> </AtomicGrouping> <Wildcard> <DotToken>.</DotToken> </Wildcard> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>b</TextToken> </AnchorEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..24)"" Text=""(?&gt;(\w)\1+).\b"" /> <Capture Name=""1"" Span=""[13..17)"" Text=""(\w)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest102() { Test(@"@""(\b(\w+)\W+)+""", @"<Tree> <CompilationUnit> <Sequence> <OneOrMoreQuantifier> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>b</TextToken> </AnchorEscape> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <OneOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>w</TextToken> </CharacterClassEscape> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <OneOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>W</TextToken> </CharacterClassEscape> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..23)"" Text=""(\b(\w+)\W+)+"" /> <Capture Name=""1"" Span=""[10..22)"" Text=""(\b(\w+)\W+)"" /> <Capture Name=""2"" Span=""[13..18)"" Text=""(\w+)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest103() { Test(@"@""\b91*9*\b""", @"<Tree> <CompilationUnit> <Sequence> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>b</TextToken> </AnchorEscape> <Text> <TextToken>9</TextToken> </Text> <ZeroOrMoreQuantifier> <Text> <TextToken>1</TextToken> </Text> <AsteriskToken>*</AsteriskToken> </ZeroOrMoreQuantifier> <ZeroOrMoreQuantifier> <Text> <TextToken>9</TextToken> </Text> <AsteriskToken>*</AsteriskToken> </ZeroOrMoreQuantifier> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>b</TextToken> </AnchorEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..19)"" Text=""\b91*9*\b"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest104() { Test(@"@""\ban+\w*?\b""", @"<Tree> <CompilationUnit> <Sequence> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>b</TextToken> </AnchorEscape> <Text> <TextToken>a</TextToken> </Text> <OneOrMoreQuantifier> <Text> <TextToken>n</TextToken> </Text> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> <LazyQuantifier> <ZeroOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>w</TextToken> </CharacterClassEscape> <AsteriskToken>*</AsteriskToken> </ZeroOrMoreQuantifier> <QuestionToken>?</QuestionToken> </LazyQuantifier> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>b</TextToken> </AnchorEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..21)"" Text=""\ban+\w*?\b"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest105() { Test(@"@""\ban?\b""", @"<Tree> <CompilationUnit> <Sequence> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>b</TextToken> </AnchorEscape> <Text> <TextToken>a</TextToken> </Text> <ZeroOrOneQuantifier> <Text> <TextToken>n</TextToken> </Text> <QuestionToken>?</QuestionToken> </ZeroOrOneQuantifier> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>b</TextToken> </AnchorEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..17)"" Text=""\ban?\b"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest106() { Test(@"@""\b\d+\,\d{3}\b""", @"<Tree> <CompilationUnit> <Sequence> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>b</TextToken> </AnchorEscape> <OneOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>d</TextToken> </CharacterClassEscape> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken>,</TextToken> </SimpleEscape> <ExactNumericQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>d</TextToken> </CharacterClassEscape> <OpenBraceToken>{</OpenBraceToken> <NumberToken value=""3"">3</NumberToken> <CloseBraceToken>}</CloseBraceToken> </ExactNumericQuantifier> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>b</TextToken> </AnchorEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..24)"" Text=""\b\d+\,\d{3}\b"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest107() { Test(@"@""\b\d{2,}\b\D+""", @"<Tree> <CompilationUnit> <Sequence> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>b</TextToken> </AnchorEscape> <OpenRangeNumericQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>d</TextToken> </CharacterClassEscape> <OpenBraceToken>{</OpenBraceToken> <NumberToken value=""2"">2</NumberToken> <CommaToken>,</CommaToken> <CloseBraceToken>}</CloseBraceToken> </OpenRangeNumericQuantifier> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>b</TextToken> </AnchorEscape> <OneOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>D</TextToken> </CharacterClassEscape> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..23)"" Text=""\b\d{2,}\b\D+"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest108() { Test(@"@""(00\s){2,4}""", @"<Tree> <CompilationUnit> <Sequence> <ClosedRangeNumericQuantifier> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <Text> <TextToken>00</TextToken> </Text> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>s</TextToken> </CharacterClassEscape> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <OpenBraceToken>{</OpenBraceToken> <NumberToken value=""2"">2</NumberToken> <CommaToken>,</CommaToken> <NumberToken value=""4"">4</NumberToken> <CloseBraceToken>}</CloseBraceToken> </ClosedRangeNumericQuantifier> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..21)"" Text=""(00\s){2,4}"" /> <Capture Name=""1"" Span=""[10..16)"" Text=""(00\s)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest109() { Test(@"@""\b\w*?oo\w*?\b""", @"<Tree> <CompilationUnit> <Sequence> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>b</TextToken> </AnchorEscape> <LazyQuantifier> <ZeroOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>w</TextToken> </CharacterClassEscape> <AsteriskToken>*</AsteriskToken> </ZeroOrMoreQuantifier> <QuestionToken>?</QuestionToken> </LazyQuantifier> <Text> <TextToken>oo</TextToken> </Text> <LazyQuantifier> <ZeroOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>w</TextToken> </CharacterClassEscape> <AsteriskToken>*</AsteriskToken> </ZeroOrMoreQuantifier> <QuestionToken>?</QuestionToken> </LazyQuantifier> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>b</TextToken> </AnchorEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..24)"" Text=""\b\w*?oo\w*?\b"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest110() { Test(@"@""\b\w+?\b""", @"<Tree> <CompilationUnit> <Sequence> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>b</TextToken> </AnchorEscape> <LazyQuantifier> <OneOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>w</TextToken> </CharacterClassEscape> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> <QuestionToken>?</QuestionToken> </LazyQuantifier> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>b</TextToken> </AnchorEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..18)"" Text=""\b\w+?\b"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest111() { Test(@"@""^\s*(System.)??Console.Write(Line)??\(??""", @"<Tree> <CompilationUnit> <Sequence> <StartAnchor> <CaretToken>^</CaretToken> </StartAnchor> <ZeroOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>s</TextToken> </CharacterClassEscape> <AsteriskToken>*</AsteriskToken> </ZeroOrMoreQuantifier> <LazyQuantifier> <ZeroOrOneQuantifier> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <Text> <TextToken>System</TextToken> </Text> <Wildcard> <DotToken>.</DotToken> </Wildcard> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <QuestionToken>?</QuestionToken> </ZeroOrOneQuantifier> <QuestionToken>?</QuestionToken> </LazyQuantifier> <Text> <TextToken>Console</TextToken> </Text> <Wildcard> <DotToken>.</DotToken> </Wildcard> <Text> <TextToken>Write</TextToken> </Text> <LazyQuantifier> <ZeroOrOneQuantifier> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <Text> <TextToken>Line</TextToken> </Text> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <QuestionToken>?</QuestionToken> </ZeroOrOneQuantifier> <QuestionToken>?</QuestionToken> </LazyQuantifier> <LazyQuantifier> <ZeroOrOneQuantifier> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken>(</TextToken> </SimpleEscape> <QuestionToken>?</QuestionToken> </ZeroOrOneQuantifier> <QuestionToken>?</QuestionToken> </LazyQuantifier> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..50)"" Text=""^\s*(System.)??Console.Write(Line)??\(??"" /> <Capture Name=""1"" Span=""[14..23)"" Text=""(System.)"" /> <Capture Name=""2"" Span=""[38..44)"" Text=""(Line)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest112() { Test(@"@""(System.)??""", @"<Tree> <CompilationUnit> <Sequence> <LazyQuantifier> <ZeroOrOneQuantifier> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <Text> <TextToken>System</TextToken> </Text> <Wildcard> <DotToken>.</DotToken> </Wildcard> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <QuestionToken>?</QuestionToken> </ZeroOrOneQuantifier> <QuestionToken>?</QuestionToken> </LazyQuantifier> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..21)"" Text=""(System.)??"" /> <Capture Name=""1"" Span=""[10..19)"" Text=""(System.)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest113() { Test(@"@""\b(\w{3,}?\.){2}?\w{3,}?\b""", @"<Tree> <CompilationUnit> <Sequence> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>b</TextToken> </AnchorEscape> <LazyQuantifier> <ExactNumericQuantifier> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <LazyQuantifier> <OpenRangeNumericQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>w</TextToken> </CharacterClassEscape> <OpenBraceToken>{</OpenBraceToken> <NumberToken value=""3"">3</NumberToken> <CommaToken>,</CommaToken> <CloseBraceToken>}</CloseBraceToken> </OpenRangeNumericQuantifier> <QuestionToken>?</QuestionToken> </LazyQuantifier> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken>.</TextToken> </SimpleEscape> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <OpenBraceToken>{</OpenBraceToken> <NumberToken value=""2"">2</NumberToken> <CloseBraceToken>}</CloseBraceToken> </ExactNumericQuantifier> <QuestionToken>?</QuestionToken> </LazyQuantifier> <LazyQuantifier> <OpenRangeNumericQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>w</TextToken> </CharacterClassEscape> <OpenBraceToken>{</OpenBraceToken> <NumberToken value=""3"">3</NumberToken> <CommaToken>,</CommaToken> <CloseBraceToken>}</CloseBraceToken> </OpenRangeNumericQuantifier> <QuestionToken>?</QuestionToken> </LazyQuantifier> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>b</TextToken> </AnchorEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..36)"" Text=""\b(\w{3,}?\.){2}?\w{3,}?\b"" /> <Capture Name=""1"" Span=""[12..23)"" Text=""(\w{3,}?\.)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest114() { Test(@"@""\b[A-Z](\w*?\s*?){1,10}[.!?]""", @"<Tree> <CompilationUnit> <Sequence> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>b</TextToken> </AnchorEscape> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <CharacterClassRange> <Text> <TextToken>A</TextToken> </Text> <MinusToken>-</MinusToken> <Text> <TextToken>Z</TextToken> </Text> </CharacterClassRange> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> <ClosedRangeNumericQuantifier> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <LazyQuantifier> <ZeroOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>w</TextToken> </CharacterClassEscape> <AsteriskToken>*</AsteriskToken> </ZeroOrMoreQuantifier> <QuestionToken>?</QuestionToken> </LazyQuantifier> <LazyQuantifier> <ZeroOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>s</TextToken> </CharacterClassEscape> <AsteriskToken>*</AsteriskToken> </ZeroOrMoreQuantifier> <QuestionToken>?</QuestionToken> </LazyQuantifier> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <OpenBraceToken>{</OpenBraceToken> <NumberToken value=""1"">1</NumberToken> <CommaToken>,</CommaToken> <NumberToken value=""10"">10</NumberToken> <CloseBraceToken>}</CloseBraceToken> </ClosedRangeNumericQuantifier> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <Text> <TextToken>.!?</TextToken> </Text> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..38)"" Text=""\b[A-Z](\w*?\s*?){1,10}[.!?]"" /> <Capture Name=""1"" Span=""[17..27)"" Text=""(\w*?\s*?)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest115() { Test(@"@""b.*([0-9]{4})\b""", @"<Tree> <CompilationUnit> <Sequence> <Text> <TextToken>b</TextToken> </Text> <ZeroOrMoreQuantifier> <Wildcard> <DotToken>.</DotToken> </Wildcard> <AsteriskToken>*</AsteriskToken> </ZeroOrMoreQuantifier> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <ExactNumericQuantifier> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <CharacterClassRange> <Text> <TextToken>0</TextToken> </Text> <MinusToken>-</MinusToken> <Text> <TextToken>9</TextToken> </Text> </CharacterClassRange> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> <OpenBraceToken>{</OpenBraceToken> <NumberToken value=""4"">4</NumberToken> <CloseBraceToken>}</CloseBraceToken> </ExactNumericQuantifier> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>b</TextToken> </AnchorEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..25)"" Text=""b.*([0-9]{4})\b"" /> <Capture Name=""1"" Span=""[13..23)"" Text=""([0-9]{4})"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest116() { Test(@"@""\b.*?([0-9]{4})\b""", @"<Tree> <CompilationUnit> <Sequence> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>b</TextToken> </AnchorEscape> <LazyQuantifier> <ZeroOrMoreQuantifier> <Wildcard> <DotToken>.</DotToken> </Wildcard> <AsteriskToken>*</AsteriskToken> </ZeroOrMoreQuantifier> <QuestionToken>?</QuestionToken> </LazyQuantifier> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <ExactNumericQuantifier> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <CharacterClassRange> <Text> <TextToken>0</TextToken> </Text> <MinusToken>-</MinusToken> <Text> <TextToken>9</TextToken> </Text> </CharacterClassRange> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> <OpenBraceToken>{</OpenBraceToken> <NumberToken value=""4"">4</NumberToken> <CloseBraceToken>}</CloseBraceToken> </ExactNumericQuantifier> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>b</TextToken> </AnchorEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..27)"" Text=""\b.*?([0-9]{4})\b"" /> <Capture Name=""1"" Span=""[15..25)"" Text=""([0-9]{4})"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest117() { Test(@"@""(a?)*""", @"<Tree> <CompilationUnit> <Sequence> <ZeroOrMoreQuantifier> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <ZeroOrOneQuantifier> <Text> <TextToken>a</TextToken> </Text> <QuestionToken>?</QuestionToken> </ZeroOrOneQuantifier> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <AsteriskToken>*</AsteriskToken> </ZeroOrMoreQuantifier> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..15)"" Text=""(a?)*"" /> <Capture Name=""1"" Span=""[10..14)"" Text=""(a?)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest118() { Test(@"@""(a\1|(?(1)\1)){0,2}""", @"<Tree> <CompilationUnit> <Sequence> <ClosedRangeNumericQuantifier> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Alternation> <Sequence> <Text> <TextToken>a</TextToken> </Text> <BackreferenceEscape> <BackslashToken>\</BackslashToken> <NumberToken value=""1"">1</NumberToken> </BackreferenceEscape> </Sequence> <BarToken>|</BarToken> <Sequence> <ConditionalCaptureGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <OpenParenToken>(</OpenParenToken> <NumberToken value=""1"">1</NumberToken> <CloseParenToken>)</CloseParenToken> <Sequence> <BackreferenceEscape> <BackslashToken>\</BackslashToken> <NumberToken value=""1"">1</NumberToken> </BackreferenceEscape> </Sequence> <CloseParenToken>)</CloseParenToken> </ConditionalCaptureGrouping> </Sequence> </Alternation> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <OpenBraceToken>{</OpenBraceToken> <NumberToken value=""0"">0</NumberToken> <CommaToken>,</CommaToken> <NumberToken value=""2"">2</NumberToken> <CloseBraceToken>}</CloseBraceToken> </ClosedRangeNumericQuantifier> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..29)"" Text=""(a\1|(?(1)\1)){0,2}"" /> <Capture Name=""1"" Span=""[10..24)"" Text=""(a\1|(?(1)\1))"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest119() { Test(@"@""(a\1|(?(1)\1)){2}""", @"<Tree> <CompilationUnit> <Sequence> <ExactNumericQuantifier> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Alternation> <Sequence> <Text> <TextToken>a</TextToken> </Text> <BackreferenceEscape> <BackslashToken>\</BackslashToken> <NumberToken value=""1"">1</NumberToken> </BackreferenceEscape> </Sequence> <BarToken>|</BarToken> <Sequence> <ConditionalCaptureGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <OpenParenToken>(</OpenParenToken> <NumberToken value=""1"">1</NumberToken> <CloseParenToken>)</CloseParenToken> <Sequence> <BackreferenceEscape> <BackslashToken>\</BackslashToken> <NumberToken value=""1"">1</NumberToken> </BackreferenceEscape> </Sequence> <CloseParenToken>)</CloseParenToken> </ConditionalCaptureGrouping> </Sequence> </Alternation> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <OpenBraceToken>{</OpenBraceToken> <NumberToken value=""2"">2</NumberToken> <CloseBraceToken>}</CloseBraceToken> </ExactNumericQuantifier> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..27)"" Text=""(a\1|(?(1)\1)){2}"" /> <Capture Name=""1"" Span=""[10..24)"" Text=""(a\1|(?(1)\1))"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest120() { Test(@"@""(\w)\1""", @"<Tree> <CompilationUnit> <Sequence> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>w</TextToken> </CharacterClassEscape> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <BackreferenceEscape> <BackslashToken>\</BackslashToken> <NumberToken value=""1"">1</NumberToken> </BackreferenceEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..16)"" Text=""(\w)\1"" /> <Capture Name=""1"" Span=""[10..14)"" Text=""(\w)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest121() { Test(@"@""(?<char>\w)\k<char>""", @"<Tree> <CompilationUnit> <Sequence> <CaptureGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <CaptureNameToken value=""char"">char</CaptureNameToken> <GreaterThanToken>&gt;</GreaterThanToken> <Sequence> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>w</TextToken> </CharacterClassEscape> </Sequence> <CloseParenToken>)</CloseParenToken> </CaptureGrouping> <KCaptureEscape> <BackslashToken>\</BackslashToken> <TextToken>k</TextToken> <LessThanToken>&lt;</LessThanToken> <CaptureNameToken value=""char"">char</CaptureNameToken> <GreaterThanToken>&gt;</GreaterThanToken> </KCaptureEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..29)"" Text=""(?&lt;char&gt;\w)\k&lt;char&gt;"" /> <Capture Name=""1"" Span=""[10..21)"" Text=""(?&lt;char&gt;\w)"" /> <Capture Name=""char"" Span=""[10..21)"" Text=""(?&lt;char&gt;\w)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest122() { Test(@"@""(?<2>\w)\k<2>""", @"<Tree> <CompilationUnit> <Sequence> <CaptureGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <NumberToken value=""2"">2</NumberToken> <GreaterThanToken>&gt;</GreaterThanToken> <Sequence> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>w</TextToken> </CharacterClassEscape> </Sequence> <CloseParenToken>)</CloseParenToken> </CaptureGrouping> <KCaptureEscape> <BackslashToken>\</BackslashToken> <TextToken>k</TextToken> <LessThanToken>&lt;</LessThanToken> <NumberToken value=""2"">2</NumberToken> <GreaterThanToken>&gt;</GreaterThanToken> </KCaptureEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..23)"" Text=""(?&lt;2&gt;\w)\k&lt;2&gt;"" /> <Capture Name=""2"" Span=""[10..18)"" Text=""(?&lt;2&gt;\w)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest123() { Test(@"@""(?<1>a)(?<1>\1b)*""", @"<Tree> <CompilationUnit> <Sequence> <CaptureGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <NumberToken value=""1"">1</NumberToken> <GreaterThanToken>&gt;</GreaterThanToken> <Sequence> <Text> <TextToken>a</TextToken> </Text> </Sequence> <CloseParenToken>)</CloseParenToken> </CaptureGrouping> <ZeroOrMoreQuantifier> <CaptureGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <NumberToken value=""1"">1</NumberToken> <GreaterThanToken>&gt;</GreaterThanToken> <Sequence> <BackreferenceEscape> <BackslashToken>\</BackslashToken> <NumberToken value=""1"">1</NumberToken> </BackreferenceEscape> <Text> <TextToken>b</TextToken> </Text> </Sequence> <CloseParenToken>)</CloseParenToken> </CaptureGrouping> <AsteriskToken>*</AsteriskToken> </ZeroOrMoreQuantifier> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..27)"" Text=""(?&lt;1&gt;a)(?&lt;1&gt;\1b)*"" /> <Capture Name=""1"" Span=""[10..17)"" Text=""(?&lt;1&gt;a)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest124() { Test(@"@""\b(\p{Lu}{2})(\d{2})?(\p{Lu}{2})\b""", @"<Tree> <CompilationUnit> <Sequence> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>b</TextToken> </AnchorEscape> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <ExactNumericQuantifier> <CategoryEscape> <BackslashToken>\</BackslashToken> <TextToken>p</TextToken> <OpenBraceToken>{</OpenBraceToken> <EscapeCategoryToken>Lu</EscapeCategoryToken> <CloseBraceToken>}</CloseBraceToken> </CategoryEscape> <OpenBraceToken>{</OpenBraceToken> <NumberToken value=""2"">2</NumberToken> <CloseBraceToken>}</CloseBraceToken> </ExactNumericQuantifier> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <ZeroOrOneQuantifier> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <ExactNumericQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>d</TextToken> </CharacterClassEscape> <OpenBraceToken>{</OpenBraceToken> <NumberToken value=""2"">2</NumberToken> <CloseBraceToken>}</CloseBraceToken> </ExactNumericQuantifier> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <QuestionToken>?</QuestionToken> </ZeroOrOneQuantifier> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <ExactNumericQuantifier> <CategoryEscape> <BackslashToken>\</BackslashToken> <TextToken>p</TextToken> <OpenBraceToken>{</OpenBraceToken> <EscapeCategoryToken>Lu</EscapeCategoryToken> <CloseBraceToken>}</CloseBraceToken> </CategoryEscape> <OpenBraceToken>{</OpenBraceToken> <NumberToken value=""2"">2</NumberToken> <CloseBraceToken>}</CloseBraceToken> </ExactNumericQuantifier> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>b</TextToken> </AnchorEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..44)"" Text=""\b(\p{Lu}{2})(\d{2})?(\p{Lu}{2})\b"" /> <Capture Name=""1"" Span=""[12..23)"" Text=""(\p{Lu}{2})"" /> <Capture Name=""2"" Span=""[23..30)"" Text=""(\d{2})"" /> <Capture Name=""3"" Span=""[31..42)"" Text=""(\p{Lu}{2})"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest125() { Test(@"@""\bgr[ae]y\b""", @"<Tree> <CompilationUnit> <Sequence> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>b</TextToken> </AnchorEscape> <Text> <TextToken>gr</TextToken> </Text> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <Text> <TextToken>ae</TextToken> </Text> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> <Text> <TextToken>y</TextToken> </Text> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>b</TextToken> </AnchorEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..21)"" Text=""\bgr[ae]y\b"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest126() { Test(@"@""\b((?# case sensitive comparison)D\w+)\s(?ixn)((?#case insensitive comparison)d\w+)\b""", @"<Tree> <CompilationUnit> <Sequence> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>b</TextToken> </AnchorEscape> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <Text> <TextToken> <Trivia> <CommentTrivia>(?# case sensitive comparison)</CommentTrivia> </Trivia>D</TextToken> </Text> <OneOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>w</TextToken> </CharacterClassEscape> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>s</TextToken> </CharacterClassEscape> <SimpleOptionsGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <OptionsToken>ixn</OptionsToken> <CloseParenToken>)</CloseParenToken> </SimpleOptionsGrouping> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <Text> <TextToken> <Trivia> <CommentTrivia>(?#case insensitive comparison)</CommentTrivia> </Trivia>d</TextToken> </Text> <OneOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>w</TextToken> </CharacterClassEscape> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>b</TextToken> </AnchorEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..95)"" Text=""\b((?# case sensitive comparison)D\w+)\s(?ixn)((?#case insensitive comparison)d\w+)\b"" /> <Capture Name=""1"" Span=""[12..48)"" Text=""((?# case sensitive comparison)D\w+)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest127() { Test(@"@""\{\d+(,-*\d+)*(\:\w{1,4}?)*\}(?x) # Looks for a composite format item.""", @"<Tree> <CompilationUnit> <Sequence> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken>{</TextToken> </SimpleEscape> <OneOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>d</TextToken> </CharacterClassEscape> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> <ZeroOrMoreQuantifier> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <Text> <TextToken>,</TextToken> </Text> <ZeroOrMoreQuantifier> <Text> <TextToken>-</TextToken> </Text> <AsteriskToken>*</AsteriskToken> </ZeroOrMoreQuantifier> <OneOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>d</TextToken> </CharacterClassEscape> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <AsteriskToken>*</AsteriskToken> </ZeroOrMoreQuantifier> <ZeroOrMoreQuantifier> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken>:</TextToken> </SimpleEscape> <LazyQuantifier> <ClosedRangeNumericQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>w</TextToken> </CharacterClassEscape> <OpenBraceToken>{</OpenBraceToken> <NumberToken value=""1"">1</NumberToken> <CommaToken>,</CommaToken> <NumberToken value=""4"">4</NumberToken> <CloseBraceToken>}</CloseBraceToken> </ClosedRangeNumericQuantifier> <QuestionToken>?</QuestionToken> </LazyQuantifier> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <AsteriskToken>*</AsteriskToken> </ZeroOrMoreQuantifier> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken>}</TextToken> </SimpleEscape> <SimpleOptionsGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <OptionsToken>x</OptionsToken> <CloseParenToken>)</CloseParenToken> </SimpleOptionsGrouping> </Sequence> <EndOfFile> <Trivia> <WhitespaceTrivia> </WhitespaceTrivia> <CommentTrivia># Looks for a composite format item.</CommentTrivia> </Trivia> </EndOfFile> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..80)"" Text=""\{\d+(,-*\d+)*(\:\w{1,4}?)*\}(?x) # Looks for a composite format item."" /> <Capture Name=""1"" Span=""[15..23)"" Text=""(,-*\d+)"" /> <Capture Name=""2"" Span=""[24..36)"" Text=""(\:\w{1,4}?)"" /> </Captures> </Tree>", RegexOptions.None); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Text.RegularExpressions; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests.EmbeddedLanguages.RegularExpressions { // All these tests came from the example at: // https://docs.microsoft.com/en-us/dotnet/standard/base-types/regular-expression-language-quick-reference public partial class CSharpRegexParserTests { [Fact] public void ReferenceTest0() { Test(@"@""[aeiou]""", @"<Tree> <CompilationUnit> <Sequence> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <Text> <TextToken>aeiou</TextToken> </Text> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..17)"" Text=""[aeiou]"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest1() { Test(@"@""(?<duplicateWord>\w+)\s\k<duplicateWord>\W(?<nextWord>\w+)""", @"<Tree> <CompilationUnit> <Sequence> <CaptureGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <CaptureNameToken value=""duplicateWord"">duplicateWord</CaptureNameToken> <GreaterThanToken>&gt;</GreaterThanToken> <Sequence> <OneOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>w</TextToken> </CharacterClassEscape> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> </Sequence> <CloseParenToken>)</CloseParenToken> </CaptureGrouping> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>s</TextToken> </CharacterClassEscape> <KCaptureEscape> <BackslashToken>\</BackslashToken> <TextToken>k</TextToken> <LessThanToken>&lt;</LessThanToken> <CaptureNameToken value=""duplicateWord"">duplicateWord</CaptureNameToken> <GreaterThanToken>&gt;</GreaterThanToken> </KCaptureEscape> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>W</TextToken> </CharacterClassEscape> <CaptureGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <CaptureNameToken value=""nextWord"">nextWord</CaptureNameToken> <GreaterThanToken>&gt;</GreaterThanToken> <Sequence> <OneOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>w</TextToken> </CharacterClassEscape> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> </Sequence> <CloseParenToken>)</CloseParenToken> </CaptureGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..68)"" Text=""(?&lt;duplicateWord&gt;\w+)\s\k&lt;duplicateWord&gt;\W(?&lt;nextWord&gt;\w+)"" /> <Capture Name=""1"" Span=""[10..31)"" Text=""(?&lt;duplicateWord&gt;\w+)"" /> <Capture Name=""2"" Span=""[52..68)"" Text=""(?&lt;nextWord&gt;\w+)"" /> <Capture Name=""duplicateWord"" Span=""[10..31)"" Text=""(?&lt;duplicateWord&gt;\w+)"" /> <Capture Name=""nextWord"" Span=""[52..68)"" Text=""(?&lt;nextWord&gt;\w+)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest2() { Test(@"@""((?<One>abc)\d+)?(?<Two>xyz)(.*)""", @"<Tree> <CompilationUnit> <Sequence> <ZeroOrOneQuantifier> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <CaptureGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <CaptureNameToken value=""One"">One</CaptureNameToken> <GreaterThanToken>&gt;</GreaterThanToken> <Sequence> <Text> <TextToken>abc</TextToken> </Text> </Sequence> <CloseParenToken>)</CloseParenToken> </CaptureGrouping> <OneOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>d</TextToken> </CharacterClassEscape> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <QuestionToken>?</QuestionToken> </ZeroOrOneQuantifier> <CaptureGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <CaptureNameToken value=""Two"">Two</CaptureNameToken> <GreaterThanToken>&gt;</GreaterThanToken> <Sequence> <Text> <TextToken>xyz</TextToken> </Text> </Sequence> <CloseParenToken>)</CloseParenToken> </CaptureGrouping> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <ZeroOrMoreQuantifier> <Wildcard> <DotToken>.</DotToken> </Wildcard> <AsteriskToken>*</AsteriskToken> </ZeroOrMoreQuantifier> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..42)"" Text=""((?&lt;One&gt;abc)\d+)?(?&lt;Two&gt;xyz)(.*)"" /> <Capture Name=""1"" Span=""[10..26)"" Text=""((?&lt;One&gt;abc)\d+)"" /> <Capture Name=""2"" Span=""[38..42)"" Text=""(.*)"" /> <Capture Name=""3"" Span=""[11..22)"" Text=""(?&lt;One&gt;abc)"" /> <Capture Name=""4"" Span=""[27..38)"" Text=""(?&lt;Two&gt;xyz)"" /> <Capture Name=""One"" Span=""[11..22)"" Text=""(?&lt;One&gt;abc)"" /> <Capture Name=""Two"" Span=""[27..38)"" Text=""(?&lt;Two&gt;xyz)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest3() { Test(@"@""(\w+)\s(\1)""", @"<Tree> <CompilationUnit> <Sequence> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <OneOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>w</TextToken> </CharacterClassEscape> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>s</TextToken> </CharacterClassEscape> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <BackreferenceEscape> <BackslashToken>\</BackslashToken> <NumberToken value=""1"">1</NumberToken> </BackreferenceEscape> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..21)"" Text=""(\w+)\s(\1)"" /> <Capture Name=""1"" Span=""[10..15)"" Text=""(\w+)"" /> <Capture Name=""2"" Span=""[17..21)"" Text=""(\1)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest4() { Test(@"@""\Bqu\w+""", @"<Tree> <CompilationUnit> <Sequence> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>B</TextToken> </AnchorEscape> <Text> <TextToken>qu</TextToken> </Text> <OneOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>w</TextToken> </CharacterClassEscape> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..17)"" Text=""\Bqu\w+"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest5() { Test(@"@""\bare\w*\b""", @"<Tree> <CompilationUnit> <Sequence> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>b</TextToken> </AnchorEscape> <Text> <TextToken>are</TextToken> </Text> <ZeroOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>w</TextToken> </CharacterClassEscape> <AsteriskToken>*</AsteriskToken> </ZeroOrMoreQuantifier> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>b</TextToken> </AnchorEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..20)"" Text=""\bare\w*\b"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest6() { Test(@"@""\G(\w+\s?\w*),?""", @"<Tree> <CompilationUnit> <Sequence> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>G</TextToken> </AnchorEscape> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <OneOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>w</TextToken> </CharacterClassEscape> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> <ZeroOrOneQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>s</TextToken> </CharacterClassEscape> <QuestionToken>?</QuestionToken> </ZeroOrOneQuantifier> <ZeroOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>w</TextToken> </CharacterClassEscape> <AsteriskToken>*</AsteriskToken> </ZeroOrMoreQuantifier> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <ZeroOrOneQuantifier> <Text> <TextToken>,</TextToken> </Text> <QuestionToken>?</QuestionToken> </ZeroOrOneQuantifier> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..25)"" Text=""\G(\w+\s?\w*),?"" /> <Capture Name=""1"" Span=""[12..23)"" Text=""(\w+\s?\w*)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest7() { Test(@"@""\D+(?<digit>\d+)\D+(?<digit>\d+)?""", @"<Tree> <CompilationUnit> <Sequence> <OneOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>D</TextToken> </CharacterClassEscape> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> <CaptureGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <CaptureNameToken value=""digit"">digit</CaptureNameToken> <GreaterThanToken>&gt;</GreaterThanToken> <Sequence> <OneOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>d</TextToken> </CharacterClassEscape> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> </Sequence> <CloseParenToken>)</CloseParenToken> </CaptureGrouping> <OneOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>D</TextToken> </CharacterClassEscape> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> <ZeroOrOneQuantifier> <CaptureGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <CaptureNameToken value=""digit"">digit</CaptureNameToken> <GreaterThanToken>&gt;</GreaterThanToken> <Sequence> <OneOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>d</TextToken> </CharacterClassEscape> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> </Sequence> <CloseParenToken>)</CloseParenToken> </CaptureGrouping> <QuestionToken>?</QuestionToken> </ZeroOrOneQuantifier> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..43)"" Text=""\D+(?&lt;digit&gt;\d+)\D+(?&lt;digit&gt;\d+)?"" /> <Capture Name=""1"" Span=""[13..26)"" Text=""(?&lt;digit&gt;\d+)"" /> <Capture Name=""digit"" Span=""[13..26)"" Text=""(?&lt;digit&gt;\d+)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest8() { Test(@"@""(\s\d{4}(-(\d{4}&#124;present))?,?)+""", @"<Tree> <CompilationUnit> <Sequence> <OneOrMoreQuantifier> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>s</TextToken> </CharacterClassEscape> <ExactNumericQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>d</TextToken> </CharacterClassEscape> <OpenBraceToken>{</OpenBraceToken> <NumberToken value=""4"">4</NumberToken> <CloseBraceToken>}</CloseBraceToken> </ExactNumericQuantifier> <ZeroOrOneQuantifier> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <Text> <TextToken>-</TextToken> </Text> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <ExactNumericQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>d</TextToken> </CharacterClassEscape> <OpenBraceToken>{</OpenBraceToken> <NumberToken value=""4"">4</NumberToken> <CloseBraceToken>}</CloseBraceToken> </ExactNumericQuantifier> <Text> <TextToken>&amp;#124;present</TextToken> </Text> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <QuestionToken>?</QuestionToken> </ZeroOrOneQuantifier> <ZeroOrOneQuantifier> <Text> <TextToken>,</TextToken> </Text> <QuestionToken>?</QuestionToken> </ZeroOrOneQuantifier> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..46)"" Text=""(\s\d{4}(-(\d{4}&amp;#124;present))?,?)+"" /> <Capture Name=""1"" Span=""[10..45)"" Text=""(\s\d{4}(-(\d{4}&amp;#124;present))?,?)"" /> <Capture Name=""2"" Span=""[18..41)"" Text=""(-(\d{4}&amp;#124;present))"" /> <Capture Name=""3"" Span=""[20..40)"" Text=""(\d{4}&amp;#124;present)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest9() { Test(@"@""^((\w+(\s?)){2,}),\s(\w+\s\w+),(\s\d{4}(-(\d{4}|present))?,?)+""", @"<Tree> <CompilationUnit> <Sequence> <StartAnchor> <CaretToken>^</CaretToken> </StartAnchor> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <OpenRangeNumericQuantifier> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <OneOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>w</TextToken> </CharacterClassEscape> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <ZeroOrOneQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>s</TextToken> </CharacterClassEscape> <QuestionToken>?</QuestionToken> </ZeroOrOneQuantifier> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <OpenBraceToken>{</OpenBraceToken> <NumberToken value=""2"">2</NumberToken> <CommaToken>,</CommaToken> <CloseBraceToken>}</CloseBraceToken> </OpenRangeNumericQuantifier> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <Text> <TextToken>,</TextToken> </Text> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>s</TextToken> </CharacterClassEscape> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <OneOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>w</TextToken> </CharacterClassEscape> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>s</TextToken> </CharacterClassEscape> <OneOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>w</TextToken> </CharacterClassEscape> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <Text> <TextToken>,</TextToken> </Text> <OneOrMoreQuantifier> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>s</TextToken> </CharacterClassEscape> <ExactNumericQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>d</TextToken> </CharacterClassEscape> <OpenBraceToken>{</OpenBraceToken> <NumberToken value=""4"">4</NumberToken> <CloseBraceToken>}</CloseBraceToken> </ExactNumericQuantifier> <ZeroOrOneQuantifier> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <Text> <TextToken>-</TextToken> </Text> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Alternation> <Sequence> <ExactNumericQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>d</TextToken> </CharacterClassEscape> <OpenBraceToken>{</OpenBraceToken> <NumberToken value=""4"">4</NumberToken> <CloseBraceToken>}</CloseBraceToken> </ExactNumericQuantifier> </Sequence> <BarToken>|</BarToken> <Sequence> <Text> <TextToken>present</TextToken> </Text> </Sequence> </Alternation> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <QuestionToken>?</QuestionToken> </ZeroOrOneQuantifier> <ZeroOrOneQuantifier> <Text> <TextToken>,</TextToken> </Text> <QuestionToken>?</QuestionToken> </ZeroOrOneQuantifier> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..72)"" Text=""^((\w+(\s?)){2,}),\s(\w+\s\w+),(\s\d{4}(-(\d{4}|present))?,?)+"" /> <Capture Name=""1"" Span=""[11..27)"" Text=""((\w+(\s?)){2,})"" /> <Capture Name=""2"" Span=""[12..22)"" Text=""(\w+(\s?))"" /> <Capture Name=""3"" Span=""[16..21)"" Text=""(\s?)"" /> <Capture Name=""4"" Span=""[30..40)"" Text=""(\w+\s\w+)"" /> <Capture Name=""5"" Span=""[41..71)"" Text=""(\s\d{4}(-(\d{4}|present))?,?)"" /> <Capture Name=""6"" Span=""[49..67)"" Text=""(-(\d{4}|present))"" /> <Capture Name=""7"" Span=""[51..66)"" Text=""(\d{4}|present)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest10() { Test(@"@""^[0-9-[2468]]+$""", @"<Tree> <CompilationUnit> <Sequence> <StartAnchor> <CaretToken>^</CaretToken> </StartAnchor> <OneOrMoreQuantifier> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <CharacterClassRange> <Text> <TextToken>0</TextToken> </Text> <MinusToken>-</MinusToken> <Text> <TextToken>9</TextToken> </Text> </CharacterClassRange> <CharacterClassSubtraction> <MinusToken>-</MinusToken> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <Text> <TextToken>2468</TextToken> </Text> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> </CharacterClassSubtraction> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> <EndAnchor> <DollarToken>$</DollarToken> </EndAnchor> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..25)"" Text=""^[0-9-[2468]]+$"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest11() { Test(@"@""[a-z-[0-9]]""", @"<Tree> <CompilationUnit> <Sequence> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <CharacterClassRange> <Text> <TextToken>a</TextToken> </Text> <MinusToken>-</MinusToken> <Text> <TextToken>z</TextToken> </Text> </CharacterClassRange> <CharacterClassSubtraction> <MinusToken>-</MinusToken> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <CharacterClassRange> <Text> <TextToken>0</TextToken> </Text> <MinusToken>-</MinusToken> <Text> <TextToken>9</TextToken> </Text> </CharacterClassRange> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> </CharacterClassSubtraction> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..21)"" Text=""[a-z-[0-9]]"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest12() { Test(@"@""[\p{IsBasicLatin}-[\x00-\x7F]]""", @"<Tree> <CompilationUnit> <Sequence> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <CategoryEscape> <BackslashToken>\</BackslashToken> <TextToken>p</TextToken> <OpenBraceToken>{</OpenBraceToken> <EscapeCategoryToken>IsBasicLatin</EscapeCategoryToken> <CloseBraceToken>}</CloseBraceToken> </CategoryEscape> <CharacterClassSubtraction> <MinusToken>-</MinusToken> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <CharacterClassRange> <HexEscape> <BackslashToken>\</BackslashToken> <TextToken>x</TextToken> <TextToken>00</TextToken> </HexEscape> <MinusToken>-</MinusToken> <HexEscape> <BackslashToken>\</BackslashToken> <TextToken>x</TextToken> <TextToken>7F</TextToken> </HexEscape> </CharacterClassRange> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> </CharacterClassSubtraction> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..40)"" Text=""[\p{IsBasicLatin}-[\x00-\x7F]]"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest13() { Test(@"@""[\u0000-\uFFFF-[\s\p{P}\p{IsGreek}\x85]]""", @"<Tree> <CompilationUnit> <Sequence> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <CharacterClassRange> <UnicodeEscape> <BackslashToken>\</BackslashToken> <TextToken>u</TextToken> <TextToken>0000</TextToken> </UnicodeEscape> <MinusToken>-</MinusToken> <UnicodeEscape> <BackslashToken>\</BackslashToken> <TextToken>u</TextToken> <TextToken>FFFF</TextToken> </UnicodeEscape> </CharacterClassRange> <CharacterClassSubtraction> <MinusToken>-</MinusToken> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>s</TextToken> </CharacterClassEscape> <CategoryEscape> <BackslashToken>\</BackslashToken> <TextToken>p</TextToken> <OpenBraceToken>{</OpenBraceToken> <EscapeCategoryToken>P</EscapeCategoryToken> <CloseBraceToken>}</CloseBraceToken> </CategoryEscape> <CategoryEscape> <BackslashToken>\</BackslashToken> <TextToken>p</TextToken> <OpenBraceToken>{</OpenBraceToken> <EscapeCategoryToken>IsGreek</EscapeCategoryToken> <CloseBraceToken>}</CloseBraceToken> </CategoryEscape> <HexEscape> <BackslashToken>\</BackslashToken> <TextToken>x</TextToken> <TextToken>85</TextToken> </HexEscape> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> </CharacterClassSubtraction> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..50)"" Text=""[\u0000-\uFFFF-[\s\p{P}\p{IsGreek}\x85]]"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest14() { Test(@"@""[a-z-[d-w-[m-o]]]""", @"<Tree> <CompilationUnit> <Sequence> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <CharacterClassRange> <Text> <TextToken>a</TextToken> </Text> <MinusToken>-</MinusToken> <Text> <TextToken>z</TextToken> </Text> </CharacterClassRange> <CharacterClassSubtraction> <MinusToken>-</MinusToken> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <CharacterClassRange> <Text> <TextToken>d</TextToken> </Text> <MinusToken>-</MinusToken> <Text> <TextToken>w</TextToken> </Text> </CharacterClassRange> <CharacterClassSubtraction> <MinusToken>-</MinusToken> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <CharacterClassRange> <Text> <TextToken>m</TextToken> </Text> <MinusToken>-</MinusToken> <Text> <TextToken>o</TextToken> </Text> </CharacterClassRange> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> </CharacterClassSubtraction> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> </CharacterClassSubtraction> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..27)"" Text=""[a-z-[d-w-[m-o]]]"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest15() { Test(@"@""((\w+(\s?)){2,}""", $@"<Tree> <CompilationUnit> <Sequence> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <OpenRangeNumericQuantifier> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <OneOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>w</TextToken> </CharacterClassEscape> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <ZeroOrOneQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>s</TextToken> </CharacterClassEscape> <QuestionToken>?</QuestionToken> </ZeroOrOneQuantifier> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <OpenBraceToken>{{</OpenBraceToken> <NumberToken value=""2"">2</NumberToken> <CommaToken>,</CommaToken> <CloseBraceToken>}}</CloseBraceToken> </OpenRangeNumericQuantifier> </Sequence> <CloseParenToken /> </SimpleGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Not_enough_close_parens}"" Span=""[25..25)"" Text="""" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..25)"" Text=""((\w+(\s?)){{2,}}"" /> <Capture Name=""1"" Span=""[10..25)"" Text=""((\w+(\s?)){{2,}}"" /> <Capture Name=""2"" Span=""[11..21)"" Text=""(\w+(\s?))"" /> <Capture Name=""3"" Span=""[15..20)"" Text=""(\s?)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest16() { Test(@"@""[a-z-[djp]]""", @"<Tree> <CompilationUnit> <Sequence> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <CharacterClassRange> <Text> <TextToken>a</TextToken> </Text> <MinusToken>-</MinusToken> <Text> <TextToken>z</TextToken> </Text> </CharacterClassRange> <CharacterClassSubtraction> <MinusToken>-</MinusToken> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <Text> <TextToken>djp</TextToken> </Text> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> </CharacterClassSubtraction> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..21)"" Text=""[a-z-[djp]]"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest17() { Test(@"@""^[^<>]*(((?'Open'<)[^<>]*)+((?'Close-Open'>)[^<>]*)+)*(?(Open)(?!))$""", @"<Tree> <CompilationUnit> <Sequence> <StartAnchor> <CaretToken>^</CaretToken> </StartAnchor> <ZeroOrMoreQuantifier> <NegatedCharacterClass> <OpenBracketToken>[</OpenBracketToken> <CaretToken>^</CaretToken> <Sequence> <Text> <TextToken>&lt;&gt;</TextToken> </Text> </Sequence> <CloseBracketToken>]</CloseBracketToken> </NegatedCharacterClass> <AsteriskToken>*</AsteriskToken> </ZeroOrMoreQuantifier> <ZeroOrMoreQuantifier> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <OneOrMoreQuantifier> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <CaptureGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <SingleQuoteToken>'</SingleQuoteToken> <CaptureNameToken value=""Open"">Open</CaptureNameToken> <SingleQuoteToken>'</SingleQuoteToken> <Sequence> <Text> <TextToken>&lt;</TextToken> </Text> </Sequence> <CloseParenToken>)</CloseParenToken> </CaptureGrouping> <ZeroOrMoreQuantifier> <NegatedCharacterClass> <OpenBracketToken>[</OpenBracketToken> <CaretToken>^</CaretToken> <Sequence> <Text> <TextToken>&lt;&gt;</TextToken> </Text> </Sequence> <CloseBracketToken>]</CloseBracketToken> </NegatedCharacterClass> <AsteriskToken>*</AsteriskToken> </ZeroOrMoreQuantifier> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> <OneOrMoreQuantifier> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <BalancingGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <SingleQuoteToken>'</SingleQuoteToken> <CaptureNameToken value=""Close"">Close</CaptureNameToken> <MinusToken>-</MinusToken> <CaptureNameToken value=""Open"">Open</CaptureNameToken> <SingleQuoteToken>'</SingleQuoteToken> <Sequence> <Text> <TextToken>&gt;</TextToken> </Text> </Sequence> <CloseParenToken>)</CloseParenToken> </BalancingGrouping> <ZeroOrMoreQuantifier> <NegatedCharacterClass> <OpenBracketToken>[</OpenBracketToken> <CaretToken>^</CaretToken> <Sequence> <Text> <TextToken>&lt;&gt;</TextToken> </Text> </Sequence> <CloseBracketToken>]</CloseBracketToken> </NegatedCharacterClass> <AsteriskToken>*</AsteriskToken> </ZeroOrMoreQuantifier> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <AsteriskToken>*</AsteriskToken> </ZeroOrMoreQuantifier> <ConditionalCaptureGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <OpenParenToken>(</OpenParenToken> <CaptureNameToken value=""Open"">Open</CaptureNameToken> <CloseParenToken>)</CloseParenToken> <Sequence> <NegativeLookaheadGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <ExclamationToken>!</ExclamationToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </NegativeLookaheadGrouping> </Sequence> <CloseParenToken>)</CloseParenToken> </ConditionalCaptureGrouping> <EndAnchor> <DollarToken>$</DollarToken> </EndAnchor> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..78)"" Text=""^[^&lt;&gt;]*(((?'Open'&lt;)[^&lt;&gt;]*)+((?'Close-Open'&gt;)[^&lt;&gt;]*)+)*(?(Open)(?!))$"" /> <Capture Name=""1"" Span=""[17..63)"" Text=""(((?'Open'&lt;)[^&lt;&gt;]*)+((?'Close-Open'&gt;)[^&lt;&gt;]*)+)"" /> <Capture Name=""2"" Span=""[18..36)"" Text=""((?'Open'&lt;)[^&lt;&gt;]*)"" /> <Capture Name=""3"" Span=""[37..61)"" Text=""((?'Close-Open'&gt;)[^&lt;&gt;]*)"" /> <Capture Name=""4"" Span=""[19..29)"" Text=""(?'Open'&lt;)"" /> <Capture Name=""5"" Span=""[38..54)"" Text=""(?'Close-Open'&gt;)"" /> <Capture Name=""Close"" Span=""[38..54)"" Text=""(?'Close-Open'&gt;)"" /> <Capture Name=""Open"" Span=""[19..29)"" Text=""(?'Open'&lt;)"" /> </Captures> </Tree>", RegexOptions.None, allowIndexOutOfRange: true); } [Fact] public void ReferenceTest18() { Test(@"@""((?'Close-Open'>)[^<>]*)+""", $@"<Tree> <CompilationUnit> <Sequence> <OneOrMoreQuantifier> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <BalancingGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <SingleQuoteToken>'</SingleQuoteToken> <CaptureNameToken value=""Close"">Close</CaptureNameToken> <MinusToken>-</MinusToken> <CaptureNameToken value=""Open"">Open</CaptureNameToken> <SingleQuoteToken>'</SingleQuoteToken> <Sequence> <Text> <TextToken>&gt;</TextToken> </Text> </Sequence> <CloseParenToken>)</CloseParenToken> </BalancingGrouping> <ZeroOrMoreQuantifier> <NegatedCharacterClass> <OpenBracketToken>[</OpenBracketToken> <CaretToken>^</CaretToken> <Sequence> <Text> <TextToken>&lt;&gt;</TextToken> </Text> </Sequence> <CloseBracketToken>]</CloseBracketToken> </NegatedCharacterClass> <AsteriskToken>*</AsteriskToken> </ZeroOrMoreQuantifier> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{string.Format(FeaturesResources.Reference_to_undefined_group_name_0, "Open")}"" Span=""[20..24)"" Text=""Open"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..35)"" Text=""((?'Close-Open'&gt;)[^&lt;&gt;]*)+"" /> <Capture Name=""1"" Span=""[10..34)"" Text=""((?'Close-Open'&gt;)[^&lt;&gt;]*)"" /> <Capture Name=""2"" Span=""[11..27)"" Text=""(?'Close-Open'&gt;)"" /> <Capture Name=""Close"" Span=""[11..27)"" Text=""(?'Close-Open'&gt;)"" /> </Captures> </Tree>", RegexOptions.None, allowIndexOutOfRange: true); } [Fact] public void ReferenceTest19() { Test(@"@""(\w)\1+.\b""", @"<Tree> <CompilationUnit> <Sequence> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>w</TextToken> </CharacterClassEscape> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <OneOrMoreQuantifier> <BackreferenceEscape> <BackslashToken>\</BackslashToken> <NumberToken value=""1"">1</NumberToken> </BackreferenceEscape> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> <Wildcard> <DotToken>.</DotToken> </Wildcard> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>b</TextToken> </AnchorEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..20)"" Text=""(\w)\1+.\b"" /> <Capture Name=""1"" Span=""[10..14)"" Text=""(\w)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest20() { Test(@"@""\d{4}\b""", @"<Tree> <CompilationUnit> <Sequence> <ExactNumericQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>d</TextToken> </CharacterClassEscape> <OpenBraceToken>{</OpenBraceToken> <NumberToken value=""4"">4</NumberToken> <CloseBraceToken>}</CloseBraceToken> </ExactNumericQuantifier> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>b</TextToken> </AnchorEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..17)"" Text=""\d{4}\b"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest21() { Test(@"@""\d{1,2},""", @"<Tree> <CompilationUnit> <Sequence> <ClosedRangeNumericQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>d</TextToken> </CharacterClassEscape> <OpenBraceToken>{</OpenBraceToken> <NumberToken value=""1"">1</NumberToken> <CommaToken>,</CommaToken> <NumberToken value=""2"">2</NumberToken> <CloseBraceToken>}</CloseBraceToken> </ClosedRangeNumericQuantifier> <Text> <TextToken>,</TextToken> </Text> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..18)"" Text=""\d{1,2},"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest22() { Test(@"@""(?<!(Saturday|Sunday) )\b\w+ \d{1,2}, \d{4}\b""", @"<Tree> <CompilationUnit> <Sequence> <NegativeLookbehindGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <ExclamationToken>!</ExclamationToken> <Sequence> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Alternation> <Sequence> <Text> <TextToken>Saturday</TextToken> </Text> </Sequence> <BarToken>|</BarToken> <Sequence> <Text> <TextToken>Sunday</TextToken> </Text> </Sequence> </Alternation> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <Text> <TextToken> </TextToken> </Text> </Sequence> <CloseParenToken>)</CloseParenToken> </NegativeLookbehindGrouping> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>b</TextToken> </AnchorEscape> <OneOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>w</TextToken> </CharacterClassEscape> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> <Text> <TextToken> </TextToken> </Text> <ClosedRangeNumericQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>d</TextToken> </CharacterClassEscape> <OpenBraceToken>{</OpenBraceToken> <NumberToken value=""1"">1</NumberToken> <CommaToken>,</CommaToken> <NumberToken value=""2"">2</NumberToken> <CloseBraceToken>}</CloseBraceToken> </ClosedRangeNumericQuantifier> <Text> <TextToken>, </TextToken> </Text> <ExactNumericQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>d</TextToken> </CharacterClassEscape> <OpenBraceToken>{</OpenBraceToken> <NumberToken value=""4"">4</NumberToken> <CloseBraceToken>}</CloseBraceToken> </ExactNumericQuantifier> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>b</TextToken> </AnchorEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..55)"" Text=""(?&lt;!(Saturday|Sunday) )\b\w+ \d{1,2}, \d{4}\b"" /> <Capture Name=""1"" Span=""[14..31)"" Text=""(Saturday|Sunday)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest23() { Test(@"@""(?<=\b20)\d{2}\b""", @"<Tree> <CompilationUnit> <Sequence> <PositiveLookbehindGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <EqualsToken>=</EqualsToken> <Sequence> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>b</TextToken> </AnchorEscape> <Text> <TextToken>20</TextToken> </Text> </Sequence> <CloseParenToken>)</CloseParenToken> </PositiveLookbehindGrouping> <ExactNumericQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>d</TextToken> </CharacterClassEscape> <OpenBraceToken>{</OpenBraceToken> <NumberToken value=""2"">2</NumberToken> <CloseBraceToken>}</CloseBraceToken> </ExactNumericQuantifier> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>b</TextToken> </AnchorEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..26)"" Text=""(?&lt;=\b20)\d{2}\b"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest24() { Test(@"@""\b\w+\b(?!\p{P})""", @"<Tree> <CompilationUnit> <Sequence> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>b</TextToken> </AnchorEscape> <OneOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>w</TextToken> </CharacterClassEscape> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>b</TextToken> </AnchorEscape> <NegativeLookaheadGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <ExclamationToken>!</ExclamationToken> <Sequence> <CategoryEscape> <BackslashToken>\</BackslashToken> <TextToken>p</TextToken> <OpenBraceToken>{</OpenBraceToken> <EscapeCategoryToken>P</EscapeCategoryToken> <CloseBraceToken>}</CloseBraceToken> </CategoryEscape> </Sequence> <CloseParenToken>)</CloseParenToken> </NegativeLookaheadGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..26)"" Text=""\b\w+\b(?!\p{P})"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest25() { Test(@"@""(((?'Open'<)[^<>]*)+((?'Close-Open'>)[^<>]*)+)*""", @"<Tree> <CompilationUnit> <Sequence> <ZeroOrMoreQuantifier> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <OneOrMoreQuantifier> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <CaptureGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <SingleQuoteToken>'</SingleQuoteToken> <CaptureNameToken value=""Open"">Open</CaptureNameToken> <SingleQuoteToken>'</SingleQuoteToken> <Sequence> <Text> <TextToken>&lt;</TextToken> </Text> </Sequence> <CloseParenToken>)</CloseParenToken> </CaptureGrouping> <ZeroOrMoreQuantifier> <NegatedCharacterClass> <OpenBracketToken>[</OpenBracketToken> <CaretToken>^</CaretToken> <Sequence> <Text> <TextToken>&lt;&gt;</TextToken> </Text> </Sequence> <CloseBracketToken>]</CloseBracketToken> </NegatedCharacterClass> <AsteriskToken>*</AsteriskToken> </ZeroOrMoreQuantifier> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> <OneOrMoreQuantifier> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <BalancingGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <SingleQuoteToken>'</SingleQuoteToken> <CaptureNameToken value=""Close"">Close</CaptureNameToken> <MinusToken>-</MinusToken> <CaptureNameToken value=""Open"">Open</CaptureNameToken> <SingleQuoteToken>'</SingleQuoteToken> <Sequence> <Text> <TextToken>&gt;</TextToken> </Text> </Sequence> <CloseParenToken>)</CloseParenToken> </BalancingGrouping> <ZeroOrMoreQuantifier> <NegatedCharacterClass> <OpenBracketToken>[</OpenBracketToken> <CaretToken>^</CaretToken> <Sequence> <Text> <TextToken>&lt;&gt;</TextToken> </Text> </Sequence> <CloseBracketToken>]</CloseBracketToken> </NegatedCharacterClass> <AsteriskToken>*</AsteriskToken> </ZeroOrMoreQuantifier> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <AsteriskToken>*</AsteriskToken> </ZeroOrMoreQuantifier> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..57)"" Text=""(((?'Open'&lt;)[^&lt;&gt;]*)+((?'Close-Open'&gt;)[^&lt;&gt;]*)+)*"" /> <Capture Name=""1"" Span=""[10..56)"" Text=""(((?'Open'&lt;)[^&lt;&gt;]*)+((?'Close-Open'&gt;)[^&lt;&gt;]*)+)"" /> <Capture Name=""2"" Span=""[11..29)"" Text=""((?'Open'&lt;)[^&lt;&gt;]*)"" /> <Capture Name=""3"" Span=""[30..54)"" Text=""((?'Close-Open'&gt;)[^&lt;&gt;]*)"" /> <Capture Name=""4"" Span=""[12..22)"" Text=""(?'Open'&lt;)"" /> <Capture Name=""5"" Span=""[31..47)"" Text=""(?'Close-Open'&gt;)"" /> <Capture Name=""Close"" Span=""[31..47)"" Text=""(?'Close-Open'&gt;)"" /> <Capture Name=""Open"" Span=""[12..22)"" Text=""(?'Open'&lt;)"" /> </Captures> </Tree>", RegexOptions.None, allowIndexOutOfRange: true); } [Fact] public void ReferenceTest26() { Test(@"@""\b(?!un)\w+\b""", @"<Tree> <CompilationUnit> <Sequence> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>b</TextToken> </AnchorEscape> <NegativeLookaheadGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <ExclamationToken>!</ExclamationToken> <Sequence> <Text> <TextToken>un</TextToken> </Text> </Sequence> <CloseParenToken>)</CloseParenToken> </NegativeLookaheadGrouping> <OneOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>w</TextToken> </CharacterClassEscape> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>b</TextToken> </AnchorEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..23)"" Text=""\b(?!un)\w+\b"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest27() { Test(@"@""\b(?ix: d \w+)\s""", @"<Tree> <CompilationUnit> <Sequence> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>b</TextToken> </AnchorEscape> <NestedOptionsGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <OptionsToken>ix</OptionsToken> <ColonToken>:</ColonToken> <Sequence> <Text> <TextToken> <Trivia> <WhitespaceTrivia> </WhitespaceTrivia> </Trivia>d</TextToken> </Text> <OneOrMoreQuantifier> <CharacterClassEscape> <BackslashToken> <Trivia> <WhitespaceTrivia> </WhitespaceTrivia> </Trivia>\</BackslashToken> <TextToken>w</TextToken> </CharacterClassEscape> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> </Sequence> <CloseParenToken>)</CloseParenToken> </NestedOptionsGrouping> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>s</TextToken> </CharacterClassEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..26)"" Text=""\b(?ix: d \w+)\s"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest28() { Test(@"@""(?:\w+)""", @"<Tree> <CompilationUnit> <Sequence> <NonCapturingGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <ColonToken>:</ColonToken> <Sequence> <OneOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>w</TextToken> </CharacterClassEscape> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> </Sequence> <CloseParenToken>)</CloseParenToken> </NonCapturingGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..17)"" Text=""(?:\w+)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest29() { Test(@"@""(?:\b(?:\w+)\W*)+""", @"<Tree> <CompilationUnit> <Sequence> <OneOrMoreQuantifier> <NonCapturingGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <ColonToken>:</ColonToken> <Sequence> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>b</TextToken> </AnchorEscape> <NonCapturingGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <ColonToken>:</ColonToken> <Sequence> <OneOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>w</TextToken> </CharacterClassEscape> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> </Sequence> <CloseParenToken>)</CloseParenToken> </NonCapturingGrouping> <ZeroOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>W</TextToken> </CharacterClassEscape> <AsteriskToken>*</AsteriskToken> </ZeroOrMoreQuantifier> </Sequence> <CloseParenToken>)</CloseParenToken> </NonCapturingGrouping> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..27)"" Text=""(?:\b(?:\w+)\W*)+"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest30() { Test(@"@""(?:\b(?:\w+)\W*)+\.""", @"<Tree> <CompilationUnit> <Sequence> <OneOrMoreQuantifier> <NonCapturingGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <ColonToken>:</ColonToken> <Sequence> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>b</TextToken> </AnchorEscape> <NonCapturingGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <ColonToken>:</ColonToken> <Sequence> <OneOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>w</TextToken> </CharacterClassEscape> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> </Sequence> <CloseParenToken>)</CloseParenToken> </NonCapturingGrouping> <ZeroOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>W</TextToken> </CharacterClassEscape> <AsteriskToken>*</AsteriskToken> </ZeroOrMoreQuantifier> </Sequence> <CloseParenToken>)</CloseParenToken> </NonCapturingGrouping> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken>.</TextToken> </SimpleEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..29)"" Text=""(?:\b(?:\w+)\W*)+\."" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest31() { Test(@"@""(?'Close-Open'>)""", $@"<Tree> <CompilationUnit> <Sequence> <BalancingGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <SingleQuoteToken>'</SingleQuoteToken> <CaptureNameToken value=""Close"">Close</CaptureNameToken> <MinusToken>-</MinusToken> <CaptureNameToken value=""Open"">Open</CaptureNameToken> <SingleQuoteToken>'</SingleQuoteToken> <Sequence> <Text> <TextToken>&gt;</TextToken> </Text> </Sequence> <CloseParenToken>)</CloseParenToken> </BalancingGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{string.Format(FeaturesResources.Reference_to_undefined_group_name_0, "Open")}"" Span=""[19..23)"" Text=""Open"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..26)"" Text=""(?'Close-Open'&gt;)"" /> <Capture Name=""1"" Span=""[10..26)"" Text=""(?'Close-Open'&gt;)"" /> <Capture Name=""Close"" Span=""[10..26)"" Text=""(?'Close-Open'&gt;)"" /> </Captures> </Tree>", RegexOptions.None, allowIndexOutOfRange: true); } [Fact] public void ReferenceTest32() { Test(@"@""[^<>]*""", @"<Tree> <CompilationUnit> <Sequence> <ZeroOrMoreQuantifier> <NegatedCharacterClass> <OpenBracketToken>[</OpenBracketToken> <CaretToken>^</CaretToken> <Sequence> <Text> <TextToken>&lt;&gt;</TextToken> </Text> </Sequence> <CloseBracketToken>]</CloseBracketToken> </NegatedCharacterClass> <AsteriskToken>*</AsteriskToken> </ZeroOrMoreQuantifier> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..16)"" Text=""[^&lt;&gt;]*"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest33() { Test(@"@""\b\w+(?=\sis\b)""", @"<Tree> <CompilationUnit> <Sequence> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>b</TextToken> </AnchorEscape> <OneOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>w</TextToken> </CharacterClassEscape> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> <PositiveLookaheadGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <EqualsToken>=</EqualsToken> <Sequence> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>s</TextToken> </CharacterClassEscape> <Text> <TextToken>is</TextToken> </Text> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>b</TextToken> </AnchorEscape> </Sequence> <CloseParenToken>)</CloseParenToken> </PositiveLookaheadGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..25)"" Text=""\b\w+(?=\sis\b)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest34() { Test(@"@""[a-z-[m]]""", @"<Tree> <CompilationUnit> <Sequence> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <CharacterClassRange> <Text> <TextToken>a</TextToken> </Text> <MinusToken>-</MinusToken> <Text> <TextToken>z</TextToken> </Text> </CharacterClassRange> <CharacterClassSubtraction> <MinusToken>-</MinusToken> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <Text> <TextToken>m</TextToken> </Text> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> </CharacterClassSubtraction> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..19)"" Text=""[a-z-[m]]"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest35() { Test(@"@""^\D\d{1,5}\D*$""", @"<Tree> <CompilationUnit> <Sequence> <StartAnchor> <CaretToken>^</CaretToken> </StartAnchor> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>D</TextToken> </CharacterClassEscape> <ClosedRangeNumericQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>d</TextToken> </CharacterClassEscape> <OpenBraceToken>{</OpenBraceToken> <NumberToken value=""1"">1</NumberToken> <CommaToken>,</CommaToken> <NumberToken value=""5"">5</NumberToken> <CloseBraceToken>}</CloseBraceToken> </ClosedRangeNumericQuantifier> <ZeroOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>D</TextToken> </CharacterClassEscape> <AsteriskToken>*</AsteriskToken> </ZeroOrMoreQuantifier> <EndAnchor> <DollarToken>$</DollarToken> </EndAnchor> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..24)"" Text=""^\D\d{1,5}\D*$"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest36() { Test(@"@""[^0-9]""", @"<Tree> <CompilationUnit> <Sequence> <NegatedCharacterClass> <OpenBracketToken>[</OpenBracketToken> <CaretToken>^</CaretToken> <Sequence> <CharacterClassRange> <Text> <TextToken>0</TextToken> </Text> <MinusToken>-</MinusToken> <Text> <TextToken>9</TextToken> </Text> </CharacterClassRange> </Sequence> <CloseBracketToken>]</CloseBracketToken> </NegatedCharacterClass> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..16)"" Text=""[^0-9]"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest37() { Test(@"@""(\p{IsGreek}+(\s)?)+""", @"<Tree> <CompilationUnit> <Sequence> <OneOrMoreQuantifier> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <OneOrMoreQuantifier> <CategoryEscape> <BackslashToken>\</BackslashToken> <TextToken>p</TextToken> <OpenBraceToken>{</OpenBraceToken> <EscapeCategoryToken>IsGreek</EscapeCategoryToken> <CloseBraceToken>}</CloseBraceToken> </CategoryEscape> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> <ZeroOrOneQuantifier> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>s</TextToken> </CharacterClassEscape> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <QuestionToken>?</QuestionToken> </ZeroOrOneQuantifier> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..30)"" Text=""(\p{IsGreek}+(\s)?)+"" /> <Capture Name=""1"" Span=""[10..29)"" Text=""(\p{IsGreek}+(\s)?)"" /> <Capture Name=""2"" Span=""[23..27)"" Text=""(\s)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest38() { Test(@"@""\b(\p{IsGreek}+(\s)?)+\p{Pd}\s(\p{IsBasicLatin}+(\s)?)+""", @"<Tree> <CompilationUnit> <Sequence> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>b</TextToken> </AnchorEscape> <OneOrMoreQuantifier> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <OneOrMoreQuantifier> <CategoryEscape> <BackslashToken>\</BackslashToken> <TextToken>p</TextToken> <OpenBraceToken>{</OpenBraceToken> <EscapeCategoryToken>IsGreek</EscapeCategoryToken> <CloseBraceToken>}</CloseBraceToken> </CategoryEscape> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> <ZeroOrOneQuantifier> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>s</TextToken> </CharacterClassEscape> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <QuestionToken>?</QuestionToken> </ZeroOrOneQuantifier> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> <CategoryEscape> <BackslashToken>\</BackslashToken> <TextToken>p</TextToken> <OpenBraceToken>{</OpenBraceToken> <EscapeCategoryToken>Pd</EscapeCategoryToken> <CloseBraceToken>}</CloseBraceToken> </CategoryEscape> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>s</TextToken> </CharacterClassEscape> <OneOrMoreQuantifier> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <OneOrMoreQuantifier> <CategoryEscape> <BackslashToken>\</BackslashToken> <TextToken>p</TextToken> <OpenBraceToken>{</OpenBraceToken> <EscapeCategoryToken>IsBasicLatin</EscapeCategoryToken> <CloseBraceToken>}</CloseBraceToken> </CategoryEscape> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> <ZeroOrOneQuantifier> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>s</TextToken> </CharacterClassEscape> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <QuestionToken>?</QuestionToken> </ZeroOrOneQuantifier> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..65)"" Text=""\b(\p{IsGreek}+(\s)?)+\p{Pd}\s(\p{IsBasicLatin}+(\s)?)+"" /> <Capture Name=""1"" Span=""[12..31)"" Text=""(\p{IsGreek}+(\s)?)"" /> <Capture Name=""2"" Span=""[25..29)"" Text=""(\s)"" /> <Capture Name=""3"" Span=""[40..64)"" Text=""(\p{IsBasicLatin}+(\s)?)"" /> <Capture Name=""4"" Span=""[58..62)"" Text=""(\s)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest39() { Test(@"@""\b.*[.?!;:](\s|\z)""", @"<Tree> <CompilationUnit> <Sequence> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>b</TextToken> </AnchorEscape> <ZeroOrMoreQuantifier> <Wildcard> <DotToken>.</DotToken> </Wildcard> <AsteriskToken>*</AsteriskToken> </ZeroOrMoreQuantifier> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <Text> <TextToken>.?!;:</TextToken> </Text> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Alternation> <Sequence> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>s</TextToken> </CharacterClassEscape> </Sequence> <BarToken>|</BarToken> <Sequence> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>z</TextToken> </AnchorEscape> </Sequence> </Alternation> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..28)"" Text=""\b.*[.?!;:](\s|\z)"" /> <Capture Name=""1"" Span=""[21..28)"" Text=""(\s|\z)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest40() { Test(@"@""^.+""", @"<Tree> <CompilationUnit> <Sequence> <StartAnchor> <CaretToken>^</CaretToken> </StartAnchor> <OneOrMoreQuantifier> <Wildcard> <DotToken>.</DotToken> </Wildcard> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..13)"" Text=""^.+"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest41() { Test(@"@""[^o]""", @"<Tree> <CompilationUnit> <Sequence> <NegatedCharacterClass> <OpenBracketToken>[</OpenBracketToken> <CaretToken>^</CaretToken> <Sequence> <Text> <TextToken>o</TextToken> </Text> </Sequence> <CloseBracketToken>]</CloseBracketToken> </NegatedCharacterClass> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..14)"" Text=""[^o]"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest42() { Test(@"@""\bth[^o]\w+\b""", @"<Tree> <CompilationUnit> <Sequence> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>b</TextToken> </AnchorEscape> <Text> <TextToken>th</TextToken> </Text> <NegatedCharacterClass> <OpenBracketToken>[</OpenBracketToken> <CaretToken>^</CaretToken> <Sequence> <Text> <TextToken>o</TextToken> </Text> </Sequence> <CloseBracketToken>]</CloseBracketToken> </NegatedCharacterClass> <OneOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>w</TextToken> </CharacterClassEscape> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>b</TextToken> </AnchorEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..23)"" Text=""\bth[^o]\w+\b"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest43() { Test(@"@""(\P{Sc})+""", @"<Tree> <CompilationUnit> <Sequence> <OneOrMoreQuantifier> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <CategoryEscape> <BackslashToken>\</BackslashToken> <TextToken>P</TextToken> <OpenBraceToken>{</OpenBraceToken> <EscapeCategoryToken>Sc</EscapeCategoryToken> <CloseBraceToken>}</CloseBraceToken> </CategoryEscape> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..19)"" Text=""(\P{Sc})+"" /> <Capture Name=""1"" Span=""[10..18)"" Text=""(\P{Sc})"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest44() { Test(@"@""[^\p{P}\d]""", @"<Tree> <CompilationUnit> <Sequence> <NegatedCharacterClass> <OpenBracketToken>[</OpenBracketToken> <CaretToken>^</CaretToken> <Sequence> <CategoryEscape> <BackslashToken>\</BackslashToken> <TextToken>p</TextToken> <OpenBraceToken>{</OpenBraceToken> <EscapeCategoryToken>P</EscapeCategoryToken> <CloseBraceToken>}</CloseBraceToken> </CategoryEscape> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>d</TextToken> </CharacterClassEscape> </Sequence> <CloseBracketToken>]</CloseBracketToken> </NegatedCharacterClass> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..20)"" Text=""[^\p{P}\d]"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest45() { Test(@"@""\b[A-Z]\w*\b""", @"<Tree> <CompilationUnit> <Sequence> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>b</TextToken> </AnchorEscape> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <CharacterClassRange> <Text> <TextToken>A</TextToken> </Text> <MinusToken>-</MinusToken> <Text> <TextToken>Z</TextToken> </Text> </CharacterClassRange> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> <ZeroOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>w</TextToken> </CharacterClassEscape> <AsteriskToken>*</AsteriskToken> </ZeroOrMoreQuantifier> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>b</TextToken> </AnchorEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..22)"" Text=""\b[A-Z]\w*\b"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest46() { Test(@"@""\S+?""", @"<Tree> <CompilationUnit> <Sequence> <LazyQuantifier> <OneOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>S</TextToken> </CharacterClassEscape> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> <QuestionToken>?</QuestionToken> </LazyQuantifier> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..14)"" Text=""\S+?"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest47() { Test(@"@""y\s""", @"<Tree> <CompilationUnit> <Sequence> <Text> <TextToken>y</TextToken> </Text> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>s</TextToken> </CharacterClassEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..13)"" Text=""y\s"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest48() { Test(@"@""gr[ae]y\s\S+?[\s\p{P}]""", @"<Tree> <CompilationUnit> <Sequence> <Text> <TextToken>gr</TextToken> </Text> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <Text> <TextToken>ae</TextToken> </Text> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> <Text> <TextToken>y</TextToken> </Text> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>s</TextToken> </CharacterClassEscape> <LazyQuantifier> <OneOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>S</TextToken> </CharacterClassEscape> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> <QuestionToken>?</QuestionToken> </LazyQuantifier> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>s</TextToken> </CharacterClassEscape> <CategoryEscape> <BackslashToken>\</BackslashToken> <TextToken>p</TextToken> <OpenBraceToken>{</OpenBraceToken> <EscapeCategoryToken>P</EscapeCategoryToken> <CloseBraceToken>}</CloseBraceToken> </CategoryEscape> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..32)"" Text=""gr[ae]y\s\S+?[\s\p{P}]"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest49() { Test(@"@""[\s\p{P}]""", @"<Tree> <CompilationUnit> <Sequence> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>s</TextToken> </CharacterClassEscape> <CategoryEscape> <BackslashToken>\</BackslashToken> <TextToken>p</TextToken> <OpenBraceToken>{</OpenBraceToken> <EscapeCategoryToken>P</EscapeCategoryToken> <CloseBraceToken>}</CloseBraceToken> </CategoryEscape> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..19)"" Text=""[\s\p{P}]"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest50() { Test(@"@""[\p{P}\d]""", @"<Tree> <CompilationUnit> <Sequence> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <CategoryEscape> <BackslashToken>\</BackslashToken> <TextToken>p</TextToken> <OpenBraceToken>{</OpenBraceToken> <EscapeCategoryToken>P</EscapeCategoryToken> <CloseBraceToken>}</CloseBraceToken> </CategoryEscape> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>d</TextToken> </CharacterClassEscape> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..19)"" Text=""[\p{P}\d]"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest51() { Test(@"@""[^aeiou]""", @"<Tree> <CompilationUnit> <Sequence> <NegatedCharacterClass> <OpenBracketToken>[</OpenBracketToken> <CaretToken>^</CaretToken> <Sequence> <Text> <TextToken>aeiou</TextToken> </Text> </Sequence> <CloseBracketToken>]</CloseBracketToken> </NegatedCharacterClass> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..18)"" Text=""[^aeiou]"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest52() { Test(@"@""(\w)\1""", @"<Tree> <CompilationUnit> <Sequence> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>w</TextToken> </CharacterClassEscape> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <BackreferenceEscape> <BackslashToken>\</BackslashToken> <NumberToken value=""1"">1</NumberToken> </BackreferenceEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..16)"" Text=""(\w)\1"" /> <Capture Name=""1"" Span=""[10..14)"" Text=""(\w)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest53() { Test(@"@""[^\p{Ll}\p{Lu}\p{Lt}\p{Lo}\p{Nd}\p{Pc}\p{Lm}] """, @"<Tree> <CompilationUnit> <Sequence> <NegatedCharacterClass> <OpenBracketToken>[</OpenBracketToken> <CaretToken>^</CaretToken> <Sequence> <CategoryEscape> <BackslashToken>\</BackslashToken> <TextToken>p</TextToken> <OpenBraceToken>{</OpenBraceToken> <EscapeCategoryToken>Ll</EscapeCategoryToken> <CloseBraceToken>}</CloseBraceToken> </CategoryEscape> <CategoryEscape> <BackslashToken>\</BackslashToken> <TextToken>p</TextToken> <OpenBraceToken>{</OpenBraceToken> <EscapeCategoryToken>Lu</EscapeCategoryToken> <CloseBraceToken>}</CloseBraceToken> </CategoryEscape> <CategoryEscape> <BackslashToken>\</BackslashToken> <TextToken>p</TextToken> <OpenBraceToken>{</OpenBraceToken> <EscapeCategoryToken>Lt</EscapeCategoryToken> <CloseBraceToken>}</CloseBraceToken> </CategoryEscape> <CategoryEscape> <BackslashToken>\</BackslashToken> <TextToken>p</TextToken> <OpenBraceToken>{</OpenBraceToken> <EscapeCategoryToken>Lo</EscapeCategoryToken> <CloseBraceToken>}</CloseBraceToken> </CategoryEscape> <CategoryEscape> <BackslashToken>\</BackslashToken> <TextToken>p</TextToken> <OpenBraceToken>{</OpenBraceToken> <EscapeCategoryToken>Nd</EscapeCategoryToken> <CloseBraceToken>}</CloseBraceToken> </CategoryEscape> <CategoryEscape> <BackslashToken>\</BackslashToken> <TextToken>p</TextToken> <OpenBraceToken>{</OpenBraceToken> <EscapeCategoryToken>Pc</EscapeCategoryToken> <CloseBraceToken>}</CloseBraceToken> </CategoryEscape> <CategoryEscape> <BackslashToken>\</BackslashToken> <TextToken>p</TextToken> <OpenBraceToken>{</OpenBraceToken> <EscapeCategoryToken>Lm</EscapeCategoryToken> <CloseBraceToken>}</CloseBraceToken> </CategoryEscape> </Sequence> <CloseBracketToken>]</CloseBracketToken> </NegatedCharacterClass> <Text> <TextToken> </TextToken> </Text> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..56)"" Text=""[^\p{Ll}\p{Lu}\p{Lt}\p{Lo}\p{Nd}\p{Pc}\p{Lm}] "" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest54() { Test(@"@""[^a-zA-Z_0-9]""", @"<Tree> <CompilationUnit> <Sequence> <NegatedCharacterClass> <OpenBracketToken>[</OpenBracketToken> <CaretToken>^</CaretToken> <Sequence> <CharacterClassRange> <Text> <TextToken>a</TextToken> </Text> <MinusToken>-</MinusToken> <Text> <TextToken>z</TextToken> </Text> </CharacterClassRange> <CharacterClassRange> <Text> <TextToken>A</TextToken> </Text> <MinusToken>-</MinusToken> <Text> <TextToken>Z</TextToken> </Text> </CharacterClassRange> <Text> <TextToken>_</TextToken> </Text> <CharacterClassRange> <Text> <TextToken>0</TextToken> </Text> <MinusToken>-</MinusToken> <Text> <TextToken>9</TextToken> </Text> </CharacterClassRange> </Sequence> <CloseBracketToken>]</CloseBracketToken> </NegatedCharacterClass> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..23)"" Text=""[^a-zA-Z_0-9]"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest55() { Test(@"@""\P{Nd}""", @"<Tree> <CompilationUnit> <Sequence> <CategoryEscape> <BackslashToken>\</BackslashToken> <TextToken>P</TextToken> <OpenBraceToken>{</OpenBraceToken> <EscapeCategoryToken>Nd</EscapeCategoryToken> <CloseBraceToken>}</CloseBraceToken> </CategoryEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..16)"" Text=""\P{Nd}"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest56() { Test(@"@""(\(?\d{3}\)?[\s-])?""", @"<Tree> <CompilationUnit> <Sequence> <ZeroOrOneQuantifier> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <ZeroOrOneQuantifier> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken>(</TextToken> </SimpleEscape> <QuestionToken>?</QuestionToken> </ZeroOrOneQuantifier> <ExactNumericQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>d</TextToken> </CharacterClassEscape> <OpenBraceToken>{</OpenBraceToken> <NumberToken value=""3"">3</NumberToken> <CloseBraceToken>}</CloseBraceToken> </ExactNumericQuantifier> <ZeroOrOneQuantifier> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken>)</TextToken> </SimpleEscape> <QuestionToken>?</QuestionToken> </ZeroOrOneQuantifier> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>s</TextToken> </CharacterClassEscape> <Text> <TextToken>-</TextToken> </Text> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <QuestionToken>?</QuestionToken> </ZeroOrOneQuantifier> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..29)"" Text=""(\(?\d{3}\)?[\s-])?"" /> <Capture Name=""1"" Span=""[10..28)"" Text=""(\(?\d{3}\)?[\s-])"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest57() { Test(@"@""^(\(?\d{3}\)?[\s-])?\d{3}-\d{4}$""", @"<Tree> <CompilationUnit> <Sequence> <StartAnchor> <CaretToken>^</CaretToken> </StartAnchor> <ZeroOrOneQuantifier> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <ZeroOrOneQuantifier> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken>(</TextToken> </SimpleEscape> <QuestionToken>?</QuestionToken> </ZeroOrOneQuantifier> <ExactNumericQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>d</TextToken> </CharacterClassEscape> <OpenBraceToken>{</OpenBraceToken> <NumberToken value=""3"">3</NumberToken> <CloseBraceToken>}</CloseBraceToken> </ExactNumericQuantifier> <ZeroOrOneQuantifier> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken>)</TextToken> </SimpleEscape> <QuestionToken>?</QuestionToken> </ZeroOrOneQuantifier> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>s</TextToken> </CharacterClassEscape> <Text> <TextToken>-</TextToken> </Text> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <QuestionToken>?</QuestionToken> </ZeroOrOneQuantifier> <ExactNumericQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>d</TextToken> </CharacterClassEscape> <OpenBraceToken>{</OpenBraceToken> <NumberToken value=""3"">3</NumberToken> <CloseBraceToken>}</CloseBraceToken> </ExactNumericQuantifier> <Text> <TextToken>-</TextToken> </Text> <ExactNumericQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>d</TextToken> </CharacterClassEscape> <OpenBraceToken>{</OpenBraceToken> <NumberToken value=""4"">4</NumberToken> <CloseBraceToken>}</CloseBraceToken> </ExactNumericQuantifier> <EndAnchor> <DollarToken>$</DollarToken> </EndAnchor> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..42)"" Text=""^(\(?\d{3}\)?[\s-])?\d{3}-\d{4}$"" /> <Capture Name=""1"" Span=""[11..29)"" Text=""(\(?\d{3}\)?[\s-])"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest58() { Test(@"@""[0-9]""", @"<Tree> <CompilationUnit> <Sequence> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <CharacterClassRange> <Text> <TextToken>0</TextToken> </Text> <MinusToken>-</MinusToken> <Text> <TextToken>9</TextToken> </Text> </CharacterClassRange> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..15)"" Text=""[0-9]"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest59() { Test(@"@""\p{Nd}""", @"<Tree> <CompilationUnit> <Sequence> <CategoryEscape> <BackslashToken>\</BackslashToken> <TextToken>p</TextToken> <OpenBraceToken>{</OpenBraceToken> <EscapeCategoryToken>Nd</EscapeCategoryToken> <CloseBraceToken>}</CloseBraceToken> </CategoryEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..16)"" Text=""\p{Nd}"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest60() { Test(@"@""\b(\S+)\s?""", @"<Tree> <CompilationUnit> <Sequence> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>b</TextToken> </AnchorEscape> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <OneOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>S</TextToken> </CharacterClassEscape> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <ZeroOrOneQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>s</TextToken> </CharacterClassEscape> <QuestionToken>?</QuestionToken> </ZeroOrOneQuantifier> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..20)"" Text=""\b(\S+)\s?"" /> <Capture Name=""1"" Span=""[12..17)"" Text=""(\S+)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest61() { Test(@"@""[^ \f\n\r\t\v]""", @"<Tree> <CompilationUnit> <Sequence> <NegatedCharacterClass> <OpenBracketToken>[</OpenBracketToken> <CaretToken>^</CaretToken> <Sequence> <Text> <TextToken> </TextToken> </Text> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken>f</TextToken> </SimpleEscape> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken>n</TextToken> </SimpleEscape> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken>r</TextToken> </SimpleEscape> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken>t</TextToken> </SimpleEscape> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken>v</TextToken> </SimpleEscape> </Sequence> <CloseBracketToken>]</CloseBracketToken> </NegatedCharacterClass> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..24)"" Text=""[^ \f\n\r\t\v]"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest62() { Test(@"@""[^\f\n\r\t\v\x85\p{Z}]""", @"<Tree> <CompilationUnit> <Sequence> <NegatedCharacterClass> <OpenBracketToken>[</OpenBracketToken> <CaretToken>^</CaretToken> <Sequence> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken>f</TextToken> </SimpleEscape> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken>n</TextToken> </SimpleEscape> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken>r</TextToken> </SimpleEscape> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken>t</TextToken> </SimpleEscape> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken>v</TextToken> </SimpleEscape> <HexEscape> <BackslashToken>\</BackslashToken> <TextToken>x</TextToken> <TextToken>85</TextToken> </HexEscape> <CategoryEscape> <BackslashToken>\</BackslashToken> <TextToken>p</TextToken> <OpenBraceToken>{</OpenBraceToken> <EscapeCategoryToken>Z</EscapeCategoryToken> <CloseBraceToken>}</CloseBraceToken> </CategoryEscape> </Sequence> <CloseBracketToken>]</CloseBracketToken> </NegatedCharacterClass> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..32)"" Text=""[^\f\n\r\t\v\x85\p{Z}]"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest63() { Test(@"@""(\s|$)""", @"<Tree> <CompilationUnit> <Sequence> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Alternation> <Sequence> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>s</TextToken> </CharacterClassEscape> </Sequence> <BarToken>|</BarToken> <Sequence> <EndAnchor> <DollarToken>$</DollarToken> </EndAnchor> </Sequence> </Alternation> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..16)"" Text=""(\s|$)"" /> <Capture Name=""1"" Span=""[10..16)"" Text=""(\s|$)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest64() { Test(@"@""\b\w+(e)?s(\s|$)""", @"<Tree> <CompilationUnit> <Sequence> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>b</TextToken> </AnchorEscape> <OneOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>w</TextToken> </CharacterClassEscape> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> <ZeroOrOneQuantifier> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <Text> <TextToken>e</TextToken> </Text> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <QuestionToken>?</QuestionToken> </ZeroOrOneQuantifier> <Text> <TextToken>s</TextToken> </Text> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Alternation> <Sequence> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>s</TextToken> </CharacterClassEscape> </Sequence> <BarToken>|</BarToken> <Sequence> <EndAnchor> <DollarToken>$</DollarToken> </EndAnchor> </Sequence> </Alternation> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..26)"" Text=""\b\w+(e)?s(\s|$)"" /> <Capture Name=""1"" Span=""[15..18)"" Text=""(e)"" /> <Capture Name=""2"" Span=""[20..26)"" Text=""(\s|$)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest65() { Test(@"@""[ \f\n\r\t\v]""", @"<Tree> <CompilationUnit> <Sequence> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <Text> <TextToken> </TextToken> </Text> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken>f</TextToken> </SimpleEscape> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken>n</TextToken> </SimpleEscape> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken>r</TextToken> </SimpleEscape> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken>t</TextToken> </SimpleEscape> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken>v</TextToken> </SimpleEscape> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..23)"" Text=""[ \f\n\r\t\v]"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest66() { Test(@"@""(\W){1,2}""", @"<Tree> <CompilationUnit> <Sequence> <ClosedRangeNumericQuantifier> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>W</TextToken> </CharacterClassEscape> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <OpenBraceToken>{</OpenBraceToken> <NumberToken value=""1"">1</NumberToken> <CommaToken>,</CommaToken> <NumberToken value=""2"">2</NumberToken> <CloseBraceToken>}</CloseBraceToken> </ClosedRangeNumericQuantifier> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..19)"" Text=""(\W){1,2}"" /> <Capture Name=""1"" Span=""[10..14)"" Text=""(\W)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest67() { Test(@"@""(\w+)""", @"<Tree> <CompilationUnit> <Sequence> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <OneOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>w</TextToken> </CharacterClassEscape> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..15)"" Text=""(\w+)"" /> <Capture Name=""1"" Span=""[10..15)"" Text=""(\w+)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest68() { Test(@"@""\b""", @"<Tree> <CompilationUnit> <Sequence> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>b</TextToken> </AnchorEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..12)"" Text=""\b"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest69() { Test(@"@""\b(\w+)(\W){1,2}""", @"<Tree> <CompilationUnit> <Sequence> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>b</TextToken> </AnchorEscape> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <OneOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>w</TextToken> </CharacterClassEscape> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <ClosedRangeNumericQuantifier> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>W</TextToken> </CharacterClassEscape> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <OpenBraceToken>{</OpenBraceToken> <NumberToken value=""1"">1</NumberToken> <CommaToken>,</CommaToken> <NumberToken value=""2"">2</NumberToken> <CloseBraceToken>}</CloseBraceToken> </ClosedRangeNumericQuantifier> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..26)"" Text=""\b(\w+)(\W){1,2}"" /> <Capture Name=""1"" Span=""[12..17)"" Text=""(\w+)"" /> <Capture Name=""2"" Span=""[17..21)"" Text=""(\W)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest70() { Test(@"@""(?>(\w)\1+).\b""", @"<Tree> <CompilationUnit> <Sequence> <AtomicGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <GreaterThanToken>&gt;</GreaterThanToken> <Sequence> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>w</TextToken> </CharacterClassEscape> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <OneOrMoreQuantifier> <BackreferenceEscape> <BackslashToken>\</BackslashToken> <NumberToken value=""1"">1</NumberToken> </BackreferenceEscape> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> </Sequence> <CloseParenToken>)</CloseParenToken> </AtomicGrouping> <Wildcard> <DotToken>.</DotToken> </Wildcard> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>b</TextToken> </AnchorEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..24)"" Text=""(?&gt;(\w)\1+).\b"" /> <Capture Name=""1"" Span=""[13..17)"" Text=""(\w)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest71() { Test(@"@""(\b(\w+)\W+)+""", @"<Tree> <CompilationUnit> <Sequence> <OneOrMoreQuantifier> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>b</TextToken> </AnchorEscape> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <OneOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>w</TextToken> </CharacterClassEscape> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <OneOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>W</TextToken> </CharacterClassEscape> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..23)"" Text=""(\b(\w+)\W+)+"" /> <Capture Name=""1"" Span=""[10..22)"" Text=""(\b(\w+)\W+)"" /> <Capture Name=""2"" Span=""[13..18)"" Text=""(\w+)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest72() { Test(@"@""(\w)\1+.\b""", @"<Tree> <CompilationUnit> <Sequence> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>w</TextToken> </CharacterClassEscape> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <OneOrMoreQuantifier> <BackreferenceEscape> <BackslashToken>\</BackslashToken> <NumberToken value=""1"">1</NumberToken> </BackreferenceEscape> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> <Wildcard> <DotToken>.</DotToken> </Wildcard> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>b</TextToken> </AnchorEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..20)"" Text=""(\w)\1+.\b"" /> <Capture Name=""1"" Span=""[10..14)"" Text=""(\w)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest73() { Test(@"@""\p{Sc}*(\s?\d+[.,]?\d*)\p{Sc}*""", @"<Tree> <CompilationUnit> <Sequence> <ZeroOrMoreQuantifier> <CategoryEscape> <BackslashToken>\</BackslashToken> <TextToken>p</TextToken> <OpenBraceToken>{</OpenBraceToken> <EscapeCategoryToken>Sc</EscapeCategoryToken> <CloseBraceToken>}</CloseBraceToken> </CategoryEscape> <AsteriskToken>*</AsteriskToken> </ZeroOrMoreQuantifier> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <ZeroOrOneQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>s</TextToken> </CharacterClassEscape> <QuestionToken>?</QuestionToken> </ZeroOrOneQuantifier> <OneOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>d</TextToken> </CharacterClassEscape> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> <ZeroOrOneQuantifier> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <Text> <TextToken>.,</TextToken> </Text> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> <QuestionToken>?</QuestionToken> </ZeroOrOneQuantifier> <ZeroOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>d</TextToken> </CharacterClassEscape> <AsteriskToken>*</AsteriskToken> </ZeroOrMoreQuantifier> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <ZeroOrMoreQuantifier> <CategoryEscape> <BackslashToken>\</BackslashToken> <TextToken>p</TextToken> <OpenBraceToken>{</OpenBraceToken> <EscapeCategoryToken>Sc</EscapeCategoryToken> <CloseBraceToken>}</CloseBraceToken> </CategoryEscape> <AsteriskToken>*</AsteriskToken> </ZeroOrMoreQuantifier> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..40)"" Text=""\p{Sc}*(\s?\d+[.,]?\d*)\p{Sc}*"" /> <Capture Name=""1"" Span=""[17..33)"" Text=""(\s?\d+[.,]?\d*)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest74() { Test(@"@""p{Sc}*(?<amount>\s?\d+[.,]?\d*)\p{Sc}*""", @"<Tree> <CompilationUnit> <Sequence> <Text> <TextToken>p{Sc</TextToken> </Text> <ZeroOrMoreQuantifier> <Text> <TextToken>}</TextToken> </Text> <AsteriskToken>*</AsteriskToken> </ZeroOrMoreQuantifier> <CaptureGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <CaptureNameToken value=""amount"">amount</CaptureNameToken> <GreaterThanToken>&gt;</GreaterThanToken> <Sequence> <ZeroOrOneQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>s</TextToken> </CharacterClassEscape> <QuestionToken>?</QuestionToken> </ZeroOrOneQuantifier> <OneOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>d</TextToken> </CharacterClassEscape> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> <ZeroOrOneQuantifier> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <Text> <TextToken>.,</TextToken> </Text> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> <QuestionToken>?</QuestionToken> </ZeroOrOneQuantifier> <ZeroOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>d</TextToken> </CharacterClassEscape> <AsteriskToken>*</AsteriskToken> </ZeroOrMoreQuantifier> </Sequence> <CloseParenToken>)</CloseParenToken> </CaptureGrouping> <ZeroOrMoreQuantifier> <CategoryEscape> <BackslashToken>\</BackslashToken> <TextToken>p</TextToken> <OpenBraceToken>{</OpenBraceToken> <EscapeCategoryToken>Sc</EscapeCategoryToken> <CloseBraceToken>}</CloseBraceToken> </CategoryEscape> <AsteriskToken>*</AsteriskToken> </ZeroOrMoreQuantifier> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..48)"" Text=""p{Sc}*(?&lt;amount&gt;\s?\d+[.,]?\d*)\p{Sc}*"" /> <Capture Name=""1"" Span=""[16..41)"" Text=""(?&lt;amount&gt;\s?\d+[.,]?\d*)"" /> <Capture Name=""amount"" Span=""[16..41)"" Text=""(?&lt;amount&gt;\s?\d+[.,]?\d*)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest75() { Test(@"@""^(\w+\s?)+$""", @"<Tree> <CompilationUnit> <Sequence> <StartAnchor> <CaretToken>^</CaretToken> </StartAnchor> <OneOrMoreQuantifier> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <OneOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>w</TextToken> </CharacterClassEscape> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> <ZeroOrOneQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>s</TextToken> </CharacterClassEscape> <QuestionToken>?</QuestionToken> </ZeroOrOneQuantifier> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> <EndAnchor> <DollarToken>$</DollarToken> </EndAnchor> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..21)"" Text=""^(\w+\s?)+$"" /> <Capture Name=""1"" Span=""[11..19)"" Text=""(\w+\s?)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest76() { Test(@"@""(?ix) d \w+ \s""", @"<Tree> <CompilationUnit> <Sequence> <SimpleOptionsGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <OptionsToken>ix</OptionsToken> <CloseParenToken>)</CloseParenToken> </SimpleOptionsGrouping> <Text> <TextToken> <Trivia> <WhitespaceTrivia> </WhitespaceTrivia> </Trivia>d</TextToken> </Text> <OneOrMoreQuantifier> <CharacterClassEscape> <BackslashToken> <Trivia> <WhitespaceTrivia> </WhitespaceTrivia> </Trivia>\</BackslashToken> <TextToken>w</TextToken> </CharacterClassEscape> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> <CharacterClassEscape> <BackslashToken> <Trivia> <WhitespaceTrivia> </WhitespaceTrivia> </Trivia>\</BackslashToken> <TextToken>s</TextToken> </CharacterClassEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..24)"" Text=""(?ix) d \w+ \s"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest77() { Test(@"@""\b(?ix: d \w+)\s""", @"<Tree> <CompilationUnit> <Sequence> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>b</TextToken> </AnchorEscape> <NestedOptionsGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <OptionsToken>ix</OptionsToken> <ColonToken>:</ColonToken> <Sequence> <Text> <TextToken> <Trivia> <WhitespaceTrivia> </WhitespaceTrivia> </Trivia>d</TextToken> </Text> <OneOrMoreQuantifier> <CharacterClassEscape> <BackslashToken> <Trivia> <WhitespaceTrivia> </WhitespaceTrivia> </Trivia>\</BackslashToken> <TextToken>w</TextToken> </CharacterClassEscape> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> </Sequence> <CloseParenToken>)</CloseParenToken> </NestedOptionsGrouping> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>s</TextToken> </CharacterClassEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..26)"" Text=""\b(?ix: d \w+)\s"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest78() { Test(@"@""\bthe\w*\b""", @"<Tree> <CompilationUnit> <Sequence> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>b</TextToken> </AnchorEscape> <Text> <TextToken>the</TextToken> </Text> <ZeroOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>w</TextToken> </CharacterClassEscape> <AsteriskToken>*</AsteriskToken> </ZeroOrMoreQuantifier> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>b</TextToken> </AnchorEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..20)"" Text=""\bthe\w*\b"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest79() { Test(@"@""\b(?i:t)he\w*\b""", @"<Tree> <CompilationUnit> <Sequence> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>b</TextToken> </AnchorEscape> <NestedOptionsGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <OptionsToken>i</OptionsToken> <ColonToken>:</ColonToken> <Sequence> <Text> <TextToken>t</TextToken> </Text> </Sequence> <CloseParenToken>)</CloseParenToken> </NestedOptionsGrouping> <Text> <TextToken>he</TextToken> </Text> <ZeroOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>w</TextToken> </CharacterClassEscape> <AsteriskToken>*</AsteriskToken> </ZeroOrMoreQuantifier> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>b</TextToken> </AnchorEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..25)"" Text=""\b(?i:t)he\w*\b"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest80() { Test(@"@""^(\w+)\s(\d+)$""", @"<Tree> <CompilationUnit> <Sequence> <StartAnchor> <CaretToken>^</CaretToken> </StartAnchor> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <OneOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>w</TextToken> </CharacterClassEscape> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>s</TextToken> </CharacterClassEscape> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <OneOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>d</TextToken> </CharacterClassEscape> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <EndAnchor> <DollarToken>$</DollarToken> </EndAnchor> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..24)"" Text=""^(\w+)\s(\d+)$"" /> <Capture Name=""1"" Span=""[11..16)"" Text=""(\w+)"" /> <Capture Name=""2"" Span=""[18..23)"" Text=""(\d+)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest81() { Test(@"@""^(\w+)\s(\d+)\r*$""", @"<Tree> <CompilationUnit> <Sequence> <StartAnchor> <CaretToken>^</CaretToken> </StartAnchor> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <OneOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>w</TextToken> </CharacterClassEscape> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>s</TextToken> </CharacterClassEscape> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <OneOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>d</TextToken> </CharacterClassEscape> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <ZeroOrMoreQuantifier> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken>r</TextToken> </SimpleEscape> <AsteriskToken>*</AsteriskToken> </ZeroOrMoreQuantifier> <EndAnchor> <DollarToken>$</DollarToken> </EndAnchor> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..27)"" Text=""^(\w+)\s(\d+)\r*$"" /> <Capture Name=""1"" Span=""[11..16)"" Text=""(\w+)"" /> <Capture Name=""2"" Span=""[18..23)"" Text=""(\d+)"" /> </Captures> </Tree>", RegexOptions.Multiline); } [Fact] public void ReferenceTest82() { Test(@"@""(?m)^(\w+)\s(\d+)\r*$""", @"<Tree> <CompilationUnit> <Sequence> <SimpleOptionsGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <OptionsToken>m</OptionsToken> <CloseParenToken>)</CloseParenToken> </SimpleOptionsGrouping> <StartAnchor> <CaretToken>^</CaretToken> </StartAnchor> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <OneOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>w</TextToken> </CharacterClassEscape> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>s</TextToken> </CharacterClassEscape> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <OneOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>d</TextToken> </CharacterClassEscape> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <ZeroOrMoreQuantifier> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken>r</TextToken> </SimpleEscape> <AsteriskToken>*</AsteriskToken> </ZeroOrMoreQuantifier> <EndAnchor> <DollarToken>$</DollarToken> </EndAnchor> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..31)"" Text=""(?m)^(\w+)\s(\d+)\r*$"" /> <Capture Name=""1"" Span=""[15..20)"" Text=""(\w+)"" /> <Capture Name=""2"" Span=""[22..27)"" Text=""(\d+)"" /> </Captures> </Tree>", RegexOptions.Multiline); } [Fact] public void ReferenceTest83() { Test(@"@""(?s)^.+""", @"<Tree> <CompilationUnit> <Sequence> <SimpleOptionsGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <OptionsToken>s</OptionsToken> <CloseParenToken>)</CloseParenToken> </SimpleOptionsGrouping> <StartAnchor> <CaretToken>^</CaretToken> </StartAnchor> <OneOrMoreQuantifier> <Wildcard> <DotToken>.</DotToken> </Wildcard> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..17)"" Text=""(?s)^.+"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest84() { Test(@"@""\b(\d{2}-)*(?(1)\d{7}|\d{3}-\d{2}-\d{4})\b""", @"<Tree> <CompilationUnit> <Sequence> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>b</TextToken> </AnchorEscape> <ZeroOrMoreQuantifier> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <ExactNumericQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>d</TextToken> </CharacterClassEscape> <OpenBraceToken>{</OpenBraceToken> <NumberToken value=""2"">2</NumberToken> <CloseBraceToken>}</CloseBraceToken> </ExactNumericQuantifier> <Text> <TextToken>-</TextToken> </Text> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <AsteriskToken>*</AsteriskToken> </ZeroOrMoreQuantifier> <ConditionalCaptureGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <OpenParenToken>(</OpenParenToken> <NumberToken value=""1"">1</NumberToken> <CloseParenToken>)</CloseParenToken> <Alternation> <Sequence> <ExactNumericQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>d</TextToken> </CharacterClassEscape> <OpenBraceToken>{</OpenBraceToken> <NumberToken value=""7"">7</NumberToken> <CloseBraceToken>}</CloseBraceToken> </ExactNumericQuantifier> </Sequence> <BarToken>|</BarToken> <Sequence> <ExactNumericQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>d</TextToken> </CharacterClassEscape> <OpenBraceToken>{</OpenBraceToken> <NumberToken value=""3"">3</NumberToken> <CloseBraceToken>}</CloseBraceToken> </ExactNumericQuantifier> <Text> <TextToken>-</TextToken> </Text> <ExactNumericQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>d</TextToken> </CharacterClassEscape> <OpenBraceToken>{</OpenBraceToken> <NumberToken value=""2"">2</NumberToken> <CloseBraceToken>}</CloseBraceToken> </ExactNumericQuantifier> <Text> <TextToken>-</TextToken> </Text> <ExactNumericQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>d</TextToken> </CharacterClassEscape> <OpenBraceToken>{</OpenBraceToken> <NumberToken value=""4"">4</NumberToken> <CloseBraceToken>}</CloseBraceToken> </ExactNumericQuantifier> </Sequence> </Alternation> <CloseParenToken>)</CloseParenToken> </ConditionalCaptureGrouping> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>b</TextToken> </AnchorEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..52)"" Text=""\b(\d{2}-)*(?(1)\d{7}|\d{3}-\d{2}-\d{4})\b"" /> <Capture Name=""1"" Span=""[12..20)"" Text=""(\d{2}-)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest85() { Test(@"@""\b\(?((\w+),?\s?)+[\.!?]\)?""", @"<Tree> <CompilationUnit> <Sequence> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>b</TextToken> </AnchorEscape> <ZeroOrOneQuantifier> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken>(</TextToken> </SimpleEscape> <QuestionToken>?</QuestionToken> </ZeroOrOneQuantifier> <OneOrMoreQuantifier> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <OneOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>w</TextToken> </CharacterClassEscape> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <ZeroOrOneQuantifier> <Text> <TextToken>,</TextToken> </Text> <QuestionToken>?</QuestionToken> </ZeroOrOneQuantifier> <ZeroOrOneQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>s</TextToken> </CharacterClassEscape> <QuestionToken>?</QuestionToken> </ZeroOrOneQuantifier> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken>.</TextToken> </SimpleEscape> <Text> <TextToken>!?</TextToken> </Text> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> <ZeroOrOneQuantifier> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken>)</TextToken> </SimpleEscape> <QuestionToken>?</QuestionToken> </ZeroOrOneQuantifier> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..37)"" Text=""\b\(?((\w+),?\s?)+[\.!?]\)?"" /> <Capture Name=""1"" Span=""[15..27)"" Text=""((\w+),?\s?)"" /> <Capture Name=""2"" Span=""[16..21)"" Text=""(\w+)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest86() { Test(@"@""(?n)\b\(?((?>\w+),?\s?)+[\.!?]\)?""", @"<Tree> <CompilationUnit> <Sequence> <SimpleOptionsGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <OptionsToken>n</OptionsToken> <CloseParenToken>)</CloseParenToken> </SimpleOptionsGrouping> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>b</TextToken> </AnchorEscape> <ZeroOrOneQuantifier> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken>(</TextToken> </SimpleEscape> <QuestionToken>?</QuestionToken> </ZeroOrOneQuantifier> <OneOrMoreQuantifier> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <AtomicGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <GreaterThanToken>&gt;</GreaterThanToken> <Sequence> <OneOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>w</TextToken> </CharacterClassEscape> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> </Sequence> <CloseParenToken>)</CloseParenToken> </AtomicGrouping> <ZeroOrOneQuantifier> <Text> <TextToken>,</TextToken> </Text> <QuestionToken>?</QuestionToken> </ZeroOrOneQuantifier> <ZeroOrOneQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>s</TextToken> </CharacterClassEscape> <QuestionToken>?</QuestionToken> </ZeroOrOneQuantifier> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken>.</TextToken> </SimpleEscape> <Text> <TextToken>!?</TextToken> </Text> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> <ZeroOrOneQuantifier> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken>)</TextToken> </SimpleEscape> <QuestionToken>?</QuestionToken> </ZeroOrOneQuantifier> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..43)"" Text=""(?n)\b\(?((?&gt;\w+),?\s?)+[\.!?]\)?"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest87() { Test(@"@""\b\(?(?n:(?>\w+),?\s?)+[\.!?]\)?""", @"<Tree> <CompilationUnit> <Sequence> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>b</TextToken> </AnchorEscape> <ZeroOrOneQuantifier> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken>(</TextToken> </SimpleEscape> <QuestionToken>?</QuestionToken> </ZeroOrOneQuantifier> <OneOrMoreQuantifier> <NestedOptionsGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <OptionsToken>n</OptionsToken> <ColonToken>:</ColonToken> <Sequence> <AtomicGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <GreaterThanToken>&gt;</GreaterThanToken> <Sequence> <OneOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>w</TextToken> </CharacterClassEscape> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> </Sequence> <CloseParenToken>)</CloseParenToken> </AtomicGrouping> <ZeroOrOneQuantifier> <Text> <TextToken>,</TextToken> </Text> <QuestionToken>?</QuestionToken> </ZeroOrOneQuantifier> <ZeroOrOneQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>s</TextToken> </CharacterClassEscape> <QuestionToken>?</QuestionToken> </ZeroOrOneQuantifier> </Sequence> <CloseParenToken>)</CloseParenToken> </NestedOptionsGrouping> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken>.</TextToken> </SimpleEscape> <Text> <TextToken>!?</TextToken> </Text> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> <ZeroOrOneQuantifier> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken>)</TextToken> </SimpleEscape> <QuestionToken>?</QuestionToken> </ZeroOrOneQuantifier> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..42)"" Text=""\b\(?(?n:(?&gt;\w+),?\s?)+[\.!?]\)?"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest88() { Test(@"@""\b\(?((?>\w+),?\s?)+[\.!?]\)?""", @"<Tree> <CompilationUnit> <Sequence> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>b</TextToken> </AnchorEscape> <ZeroOrOneQuantifier> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken>(</TextToken> </SimpleEscape> <QuestionToken>?</QuestionToken> </ZeroOrOneQuantifier> <OneOrMoreQuantifier> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <AtomicGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <GreaterThanToken>&gt;</GreaterThanToken> <Sequence> <OneOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>w</TextToken> </CharacterClassEscape> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> </Sequence> <CloseParenToken>)</CloseParenToken> </AtomicGrouping> <ZeroOrOneQuantifier> <Text> <TextToken>,</TextToken> </Text> <QuestionToken>?</QuestionToken> </ZeroOrOneQuantifier> <ZeroOrOneQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>s</TextToken> </CharacterClassEscape> <QuestionToken>?</QuestionToken> </ZeroOrOneQuantifier> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken>.</TextToken> </SimpleEscape> <Text> <TextToken>!?</TextToken> </Text> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> <ZeroOrOneQuantifier> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken>)</TextToken> </SimpleEscape> <QuestionToken>?</QuestionToken> </ZeroOrOneQuantifier> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..39)"" Text=""\b\(?((?&gt;\w+),?\s?)+[\.!?]\)?"" /> <Capture Name=""1"" Span=""[15..29)"" Text=""((?&gt;\w+),?\s?)"" /> </Captures> </Tree>", RegexOptions.IgnorePatternWhitespace); } [Fact] public void ReferenceTest89() { Test(@"@""(?x)\b \(? ( (?>\w+) ,?\s? )+ [\.!?] \)? # Matches an entire sentence.""", @"<Tree> <CompilationUnit> <Sequence> <SimpleOptionsGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <OptionsToken>x</OptionsToken> <CloseParenToken>)</CloseParenToken> </SimpleOptionsGrouping> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>b</TextToken> </AnchorEscape> <ZeroOrOneQuantifier> <SimpleEscape> <BackslashToken> <Trivia> <WhitespaceTrivia> </WhitespaceTrivia> </Trivia>\</BackslashToken> <TextToken>(</TextToken> </SimpleEscape> <QuestionToken>?</QuestionToken> </ZeroOrOneQuantifier> <OneOrMoreQuantifier> <SimpleGrouping> <OpenParenToken> <Trivia> <WhitespaceTrivia> </WhitespaceTrivia> </Trivia>(</OpenParenToken> <Sequence> <AtomicGrouping> <OpenParenToken> <Trivia> <WhitespaceTrivia> </WhitespaceTrivia> </Trivia>(</OpenParenToken> <QuestionToken>?</QuestionToken> <GreaterThanToken>&gt;</GreaterThanToken> <Sequence> <OneOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>w</TextToken> </CharacterClassEscape> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> </Sequence> <CloseParenToken>)</CloseParenToken> </AtomicGrouping> <ZeroOrOneQuantifier> <Text> <TextToken> <Trivia> <WhitespaceTrivia> </WhitespaceTrivia> </Trivia>,</TextToken> </Text> <QuestionToken>?</QuestionToken> </ZeroOrOneQuantifier> <ZeroOrOneQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>s</TextToken> </CharacterClassEscape> <QuestionToken>?</QuestionToken> </ZeroOrOneQuantifier> </Sequence> <CloseParenToken> <Trivia> <WhitespaceTrivia> </WhitespaceTrivia> </Trivia>)</CloseParenToken> </SimpleGrouping> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> <CharacterClass> <OpenBracketToken> <Trivia> <WhitespaceTrivia> </WhitespaceTrivia> </Trivia>[</OpenBracketToken> <Sequence> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken>.</TextToken> </SimpleEscape> <Text> <TextToken>!?</TextToken> </Text> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> <ZeroOrOneQuantifier> <SimpleEscape> <BackslashToken> <Trivia> <WhitespaceTrivia> </WhitespaceTrivia> </Trivia>\</BackslashToken> <TextToken>)</TextToken> </SimpleEscape> <QuestionToken>?</QuestionToken> </ZeroOrOneQuantifier> </Sequence> <EndOfFile> <Trivia> <WhitespaceTrivia> </WhitespaceTrivia> <CommentTrivia># Matches an entire sentence.</CommentTrivia> </Trivia> </EndOfFile> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..81)"" Text=""(?x)\b \(? ( (?&gt;\w+) ,?\s? )+ [\.!?] \)? # Matches an entire sentence."" /> <Capture Name=""1"" Span=""[21..38)"" Text=""( (?&gt;\w+) ,?\s? )"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest90() { Test(@"@""\bb\w+\s""", @"<Tree> <CompilationUnit> <Sequence> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>b</TextToken> </AnchorEscape> <Text> <TextToken>b</TextToken> </Text> <OneOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>w</TextToken> </CharacterClassEscape> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>s</TextToken> </CharacterClassEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..18)"" Text=""\bb\w+\s"" /> </Captures> </Tree>", RegexOptions.RightToLeft); } [Fact] public void ReferenceTest91() { Test(@"@""(?<=\d{1,2}\s)\w+,?\s\d{4}""", @"<Tree> <CompilationUnit> <Sequence> <PositiveLookbehindGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <EqualsToken>=</EqualsToken> <Sequence> <ClosedRangeNumericQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>d</TextToken> </CharacterClassEscape> <OpenBraceToken>{</OpenBraceToken> <NumberToken value=""1"">1</NumberToken> <CommaToken>,</CommaToken> <NumberToken value=""2"">2</NumberToken> <CloseBraceToken>}</CloseBraceToken> </ClosedRangeNumericQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>s</TextToken> </CharacterClassEscape> </Sequence> <CloseParenToken>)</CloseParenToken> </PositiveLookbehindGrouping> <OneOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>w</TextToken> </CharacterClassEscape> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> <ZeroOrOneQuantifier> <Text> <TextToken>,</TextToken> </Text> <QuestionToken>?</QuestionToken> </ZeroOrOneQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>s</TextToken> </CharacterClassEscape> <ExactNumericQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>d</TextToken> </CharacterClassEscape> <OpenBraceToken>{</OpenBraceToken> <NumberToken value=""4"">4</NumberToken> <CloseBraceToken>}</CloseBraceToken> </ExactNumericQuantifier> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..36)"" Text=""(?&lt;=\d{1,2}\s)\w+,?\s\d{4}"" /> </Captures> </Tree>", RegexOptions.RightToLeft); } [Fact] public void ReferenceTest92() { Test(@"@""\b(\w+\s*)+""", @"<Tree> <CompilationUnit> <Sequence> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>b</TextToken> </AnchorEscape> <OneOrMoreQuantifier> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <OneOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>w</TextToken> </CharacterClassEscape> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> <ZeroOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>s</TextToken> </CharacterClassEscape> <AsteriskToken>*</AsteriskToken> </ZeroOrMoreQuantifier> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..21)"" Text=""\b(\w+\s*)+"" /> <Capture Name=""1"" Span=""[12..20)"" Text=""(\w+\s*)"" /> </Captures> </Tree>", RegexOptions.ECMAScript); } [Fact] public void ReferenceTest93() { Test(@"@""((a+)(\1) ?)+""", @"<Tree> <CompilationUnit> <Sequence> <OneOrMoreQuantifier> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <OneOrMoreQuantifier> <Text> <TextToken>a</TextToken> </Text> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <BackreferenceEscape> <BackslashToken>\</BackslashToken> <NumberToken value=""1"">1</NumberToken> </BackreferenceEscape> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <ZeroOrOneQuantifier> <Text> <TextToken> </TextToken> </Text> <QuestionToken>?</QuestionToken> </ZeroOrOneQuantifier> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..23)"" Text=""((a+)(\1) ?)+"" /> <Capture Name=""1"" Span=""[10..22)"" Text=""((a+)(\1) ?)"" /> <Capture Name=""2"" Span=""[11..15)"" Text=""(a+)"" /> <Capture Name=""3"" Span=""[15..19)"" Text=""(\1)"" /> </Captures> </Tree>", RegexOptions.ECMAScript); } [Fact] public void ReferenceTest94() { Test(@"@""\b(D\w+)\s(d\w+)\b""", @"<Tree> <CompilationUnit> <Sequence> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>b</TextToken> </AnchorEscape> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <Text> <TextToken>D</TextToken> </Text> <OneOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>w</TextToken> </CharacterClassEscape> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>s</TextToken> </CharacterClassEscape> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <Text> <TextToken>d</TextToken> </Text> <OneOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>w</TextToken> </CharacterClassEscape> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>b</TextToken> </AnchorEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..28)"" Text=""\b(D\w+)\s(d\w+)\b"" /> <Capture Name=""1"" Span=""[12..18)"" Text=""(D\w+)"" /> <Capture Name=""2"" Span=""[20..26)"" Text=""(d\w+)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest95() { Test(@"@""\b(D\w+)(?ixn) \s (d\w+) \b""", @"<Tree> <CompilationUnit> <Sequence> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>b</TextToken> </AnchorEscape> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <Text> <TextToken>D</TextToken> </Text> <OneOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>w</TextToken> </CharacterClassEscape> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <SimpleOptionsGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <OptionsToken>ixn</OptionsToken> <CloseParenToken>)</CloseParenToken> </SimpleOptionsGrouping> <CharacterClassEscape> <BackslashToken> <Trivia> <WhitespaceTrivia> </WhitespaceTrivia> </Trivia>\</BackslashToken> <TextToken>s</TextToken> </CharacterClassEscape> <SimpleGrouping> <OpenParenToken> <Trivia> <WhitespaceTrivia> </WhitespaceTrivia> </Trivia>(</OpenParenToken> <Sequence> <Text> <TextToken>d</TextToken> </Text> <OneOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>w</TextToken> </CharacterClassEscape> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <AnchorEscape> <BackslashToken> <Trivia> <WhitespaceTrivia> </WhitespaceTrivia> </Trivia>\</BackslashToken> <TextToken>b</TextToken> </AnchorEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..37)"" Text=""\b(D\w+)(?ixn) \s (d\w+) \b"" /> <Capture Name=""1"" Span=""[12..18)"" Text=""(D\w+)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest96() { Test(@"@""\b((?# case-sensitive comparison)D\w+)\s((?#case-insensitive comparison)d\w+)\b""", @"<Tree> <CompilationUnit> <Sequence> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>b</TextToken> </AnchorEscape> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <Text> <TextToken> <Trivia> <CommentTrivia>(?# case-sensitive comparison)</CommentTrivia> </Trivia>D</TextToken> </Text> <OneOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>w</TextToken> </CharacterClassEscape> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>s</TextToken> </CharacterClassEscape> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <Text> <TextToken> <Trivia> <CommentTrivia>(?#case-insensitive comparison)</CommentTrivia> </Trivia>d</TextToken> </Text> <OneOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>w</TextToken> </CharacterClassEscape> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>b</TextToken> </AnchorEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..89)"" Text=""\b((?# case-sensitive comparison)D\w+)\s((?#case-insensitive comparison)d\w+)\b"" /> <Capture Name=""1"" Span=""[12..48)"" Text=""((?# case-sensitive comparison)D\w+)"" /> <Capture Name=""2"" Span=""[50..87)"" Text=""((?#case-insensitive comparison)d\w+)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest97() { Test(@"@""\b\(?((?>\w+),?\s?)+[\.!?]\)?""", @"<Tree> <CompilationUnit> <Sequence> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>b</TextToken> </AnchorEscape> <ZeroOrOneQuantifier> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken>(</TextToken> </SimpleEscape> <QuestionToken>?</QuestionToken> </ZeroOrOneQuantifier> <OneOrMoreQuantifier> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <AtomicGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <GreaterThanToken>&gt;</GreaterThanToken> <Sequence> <OneOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>w</TextToken> </CharacterClassEscape> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> </Sequence> <CloseParenToken>)</CloseParenToken> </AtomicGrouping> <ZeroOrOneQuantifier> <Text> <TextToken>,</TextToken> </Text> <QuestionToken>?</QuestionToken> </ZeroOrOneQuantifier> <ZeroOrOneQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>s</TextToken> </CharacterClassEscape> <QuestionToken>?</QuestionToken> </ZeroOrOneQuantifier> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken>.</TextToken> </SimpleEscape> <Text> <TextToken>!?</TextToken> </Text> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> <ZeroOrOneQuantifier> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken>)</TextToken> </SimpleEscape> <QuestionToken>?</QuestionToken> </ZeroOrOneQuantifier> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..39)"" Text=""\b\(?((?&gt;\w+),?\s?)+[\.!?]\)?"" /> <Capture Name=""1"" Span=""[15..29)"" Text=""((?&gt;\w+),?\s?)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest98() { Test(@"@""\b(?<n2>\d{2}-)*(?(n2)\d{7}|\d{3}-\d{2}-\d{4})\b""", @"<Tree> <CompilationUnit> <Sequence> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>b</TextToken> </AnchorEscape> <ZeroOrMoreQuantifier> <CaptureGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <CaptureNameToken value=""n2"">n2</CaptureNameToken> <GreaterThanToken>&gt;</GreaterThanToken> <Sequence> <ExactNumericQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>d</TextToken> </CharacterClassEscape> <OpenBraceToken>{</OpenBraceToken> <NumberToken value=""2"">2</NumberToken> <CloseBraceToken>}</CloseBraceToken> </ExactNumericQuantifier> <Text> <TextToken>-</TextToken> </Text> </Sequence> <CloseParenToken>)</CloseParenToken> </CaptureGrouping> <AsteriskToken>*</AsteriskToken> </ZeroOrMoreQuantifier> <ConditionalCaptureGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <OpenParenToken>(</OpenParenToken> <CaptureNameToken value=""n2"">n2</CaptureNameToken> <CloseParenToken>)</CloseParenToken> <Alternation> <Sequence> <ExactNumericQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>d</TextToken> </CharacterClassEscape> <OpenBraceToken>{</OpenBraceToken> <NumberToken value=""7"">7</NumberToken> <CloseBraceToken>}</CloseBraceToken> </ExactNumericQuantifier> </Sequence> <BarToken>|</BarToken> <Sequence> <ExactNumericQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>d</TextToken> </CharacterClassEscape> <OpenBraceToken>{</OpenBraceToken> <NumberToken value=""3"">3</NumberToken> <CloseBraceToken>}</CloseBraceToken> </ExactNumericQuantifier> <Text> <TextToken>-</TextToken> </Text> <ExactNumericQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>d</TextToken> </CharacterClassEscape> <OpenBraceToken>{</OpenBraceToken> <NumberToken value=""2"">2</NumberToken> <CloseBraceToken>}</CloseBraceToken> </ExactNumericQuantifier> <Text> <TextToken>-</TextToken> </Text> <ExactNumericQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>d</TextToken> </CharacterClassEscape> <OpenBraceToken>{</OpenBraceToken> <NumberToken value=""4"">4</NumberToken> <CloseBraceToken>}</CloseBraceToken> </ExactNumericQuantifier> </Sequence> </Alternation> <CloseParenToken>)</CloseParenToken> </ConditionalCaptureGrouping> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>b</TextToken> </AnchorEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..58)"" Text=""\b(?&lt;n2&gt;\d{2}-)*(?(n2)\d{7}|\d{3}-\d{2}-\d{4})\b"" /> <Capture Name=""1"" Span=""[12..25)"" Text=""(?&lt;n2&gt;\d{2}-)"" /> <Capture Name=""n2"" Span=""[12..25)"" Text=""(?&lt;n2&gt;\d{2}-)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest99() { Test(@"@""\b(\d{2}-\d{7}|\d{3}-\d{2}-\d{4})\b""", @"<Tree> <CompilationUnit> <Sequence> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>b</TextToken> </AnchorEscape> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Alternation> <Sequence> <ExactNumericQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>d</TextToken> </CharacterClassEscape> <OpenBraceToken>{</OpenBraceToken> <NumberToken value=""2"">2</NumberToken> <CloseBraceToken>}</CloseBraceToken> </ExactNumericQuantifier> <Text> <TextToken>-</TextToken> </Text> <ExactNumericQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>d</TextToken> </CharacterClassEscape> <OpenBraceToken>{</OpenBraceToken> <NumberToken value=""7"">7</NumberToken> <CloseBraceToken>}</CloseBraceToken> </ExactNumericQuantifier> </Sequence> <BarToken>|</BarToken> <Sequence> <ExactNumericQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>d</TextToken> </CharacterClassEscape> <OpenBraceToken>{</OpenBraceToken> <NumberToken value=""3"">3</NumberToken> <CloseBraceToken>}</CloseBraceToken> </ExactNumericQuantifier> <Text> <TextToken>-</TextToken> </Text> <ExactNumericQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>d</TextToken> </CharacterClassEscape> <OpenBraceToken>{</OpenBraceToken> <NumberToken value=""2"">2</NumberToken> <CloseBraceToken>}</CloseBraceToken> </ExactNumericQuantifier> <Text> <TextToken>-</TextToken> </Text> <ExactNumericQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>d</TextToken> </CharacterClassEscape> <OpenBraceToken>{</OpenBraceToken> <NumberToken value=""4"">4</NumberToken> <CloseBraceToken>}</CloseBraceToken> </ExactNumericQuantifier> </Sequence> </Alternation> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>b</TextToken> </AnchorEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..45)"" Text=""\b(\d{2}-\d{7}|\d{3}-\d{2}-\d{4})\b"" /> <Capture Name=""1"" Span=""[12..43)"" Text=""(\d{2}-\d{7}|\d{3}-\d{2}-\d{4})"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest100() { Test(@"@""\bgr(a|e)y\b""", @"<Tree> <CompilationUnit> <Sequence> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>b</TextToken> </AnchorEscape> <Text> <TextToken>gr</TextToken> </Text> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Alternation> <Sequence> <Text> <TextToken>a</TextToken> </Text> </Sequence> <BarToken>|</BarToken> <Sequence> <Text> <TextToken>e</TextToken> </Text> </Sequence> </Alternation> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <Text> <TextToken>y</TextToken> </Text> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>b</TextToken> </AnchorEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..22)"" Text=""\bgr(a|e)y\b"" /> <Capture Name=""1"" Span=""[14..19)"" Text=""(a|e)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest101() { Test(@"@""(?>(\w)\1+).\b""", @"<Tree> <CompilationUnit> <Sequence> <AtomicGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <GreaterThanToken>&gt;</GreaterThanToken> <Sequence> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>w</TextToken> </CharacterClassEscape> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <OneOrMoreQuantifier> <BackreferenceEscape> <BackslashToken>\</BackslashToken> <NumberToken value=""1"">1</NumberToken> </BackreferenceEscape> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> </Sequence> <CloseParenToken>)</CloseParenToken> </AtomicGrouping> <Wildcard> <DotToken>.</DotToken> </Wildcard> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>b</TextToken> </AnchorEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..24)"" Text=""(?&gt;(\w)\1+).\b"" /> <Capture Name=""1"" Span=""[13..17)"" Text=""(\w)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest102() { Test(@"@""(\b(\w+)\W+)+""", @"<Tree> <CompilationUnit> <Sequence> <OneOrMoreQuantifier> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>b</TextToken> </AnchorEscape> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <OneOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>w</TextToken> </CharacterClassEscape> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <OneOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>W</TextToken> </CharacterClassEscape> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..23)"" Text=""(\b(\w+)\W+)+"" /> <Capture Name=""1"" Span=""[10..22)"" Text=""(\b(\w+)\W+)"" /> <Capture Name=""2"" Span=""[13..18)"" Text=""(\w+)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest103() { Test(@"@""\b91*9*\b""", @"<Tree> <CompilationUnit> <Sequence> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>b</TextToken> </AnchorEscape> <Text> <TextToken>9</TextToken> </Text> <ZeroOrMoreQuantifier> <Text> <TextToken>1</TextToken> </Text> <AsteriskToken>*</AsteriskToken> </ZeroOrMoreQuantifier> <ZeroOrMoreQuantifier> <Text> <TextToken>9</TextToken> </Text> <AsteriskToken>*</AsteriskToken> </ZeroOrMoreQuantifier> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>b</TextToken> </AnchorEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..19)"" Text=""\b91*9*\b"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest104() { Test(@"@""\ban+\w*?\b""", @"<Tree> <CompilationUnit> <Sequence> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>b</TextToken> </AnchorEscape> <Text> <TextToken>a</TextToken> </Text> <OneOrMoreQuantifier> <Text> <TextToken>n</TextToken> </Text> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> <LazyQuantifier> <ZeroOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>w</TextToken> </CharacterClassEscape> <AsteriskToken>*</AsteriskToken> </ZeroOrMoreQuantifier> <QuestionToken>?</QuestionToken> </LazyQuantifier> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>b</TextToken> </AnchorEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..21)"" Text=""\ban+\w*?\b"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest105() { Test(@"@""\ban?\b""", @"<Tree> <CompilationUnit> <Sequence> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>b</TextToken> </AnchorEscape> <Text> <TextToken>a</TextToken> </Text> <ZeroOrOneQuantifier> <Text> <TextToken>n</TextToken> </Text> <QuestionToken>?</QuestionToken> </ZeroOrOneQuantifier> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>b</TextToken> </AnchorEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..17)"" Text=""\ban?\b"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest106() { Test(@"@""\b\d+\,\d{3}\b""", @"<Tree> <CompilationUnit> <Sequence> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>b</TextToken> </AnchorEscape> <OneOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>d</TextToken> </CharacterClassEscape> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken>,</TextToken> </SimpleEscape> <ExactNumericQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>d</TextToken> </CharacterClassEscape> <OpenBraceToken>{</OpenBraceToken> <NumberToken value=""3"">3</NumberToken> <CloseBraceToken>}</CloseBraceToken> </ExactNumericQuantifier> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>b</TextToken> </AnchorEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..24)"" Text=""\b\d+\,\d{3}\b"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest107() { Test(@"@""\b\d{2,}\b\D+""", @"<Tree> <CompilationUnit> <Sequence> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>b</TextToken> </AnchorEscape> <OpenRangeNumericQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>d</TextToken> </CharacterClassEscape> <OpenBraceToken>{</OpenBraceToken> <NumberToken value=""2"">2</NumberToken> <CommaToken>,</CommaToken> <CloseBraceToken>}</CloseBraceToken> </OpenRangeNumericQuantifier> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>b</TextToken> </AnchorEscape> <OneOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>D</TextToken> </CharacterClassEscape> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..23)"" Text=""\b\d{2,}\b\D+"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest108() { Test(@"@""(00\s){2,4}""", @"<Tree> <CompilationUnit> <Sequence> <ClosedRangeNumericQuantifier> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <Text> <TextToken>00</TextToken> </Text> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>s</TextToken> </CharacterClassEscape> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <OpenBraceToken>{</OpenBraceToken> <NumberToken value=""2"">2</NumberToken> <CommaToken>,</CommaToken> <NumberToken value=""4"">4</NumberToken> <CloseBraceToken>}</CloseBraceToken> </ClosedRangeNumericQuantifier> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..21)"" Text=""(00\s){2,4}"" /> <Capture Name=""1"" Span=""[10..16)"" Text=""(00\s)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest109() { Test(@"@""\b\w*?oo\w*?\b""", @"<Tree> <CompilationUnit> <Sequence> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>b</TextToken> </AnchorEscape> <LazyQuantifier> <ZeroOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>w</TextToken> </CharacterClassEscape> <AsteriskToken>*</AsteriskToken> </ZeroOrMoreQuantifier> <QuestionToken>?</QuestionToken> </LazyQuantifier> <Text> <TextToken>oo</TextToken> </Text> <LazyQuantifier> <ZeroOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>w</TextToken> </CharacterClassEscape> <AsteriskToken>*</AsteriskToken> </ZeroOrMoreQuantifier> <QuestionToken>?</QuestionToken> </LazyQuantifier> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>b</TextToken> </AnchorEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..24)"" Text=""\b\w*?oo\w*?\b"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest110() { Test(@"@""\b\w+?\b""", @"<Tree> <CompilationUnit> <Sequence> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>b</TextToken> </AnchorEscape> <LazyQuantifier> <OneOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>w</TextToken> </CharacterClassEscape> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> <QuestionToken>?</QuestionToken> </LazyQuantifier> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>b</TextToken> </AnchorEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..18)"" Text=""\b\w+?\b"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest111() { Test(@"@""^\s*(System.)??Console.Write(Line)??\(??""", @"<Tree> <CompilationUnit> <Sequence> <StartAnchor> <CaretToken>^</CaretToken> </StartAnchor> <ZeroOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>s</TextToken> </CharacterClassEscape> <AsteriskToken>*</AsteriskToken> </ZeroOrMoreQuantifier> <LazyQuantifier> <ZeroOrOneQuantifier> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <Text> <TextToken>System</TextToken> </Text> <Wildcard> <DotToken>.</DotToken> </Wildcard> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <QuestionToken>?</QuestionToken> </ZeroOrOneQuantifier> <QuestionToken>?</QuestionToken> </LazyQuantifier> <Text> <TextToken>Console</TextToken> </Text> <Wildcard> <DotToken>.</DotToken> </Wildcard> <Text> <TextToken>Write</TextToken> </Text> <LazyQuantifier> <ZeroOrOneQuantifier> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <Text> <TextToken>Line</TextToken> </Text> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <QuestionToken>?</QuestionToken> </ZeroOrOneQuantifier> <QuestionToken>?</QuestionToken> </LazyQuantifier> <LazyQuantifier> <ZeroOrOneQuantifier> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken>(</TextToken> </SimpleEscape> <QuestionToken>?</QuestionToken> </ZeroOrOneQuantifier> <QuestionToken>?</QuestionToken> </LazyQuantifier> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..50)"" Text=""^\s*(System.)??Console.Write(Line)??\(??"" /> <Capture Name=""1"" Span=""[14..23)"" Text=""(System.)"" /> <Capture Name=""2"" Span=""[38..44)"" Text=""(Line)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest112() { Test(@"@""(System.)??""", @"<Tree> <CompilationUnit> <Sequence> <LazyQuantifier> <ZeroOrOneQuantifier> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <Text> <TextToken>System</TextToken> </Text> <Wildcard> <DotToken>.</DotToken> </Wildcard> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <QuestionToken>?</QuestionToken> </ZeroOrOneQuantifier> <QuestionToken>?</QuestionToken> </LazyQuantifier> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..21)"" Text=""(System.)??"" /> <Capture Name=""1"" Span=""[10..19)"" Text=""(System.)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest113() { Test(@"@""\b(\w{3,}?\.){2}?\w{3,}?\b""", @"<Tree> <CompilationUnit> <Sequence> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>b</TextToken> </AnchorEscape> <LazyQuantifier> <ExactNumericQuantifier> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <LazyQuantifier> <OpenRangeNumericQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>w</TextToken> </CharacterClassEscape> <OpenBraceToken>{</OpenBraceToken> <NumberToken value=""3"">3</NumberToken> <CommaToken>,</CommaToken> <CloseBraceToken>}</CloseBraceToken> </OpenRangeNumericQuantifier> <QuestionToken>?</QuestionToken> </LazyQuantifier> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken>.</TextToken> </SimpleEscape> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <OpenBraceToken>{</OpenBraceToken> <NumberToken value=""2"">2</NumberToken> <CloseBraceToken>}</CloseBraceToken> </ExactNumericQuantifier> <QuestionToken>?</QuestionToken> </LazyQuantifier> <LazyQuantifier> <OpenRangeNumericQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>w</TextToken> </CharacterClassEscape> <OpenBraceToken>{</OpenBraceToken> <NumberToken value=""3"">3</NumberToken> <CommaToken>,</CommaToken> <CloseBraceToken>}</CloseBraceToken> </OpenRangeNumericQuantifier> <QuestionToken>?</QuestionToken> </LazyQuantifier> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>b</TextToken> </AnchorEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..36)"" Text=""\b(\w{3,}?\.){2}?\w{3,}?\b"" /> <Capture Name=""1"" Span=""[12..23)"" Text=""(\w{3,}?\.)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest114() { Test(@"@""\b[A-Z](\w*?\s*?){1,10}[.!?]""", @"<Tree> <CompilationUnit> <Sequence> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>b</TextToken> </AnchorEscape> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <CharacterClassRange> <Text> <TextToken>A</TextToken> </Text> <MinusToken>-</MinusToken> <Text> <TextToken>Z</TextToken> </Text> </CharacterClassRange> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> <ClosedRangeNumericQuantifier> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <LazyQuantifier> <ZeroOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>w</TextToken> </CharacterClassEscape> <AsteriskToken>*</AsteriskToken> </ZeroOrMoreQuantifier> <QuestionToken>?</QuestionToken> </LazyQuantifier> <LazyQuantifier> <ZeroOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>s</TextToken> </CharacterClassEscape> <AsteriskToken>*</AsteriskToken> </ZeroOrMoreQuantifier> <QuestionToken>?</QuestionToken> </LazyQuantifier> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <OpenBraceToken>{</OpenBraceToken> <NumberToken value=""1"">1</NumberToken> <CommaToken>,</CommaToken> <NumberToken value=""10"">10</NumberToken> <CloseBraceToken>}</CloseBraceToken> </ClosedRangeNumericQuantifier> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <Text> <TextToken>.!?</TextToken> </Text> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..38)"" Text=""\b[A-Z](\w*?\s*?){1,10}[.!?]"" /> <Capture Name=""1"" Span=""[17..27)"" Text=""(\w*?\s*?)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest115() { Test(@"@""b.*([0-9]{4})\b""", @"<Tree> <CompilationUnit> <Sequence> <Text> <TextToken>b</TextToken> </Text> <ZeroOrMoreQuantifier> <Wildcard> <DotToken>.</DotToken> </Wildcard> <AsteriskToken>*</AsteriskToken> </ZeroOrMoreQuantifier> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <ExactNumericQuantifier> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <CharacterClassRange> <Text> <TextToken>0</TextToken> </Text> <MinusToken>-</MinusToken> <Text> <TextToken>9</TextToken> </Text> </CharacterClassRange> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> <OpenBraceToken>{</OpenBraceToken> <NumberToken value=""4"">4</NumberToken> <CloseBraceToken>}</CloseBraceToken> </ExactNumericQuantifier> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>b</TextToken> </AnchorEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..25)"" Text=""b.*([0-9]{4})\b"" /> <Capture Name=""1"" Span=""[13..23)"" Text=""([0-9]{4})"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest116() { Test(@"@""\b.*?([0-9]{4})\b""", @"<Tree> <CompilationUnit> <Sequence> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>b</TextToken> </AnchorEscape> <LazyQuantifier> <ZeroOrMoreQuantifier> <Wildcard> <DotToken>.</DotToken> </Wildcard> <AsteriskToken>*</AsteriskToken> </ZeroOrMoreQuantifier> <QuestionToken>?</QuestionToken> </LazyQuantifier> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <ExactNumericQuantifier> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <CharacterClassRange> <Text> <TextToken>0</TextToken> </Text> <MinusToken>-</MinusToken> <Text> <TextToken>9</TextToken> </Text> </CharacterClassRange> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> <OpenBraceToken>{</OpenBraceToken> <NumberToken value=""4"">4</NumberToken> <CloseBraceToken>}</CloseBraceToken> </ExactNumericQuantifier> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>b</TextToken> </AnchorEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..27)"" Text=""\b.*?([0-9]{4})\b"" /> <Capture Name=""1"" Span=""[15..25)"" Text=""([0-9]{4})"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest117() { Test(@"@""(a?)*""", @"<Tree> <CompilationUnit> <Sequence> <ZeroOrMoreQuantifier> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <ZeroOrOneQuantifier> <Text> <TextToken>a</TextToken> </Text> <QuestionToken>?</QuestionToken> </ZeroOrOneQuantifier> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <AsteriskToken>*</AsteriskToken> </ZeroOrMoreQuantifier> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..15)"" Text=""(a?)*"" /> <Capture Name=""1"" Span=""[10..14)"" Text=""(a?)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest118() { Test(@"@""(a\1|(?(1)\1)){0,2}""", @"<Tree> <CompilationUnit> <Sequence> <ClosedRangeNumericQuantifier> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Alternation> <Sequence> <Text> <TextToken>a</TextToken> </Text> <BackreferenceEscape> <BackslashToken>\</BackslashToken> <NumberToken value=""1"">1</NumberToken> </BackreferenceEscape> </Sequence> <BarToken>|</BarToken> <Sequence> <ConditionalCaptureGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <OpenParenToken>(</OpenParenToken> <NumberToken value=""1"">1</NumberToken> <CloseParenToken>)</CloseParenToken> <Sequence> <BackreferenceEscape> <BackslashToken>\</BackslashToken> <NumberToken value=""1"">1</NumberToken> </BackreferenceEscape> </Sequence> <CloseParenToken>)</CloseParenToken> </ConditionalCaptureGrouping> </Sequence> </Alternation> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <OpenBraceToken>{</OpenBraceToken> <NumberToken value=""0"">0</NumberToken> <CommaToken>,</CommaToken> <NumberToken value=""2"">2</NumberToken> <CloseBraceToken>}</CloseBraceToken> </ClosedRangeNumericQuantifier> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..29)"" Text=""(a\1|(?(1)\1)){0,2}"" /> <Capture Name=""1"" Span=""[10..24)"" Text=""(a\1|(?(1)\1))"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest119() { Test(@"@""(a\1|(?(1)\1)){2}""", @"<Tree> <CompilationUnit> <Sequence> <ExactNumericQuantifier> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Alternation> <Sequence> <Text> <TextToken>a</TextToken> </Text> <BackreferenceEscape> <BackslashToken>\</BackslashToken> <NumberToken value=""1"">1</NumberToken> </BackreferenceEscape> </Sequence> <BarToken>|</BarToken> <Sequence> <ConditionalCaptureGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <OpenParenToken>(</OpenParenToken> <NumberToken value=""1"">1</NumberToken> <CloseParenToken>)</CloseParenToken> <Sequence> <BackreferenceEscape> <BackslashToken>\</BackslashToken> <NumberToken value=""1"">1</NumberToken> </BackreferenceEscape> </Sequence> <CloseParenToken>)</CloseParenToken> </ConditionalCaptureGrouping> </Sequence> </Alternation> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <OpenBraceToken>{</OpenBraceToken> <NumberToken value=""2"">2</NumberToken> <CloseBraceToken>}</CloseBraceToken> </ExactNumericQuantifier> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..27)"" Text=""(a\1|(?(1)\1)){2}"" /> <Capture Name=""1"" Span=""[10..24)"" Text=""(a\1|(?(1)\1))"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest120() { Test(@"@""(\w)\1""", @"<Tree> <CompilationUnit> <Sequence> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>w</TextToken> </CharacterClassEscape> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <BackreferenceEscape> <BackslashToken>\</BackslashToken> <NumberToken value=""1"">1</NumberToken> </BackreferenceEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..16)"" Text=""(\w)\1"" /> <Capture Name=""1"" Span=""[10..14)"" Text=""(\w)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest121() { Test(@"@""(?<char>\w)\k<char>""", @"<Tree> <CompilationUnit> <Sequence> <CaptureGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <CaptureNameToken value=""char"">char</CaptureNameToken> <GreaterThanToken>&gt;</GreaterThanToken> <Sequence> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>w</TextToken> </CharacterClassEscape> </Sequence> <CloseParenToken>)</CloseParenToken> </CaptureGrouping> <KCaptureEscape> <BackslashToken>\</BackslashToken> <TextToken>k</TextToken> <LessThanToken>&lt;</LessThanToken> <CaptureNameToken value=""char"">char</CaptureNameToken> <GreaterThanToken>&gt;</GreaterThanToken> </KCaptureEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..29)"" Text=""(?&lt;char&gt;\w)\k&lt;char&gt;"" /> <Capture Name=""1"" Span=""[10..21)"" Text=""(?&lt;char&gt;\w)"" /> <Capture Name=""char"" Span=""[10..21)"" Text=""(?&lt;char&gt;\w)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest122() { Test(@"@""(?<2>\w)\k<2>""", @"<Tree> <CompilationUnit> <Sequence> <CaptureGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <NumberToken value=""2"">2</NumberToken> <GreaterThanToken>&gt;</GreaterThanToken> <Sequence> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>w</TextToken> </CharacterClassEscape> </Sequence> <CloseParenToken>)</CloseParenToken> </CaptureGrouping> <KCaptureEscape> <BackslashToken>\</BackslashToken> <TextToken>k</TextToken> <LessThanToken>&lt;</LessThanToken> <NumberToken value=""2"">2</NumberToken> <GreaterThanToken>&gt;</GreaterThanToken> </KCaptureEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..23)"" Text=""(?&lt;2&gt;\w)\k&lt;2&gt;"" /> <Capture Name=""2"" Span=""[10..18)"" Text=""(?&lt;2&gt;\w)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest123() { Test(@"@""(?<1>a)(?<1>\1b)*""", @"<Tree> <CompilationUnit> <Sequence> <CaptureGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <NumberToken value=""1"">1</NumberToken> <GreaterThanToken>&gt;</GreaterThanToken> <Sequence> <Text> <TextToken>a</TextToken> </Text> </Sequence> <CloseParenToken>)</CloseParenToken> </CaptureGrouping> <ZeroOrMoreQuantifier> <CaptureGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <NumberToken value=""1"">1</NumberToken> <GreaterThanToken>&gt;</GreaterThanToken> <Sequence> <BackreferenceEscape> <BackslashToken>\</BackslashToken> <NumberToken value=""1"">1</NumberToken> </BackreferenceEscape> <Text> <TextToken>b</TextToken> </Text> </Sequence> <CloseParenToken>)</CloseParenToken> </CaptureGrouping> <AsteriskToken>*</AsteriskToken> </ZeroOrMoreQuantifier> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..27)"" Text=""(?&lt;1&gt;a)(?&lt;1&gt;\1b)*"" /> <Capture Name=""1"" Span=""[10..17)"" Text=""(?&lt;1&gt;a)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest124() { Test(@"@""\b(\p{Lu}{2})(\d{2})?(\p{Lu}{2})\b""", @"<Tree> <CompilationUnit> <Sequence> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>b</TextToken> </AnchorEscape> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <ExactNumericQuantifier> <CategoryEscape> <BackslashToken>\</BackslashToken> <TextToken>p</TextToken> <OpenBraceToken>{</OpenBraceToken> <EscapeCategoryToken>Lu</EscapeCategoryToken> <CloseBraceToken>}</CloseBraceToken> </CategoryEscape> <OpenBraceToken>{</OpenBraceToken> <NumberToken value=""2"">2</NumberToken> <CloseBraceToken>}</CloseBraceToken> </ExactNumericQuantifier> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <ZeroOrOneQuantifier> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <ExactNumericQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>d</TextToken> </CharacterClassEscape> <OpenBraceToken>{</OpenBraceToken> <NumberToken value=""2"">2</NumberToken> <CloseBraceToken>}</CloseBraceToken> </ExactNumericQuantifier> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <QuestionToken>?</QuestionToken> </ZeroOrOneQuantifier> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <ExactNumericQuantifier> <CategoryEscape> <BackslashToken>\</BackslashToken> <TextToken>p</TextToken> <OpenBraceToken>{</OpenBraceToken> <EscapeCategoryToken>Lu</EscapeCategoryToken> <CloseBraceToken>}</CloseBraceToken> </CategoryEscape> <OpenBraceToken>{</OpenBraceToken> <NumberToken value=""2"">2</NumberToken> <CloseBraceToken>}</CloseBraceToken> </ExactNumericQuantifier> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>b</TextToken> </AnchorEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..44)"" Text=""\b(\p{Lu}{2})(\d{2})?(\p{Lu}{2})\b"" /> <Capture Name=""1"" Span=""[12..23)"" Text=""(\p{Lu}{2})"" /> <Capture Name=""2"" Span=""[23..30)"" Text=""(\d{2})"" /> <Capture Name=""3"" Span=""[31..42)"" Text=""(\p{Lu}{2})"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest125() { Test(@"@""\bgr[ae]y\b""", @"<Tree> <CompilationUnit> <Sequence> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>b</TextToken> </AnchorEscape> <Text> <TextToken>gr</TextToken> </Text> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <Text> <TextToken>ae</TextToken> </Text> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> <Text> <TextToken>y</TextToken> </Text> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>b</TextToken> </AnchorEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..21)"" Text=""\bgr[ae]y\b"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest126() { Test(@"@""\b((?# case sensitive comparison)D\w+)\s(?ixn)((?#case insensitive comparison)d\w+)\b""", @"<Tree> <CompilationUnit> <Sequence> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>b</TextToken> </AnchorEscape> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <Text> <TextToken> <Trivia> <CommentTrivia>(?# case sensitive comparison)</CommentTrivia> </Trivia>D</TextToken> </Text> <OneOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>w</TextToken> </CharacterClassEscape> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>s</TextToken> </CharacterClassEscape> <SimpleOptionsGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <OptionsToken>ixn</OptionsToken> <CloseParenToken>)</CloseParenToken> </SimpleOptionsGrouping> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <Text> <TextToken> <Trivia> <CommentTrivia>(?#case insensitive comparison)</CommentTrivia> </Trivia>d</TextToken> </Text> <OneOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>w</TextToken> </CharacterClassEscape> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>b</TextToken> </AnchorEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..95)"" Text=""\b((?# case sensitive comparison)D\w+)\s(?ixn)((?#case insensitive comparison)d\w+)\b"" /> <Capture Name=""1"" Span=""[12..48)"" Text=""((?# case sensitive comparison)D\w+)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void ReferenceTest127() { Test(@"@""\{\d+(,-*\d+)*(\:\w{1,4}?)*\}(?x) # Looks for a composite format item.""", @"<Tree> <CompilationUnit> <Sequence> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken>{</TextToken> </SimpleEscape> <OneOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>d</TextToken> </CharacterClassEscape> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> <ZeroOrMoreQuantifier> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <Text> <TextToken>,</TextToken> </Text> <ZeroOrMoreQuantifier> <Text> <TextToken>-</TextToken> </Text> <AsteriskToken>*</AsteriskToken> </ZeroOrMoreQuantifier> <OneOrMoreQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>d</TextToken> </CharacterClassEscape> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <AsteriskToken>*</AsteriskToken> </ZeroOrMoreQuantifier> <ZeroOrMoreQuantifier> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken>:</TextToken> </SimpleEscape> <LazyQuantifier> <ClosedRangeNumericQuantifier> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>w</TextToken> </CharacterClassEscape> <OpenBraceToken>{</OpenBraceToken> <NumberToken value=""1"">1</NumberToken> <CommaToken>,</CommaToken> <NumberToken value=""4"">4</NumberToken> <CloseBraceToken>}</CloseBraceToken> </ClosedRangeNumericQuantifier> <QuestionToken>?</QuestionToken> </LazyQuantifier> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <AsteriskToken>*</AsteriskToken> </ZeroOrMoreQuantifier> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken>}</TextToken> </SimpleEscape> <SimpleOptionsGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <OptionsToken>x</OptionsToken> <CloseParenToken>)</CloseParenToken> </SimpleOptionsGrouping> </Sequence> <EndOfFile> <Trivia> <WhitespaceTrivia> </WhitespaceTrivia> <CommentTrivia># Looks for a composite format item.</CommentTrivia> </Trivia> </EndOfFile> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..80)"" Text=""\{\d+(,-*\d+)*(\:\w{1,4}?)*\}(?x) # Looks for a composite format item."" /> <Capture Name=""1"" Span=""[15..23)"" Text=""(,-*\d+)"" /> <Capture Name=""2"" Span=""[24..36)"" Text=""(\:\w{1,4}?)"" /> </Captures> </Tree>", RegexOptions.None); } } }
-1
dotnet/roslyn
55,430
Fix LSP semantic tokens algorithm
This PR primarily accomplishes two tasks: 1) Overhauls the existing LSP semantic tokens edits processing algorithm to align with [Razor's](https://github.com/dotnet/aspnetcore-tooling/blob/main/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/Semantic/Services/SemanticTokensEditsDiffer.cs) (shoutout to Ryan and the rest of the Razor team for writing the original 😄). The main change here is going from calculating edits per token (i.e. five ints) to per int. The updated algorithm is much more efficient than our previous algorithm, and returns less edits back to the LSP client. 2) The interpretation of Roslyn's LongestCommonSubstring algorithm, which we use to calculate raw edits, was missing a critical piece. Namely, for insertions, we need to keep track of _where_ we should be inserting into the original token set. We don't keep track of this in the existing implementation, resulting in bugs such as #54671. Resolves #54671
allisonchou
2021-08-05T06:06:43Z
2021-08-06T23:44:44Z
b9200d03a76c74d404040d44b9bbe12b1d0a8ef2
f300a818940ea1acef66c946cfa83756729d5e59
Fix LSP semantic tokens algorithm. This PR primarily accomplishes two tasks: 1) Overhauls the existing LSP semantic tokens edits processing algorithm to align with [Razor's](https://github.com/dotnet/aspnetcore-tooling/blob/main/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/Semantic/Services/SemanticTokensEditsDiffer.cs) (shoutout to Ryan and the rest of the Razor team for writing the original 😄). The main change here is going from calculating edits per token (i.e. five ints) to per int. The updated algorithm is much more efficient than our previous algorithm, and returns less edits back to the LSP client. 2) The interpretation of Roslyn's LongestCommonSubstring algorithm, which we use to calculate raw edits, was missing a critical piece. Namely, for insertions, we need to keep track of _where_ we should be inserting into the original token set. We don't keep track of this in the existing implementation, resulting in bugs such as #54671. Resolves #54671
./src/Analyzers/CSharp/Analyzers/ConvertSwitchStatementToExpression/ConvertSwitchStatementToExpressionHelpers.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET 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.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; namespace Microsoft.CodeAnalysis.CSharp.ConvertSwitchStatementToExpression { internal static class ConvertSwitchStatementToExpressionHelpers { public static bool IsDefaultSwitchLabel(SwitchLabelSyntax node) { // default: if (node.IsKind(SyntaxKind.DefaultSwitchLabel)) { return true; } if (node.IsKind(SyntaxKind.CasePatternSwitchLabel, out CasePatternSwitchLabelSyntax @case)) { // case _: if (@case.Pattern.IsKind(SyntaxKind.DiscardPattern)) { return @case.WhenClause == null; } // case var _: // case var x: if (@case.Pattern.IsKind(SyntaxKind.VarPattern, out VarPatternSyntax varPattern) && varPattern.Designation.IsKind(SyntaxKind.DiscardDesignation, SyntaxKind.SingleVariableDesignation)) { return @case.WhenClause == null; } } return false; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; namespace Microsoft.CodeAnalysis.CSharp.ConvertSwitchStatementToExpression { internal static class ConvertSwitchStatementToExpressionHelpers { public static bool IsDefaultSwitchLabel(SwitchLabelSyntax node) { // default: if (node.IsKind(SyntaxKind.DefaultSwitchLabel)) { return true; } if (node.IsKind(SyntaxKind.CasePatternSwitchLabel, out CasePatternSwitchLabelSyntax @case)) { // case _: if (@case.Pattern.IsKind(SyntaxKind.DiscardPattern)) { return @case.WhenClause == null; } // case var _: // case var x: if (@case.Pattern.IsKind(SyntaxKind.VarPattern, out VarPatternSyntax varPattern) && varPattern.Designation.IsKind(SyntaxKind.DiscardDesignation, SyntaxKind.SingleVariableDesignation)) { return @case.WhenClause == null; } } return false; } } }
-1
dotnet/roslyn
55,430
Fix LSP semantic tokens algorithm
This PR primarily accomplishes two tasks: 1) Overhauls the existing LSP semantic tokens edits processing algorithm to align with [Razor's](https://github.com/dotnet/aspnetcore-tooling/blob/main/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/Semantic/Services/SemanticTokensEditsDiffer.cs) (shoutout to Ryan and the rest of the Razor team for writing the original 😄). The main change here is going from calculating edits per token (i.e. five ints) to per int. The updated algorithm is much more efficient than our previous algorithm, and returns less edits back to the LSP client. 2) The interpretation of Roslyn's LongestCommonSubstring algorithm, which we use to calculate raw edits, was missing a critical piece. Namely, for insertions, we need to keep track of _where_ we should be inserting into the original token set. We don't keep track of this in the existing implementation, resulting in bugs such as #54671. Resolves #54671
allisonchou
2021-08-05T06:06:43Z
2021-08-06T23:44:44Z
b9200d03a76c74d404040d44b9bbe12b1d0a8ef2
f300a818940ea1acef66c946cfa83756729d5e59
Fix LSP semantic tokens algorithm. This PR primarily accomplishes two tasks: 1) Overhauls the existing LSP semantic tokens edits processing algorithm to align with [Razor's](https://github.com/dotnet/aspnetcore-tooling/blob/main/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/Semantic/Services/SemanticTokensEditsDiffer.cs) (shoutout to Ryan and the rest of the Razor team for writing the original 😄). The main change here is going from calculating edits per token (i.e. five ints) to per int. The updated algorithm is much more efficient than our previous algorithm, and returns less edits back to the LSP client. 2) The interpretation of Roslyn's LongestCommonSubstring algorithm, which we use to calculate raw edits, was missing a critical piece. Namely, for insertions, we need to keep track of _where_ we should be inserting into the original token set. We don't keep track of this in the existing implementation, resulting in bugs such as #54671. Resolves #54671
./src/Compilers/CSharp/Portable/Symbols/Tuples/TupleErrorFieldSymbol.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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 Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Symbols { /// <summary> /// Represents a field of a tuple type (such as (int, byte).Item1) /// that doesn't have a corresponding backing field within the tuple underlying type. /// Created in response to an error condition. /// </summary> internal sealed class TupleErrorFieldSymbol : SynthesizedFieldSymbolBase { private readonly TypeWithAnnotations _type; /// <summary> /// If this field represents a tuple element with index X /// 2X if this field represents Default-named element /// 2X + 1 if this field represents Friendly-named element /// Otherwise, (-1 - [index in members array]); /// </summary> private readonly int _tupleElementIndex; private readonly ImmutableArray<Location> _locations; private readonly DiagnosticInfo _useSiteDiagnosticInfo; private readonly TupleErrorFieldSymbol _correspondingDefaultField; // default tuple elements like Item1 or Item20 could be provided by the user or // otherwise implicitly declared by compiler private readonly bool _isImplicitlyDeclared; public TupleErrorFieldSymbol( NamedTypeSymbol container, string name, int tupleElementIndex, Location location, TypeWithAnnotations type, DiagnosticInfo useSiteDiagnosticInfo, bool isImplicitlyDeclared, TupleErrorFieldSymbol correspondingDefaultFieldOpt) : base(container, name, isPublic: true, isReadOnly: false, isStatic: false) { Debug.Assert(name != null); _type = type; _locations = location == null ? ImmutableArray<Location>.Empty : ImmutableArray.Create(location); _useSiteDiagnosticInfo = useSiteDiagnosticInfo; _tupleElementIndex = (object)correspondingDefaultFieldOpt == null ? tupleElementIndex << 1 : (tupleElementIndex << 1) + 1; _isImplicitlyDeclared = isImplicitlyDeclared; Debug.Assert((correspondingDefaultFieldOpt == null) == this.IsDefaultTupleElement); Debug.Assert(correspondingDefaultFieldOpt == null || correspondingDefaultFieldOpt.IsDefaultTupleElement); _correspondingDefaultField = correspondingDefaultFieldOpt ?? this; } /// <summary> /// If this is a field representing a tuple element, /// returns the index of the element (zero-based). /// Otherwise returns -1 /// </summary> public override int TupleElementIndex { get { if (_tupleElementIndex < 0) { return -1; } return _tupleElementIndex >> 1; } } public override bool IsDefaultTupleElement { get { // not negative and even return (_tupleElementIndex & ((1 << 31) | 1)) == 0; } } public override bool IsExplicitlyNamedTupleElement { get { return _tupleElementIndex >= 0 && !_isImplicitlyDeclared; } } public override FieldSymbol TupleUnderlyingField { get { // Failed to find one return null; } } public override FieldSymbol OriginalDefinition { get { return this; } } public override ImmutableArray<Location> Locations { get { return _locations; } } public override ImmutableArray<SyntaxReference> DeclaringSyntaxReferences { get { return _isImplicitlyDeclared ? ImmutableArray<SyntaxReference>.Empty : GetDeclaringSyntaxReferenceHelper<CSharpSyntaxNode>(_locations); } } public override bool IsImplicitlyDeclared { get { return _isImplicitlyDeclared; } } public override FieldSymbol CorrespondingTupleField { get { return _correspondingDefaultField; } } internal override bool SuppressDynamicAttribute { get { return true; } } internal override TypeWithAnnotations GetFieldType(ConsList<FieldSymbol> fieldsBeingBound) { return _type; } internal override UseSiteInfo<AssemblySymbol> GetUseSiteInfo() { return new UseSiteInfo<AssemblySymbol>(_useSiteDiagnosticInfo); } public sealed override int GetHashCode() { return Hash.Combine(ContainingType.GetHashCode(), _tupleElementIndex.GetHashCode()); } public override bool Equals(Symbol obj, TypeCompareKind compareKind) { return Equals(obj as TupleErrorFieldSymbol, compareKind); } public bool Equals(TupleErrorFieldSymbol other, TypeCompareKind compareKind) { if ((object)other == this) { return true; } return (object)other != null && _tupleElementIndex == other._tupleElementIndex && TypeSymbol.Equals(ContainingType, other.ContainingType, compareKind); } internal override FieldSymbol AsMember(NamedTypeSymbol newOwner) { Debug.Assert(newOwner.IsTupleType && newOwner.TupleElementTypesWithAnnotations.Length > TupleElementIndex); if (ReferenceEquals(newOwner, ContainingType)) { return this; } TupleErrorFieldSymbol newCorrespondingField = null; if (!ReferenceEquals(_correspondingDefaultField, this)) { newCorrespondingField = (TupleErrorFieldSymbol)_correspondingDefaultField.AsMember(newOwner); } return new TupleErrorFieldSymbol( newOwner, Name, TupleElementIndex, _locations.IsEmpty ? null : Locations[0], newOwner.TupleElementTypesWithAnnotations[TupleElementIndex], _useSiteDiagnosticInfo, _isImplicitlyDeclared, newCorrespondingField); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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 Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Symbols { /// <summary> /// Represents a field of a tuple type (such as (int, byte).Item1) /// that doesn't have a corresponding backing field within the tuple underlying type. /// Created in response to an error condition. /// </summary> internal sealed class TupleErrorFieldSymbol : SynthesizedFieldSymbolBase { private readonly TypeWithAnnotations _type; /// <summary> /// If this field represents a tuple element with index X /// 2X if this field represents Default-named element /// 2X + 1 if this field represents Friendly-named element /// Otherwise, (-1 - [index in members array]); /// </summary> private readonly int _tupleElementIndex; private readonly ImmutableArray<Location> _locations; private readonly DiagnosticInfo _useSiteDiagnosticInfo; private readonly TupleErrorFieldSymbol _correspondingDefaultField; // default tuple elements like Item1 or Item20 could be provided by the user or // otherwise implicitly declared by compiler private readonly bool _isImplicitlyDeclared; public TupleErrorFieldSymbol( NamedTypeSymbol container, string name, int tupleElementIndex, Location location, TypeWithAnnotations type, DiagnosticInfo useSiteDiagnosticInfo, bool isImplicitlyDeclared, TupleErrorFieldSymbol correspondingDefaultFieldOpt) : base(container, name, isPublic: true, isReadOnly: false, isStatic: false) { Debug.Assert(name != null); _type = type; _locations = location == null ? ImmutableArray<Location>.Empty : ImmutableArray.Create(location); _useSiteDiagnosticInfo = useSiteDiagnosticInfo; _tupleElementIndex = (object)correspondingDefaultFieldOpt == null ? tupleElementIndex << 1 : (tupleElementIndex << 1) + 1; _isImplicitlyDeclared = isImplicitlyDeclared; Debug.Assert((correspondingDefaultFieldOpt == null) == this.IsDefaultTupleElement); Debug.Assert(correspondingDefaultFieldOpt == null || correspondingDefaultFieldOpt.IsDefaultTupleElement); _correspondingDefaultField = correspondingDefaultFieldOpt ?? this; } /// <summary> /// If this is a field representing a tuple element, /// returns the index of the element (zero-based). /// Otherwise returns -1 /// </summary> public override int TupleElementIndex { get { if (_tupleElementIndex < 0) { return -1; } return _tupleElementIndex >> 1; } } public override bool IsDefaultTupleElement { get { // not negative and even return (_tupleElementIndex & ((1 << 31) | 1)) == 0; } } public override bool IsExplicitlyNamedTupleElement { get { return _tupleElementIndex >= 0 && !_isImplicitlyDeclared; } } public override FieldSymbol TupleUnderlyingField { get { // Failed to find one return null; } } public override FieldSymbol OriginalDefinition { get { return this; } } public override ImmutableArray<Location> Locations { get { return _locations; } } public override ImmutableArray<SyntaxReference> DeclaringSyntaxReferences { get { return _isImplicitlyDeclared ? ImmutableArray<SyntaxReference>.Empty : GetDeclaringSyntaxReferenceHelper<CSharpSyntaxNode>(_locations); } } public override bool IsImplicitlyDeclared { get { return _isImplicitlyDeclared; } } public override FieldSymbol CorrespondingTupleField { get { return _correspondingDefaultField; } } internal override bool SuppressDynamicAttribute { get { return true; } } internal override TypeWithAnnotations GetFieldType(ConsList<FieldSymbol> fieldsBeingBound) { return _type; } internal override UseSiteInfo<AssemblySymbol> GetUseSiteInfo() { return new UseSiteInfo<AssemblySymbol>(_useSiteDiagnosticInfo); } public sealed override int GetHashCode() { return Hash.Combine(ContainingType.GetHashCode(), _tupleElementIndex.GetHashCode()); } public override bool Equals(Symbol obj, TypeCompareKind compareKind) { return Equals(obj as TupleErrorFieldSymbol, compareKind); } public bool Equals(TupleErrorFieldSymbol other, TypeCompareKind compareKind) { if ((object)other == this) { return true; } return (object)other != null && _tupleElementIndex == other._tupleElementIndex && TypeSymbol.Equals(ContainingType, other.ContainingType, compareKind); } internal override FieldSymbol AsMember(NamedTypeSymbol newOwner) { Debug.Assert(newOwner.IsTupleType && newOwner.TupleElementTypesWithAnnotations.Length > TupleElementIndex); if (ReferenceEquals(newOwner, ContainingType)) { return this; } TupleErrorFieldSymbol newCorrespondingField = null; if (!ReferenceEquals(_correspondingDefaultField, this)) { newCorrespondingField = (TupleErrorFieldSymbol)_correspondingDefaultField.AsMember(newOwner); } return new TupleErrorFieldSymbol( newOwner, Name, TupleElementIndex, _locations.IsEmpty ? null : Locations[0], newOwner.TupleElementTypesWithAnnotations[TupleElementIndex], _useSiteDiagnosticInfo, _isImplicitlyDeclared, newCorrespondingField); } } }
-1
dotnet/roslyn
55,430
Fix LSP semantic tokens algorithm
This PR primarily accomplishes two tasks: 1) Overhauls the existing LSP semantic tokens edits processing algorithm to align with [Razor's](https://github.com/dotnet/aspnetcore-tooling/blob/main/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/Semantic/Services/SemanticTokensEditsDiffer.cs) (shoutout to Ryan and the rest of the Razor team for writing the original 😄). The main change here is going from calculating edits per token (i.e. five ints) to per int. The updated algorithm is much more efficient than our previous algorithm, and returns less edits back to the LSP client. 2) The interpretation of Roslyn's LongestCommonSubstring algorithm, which we use to calculate raw edits, was missing a critical piece. Namely, for insertions, we need to keep track of _where_ we should be inserting into the original token set. We don't keep track of this in the existing implementation, resulting in bugs such as #54671. Resolves #54671
allisonchou
2021-08-05T06:06:43Z
2021-08-06T23:44:44Z
b9200d03a76c74d404040d44b9bbe12b1d0a8ef2
f300a818940ea1acef66c946cfa83756729d5e59
Fix LSP semantic tokens algorithm. This PR primarily accomplishes two tasks: 1) Overhauls the existing LSP semantic tokens edits processing algorithm to align with [Razor's](https://github.com/dotnet/aspnetcore-tooling/blob/main/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/Semantic/Services/SemanticTokensEditsDiffer.cs) (shoutout to Ryan and the rest of the Razor team for writing the original 😄). The main change here is going from calculating edits per token (i.e. five ints) to per int. The updated algorithm is much more efficient than our previous algorithm, and returns less edits back to the LSP client. 2) The interpretation of Roslyn's LongestCommonSubstring algorithm, which we use to calculate raw edits, was missing a critical piece. Namely, for insertions, we need to keep track of _where_ we should be inserting into the original token set. We don't keep track of this in the existing implementation, resulting in bugs such as #54671. Resolves #54671
./src/Workspaces/Core/Portable/Simplification/AbstractSimplificationService.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.Internal.Log; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Shared.Collections; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; #if DEBUG using Microsoft.CodeAnalysis.Shared.Extensions; #endif namespace Microsoft.CodeAnalysis.Simplification { internal abstract class AbstractSimplificationService<TExpressionSyntax, TStatementSyntax, TCrefSyntax> : ISimplificationService where TExpressionSyntax : SyntaxNode where TStatementSyntax : SyntaxNode where TCrefSyntax : SyntaxNode { private ImmutableArray<AbstractReducer> _reducers; protected AbstractSimplificationService(ImmutableArray<AbstractReducer> reducers) => _reducers = reducers; protected abstract ImmutableArray<NodeOrTokenToReduce> GetNodesAndTokensToReduce(SyntaxNode root, Func<SyntaxNodeOrToken, bool> isNodeOrTokenOutsideSimplifySpans); protected abstract SemanticModel GetSpeculativeSemanticModel(ref SyntaxNode nodeToSpeculate, SemanticModel originalSemanticModel, SyntaxNode originalNode); protected abstract bool CanNodeBeSimplifiedWithoutSpeculation(SyntaxNode node); protected virtual SyntaxNode TransformReducedNode(SyntaxNode reducedNode, SyntaxNode originalNode) => reducedNode; public abstract SyntaxNode Expand(SyntaxNode node, SemanticModel semanticModel, SyntaxAnnotation annotationForReplacedAliasIdentifier, Func<SyntaxNode, bool> expandInsideNode, bool expandParameter, CancellationToken cancellationToken); public abstract SyntaxToken Expand(SyntaxToken token, SemanticModel semanticModel, Func<SyntaxNode, bool> expandInsideNode, CancellationToken cancellationToken); public async Task<Document> ReduceAsync( Document document, ImmutableArray<TextSpan> spans, OptionSet optionSet = null, ImmutableArray<AbstractReducer> reducers = default, CancellationToken cancellationToken = default) { using (Logger.LogBlock(FunctionId.Simplifier_ReduceAsync, cancellationToken)) { var spanList = spans.NullToEmpty(); // we have no span if (!spanList.Any()) { return document; } optionSet ??= await document.GetOptionsAsync(cancellationToken).ConfigureAwait(false); var semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false); // Chaining of the Speculative SemanticModel (i.e. Generating a speculative SemanticModel from an existing Speculative SemanticModel) is not supported // Hence make sure we always start working off of the actual SemanticModel instead of a speculative SemanticModel. Debug.Assert(!semanticModel.IsSpeculativeSemanticModel); var root = await semanticModel.SyntaxTree.GetRootAsync(cancellationToken).ConfigureAwait(false); #if DEBUG var originalDocHasErrors = await document.HasAnyErrorsAsync(cancellationToken).ConfigureAwait(false); #endif var reduced = await this.ReduceCoreAsync(document, spanList, optionSet, reducers, cancellationToken).ConfigureAwait(false); if (reduced != document) { #if DEBUG if (!originalDocHasErrors) { await reduced.VerifyNoErrorsAsync("Error introduced by Simplification Service", cancellationToken).ConfigureAwait(false); } #endif } return reduced; } } private async Task<Document> ReduceCoreAsync( Document document, ImmutableArray<TextSpan> spans, OptionSet optionSet, ImmutableArray<AbstractReducer> reducers, CancellationToken cancellationToken) { // Create a simple interval tree for simplification spans. var spansTree = new SimpleIntervalTree<TextSpan, TextSpanIntervalIntrospector>(new TextSpanIntervalIntrospector(), spans); bool isNodeOrTokenOutsideSimplifySpans(SyntaxNodeOrToken nodeOrToken) => !spansTree.HasIntervalThatOverlapsWith(nodeOrToken.FullSpan.Start, nodeOrToken.FullSpan.Length); var semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false); var root = await semanticModel.SyntaxTree.GetRootAsync(cancellationToken).ConfigureAwait(false); // prep namespace imports marked for simplification var removeIfUnusedAnnotation = new SyntaxAnnotation(); var originalRoot = root; root = PrepareNamespaceImportsForRemovalIfUnused(document, root, removeIfUnusedAnnotation, isNodeOrTokenOutsideSimplifySpans); var hasImportsToSimplify = root != originalRoot; if (hasImportsToSimplify) { document = document.WithSyntaxRoot(root); semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false); root = await semanticModel.SyntaxTree.GetRootAsync(cancellationToken).ConfigureAwait(false); } // Get the list of syntax nodes and tokens that need to be reduced. var nodesAndTokensToReduce = this.GetNodesAndTokensToReduce(root, isNodeOrTokenOutsideSimplifySpans); if (nodesAndTokensToReduce.Any()) { if (reducers.IsDefault) { reducers = _reducers; } // Take out any reducers that don't even apply with the current // set of users options. i.e. no point running 'reduce to var' // if the user doesn't have the 'var' preference set. reducers = reducers.WhereAsArray(r => r.IsApplicable(optionSet)); var reducedNodesMap = new ConcurrentDictionary<SyntaxNode, SyntaxNode>(); var reducedTokensMap = new ConcurrentDictionary<SyntaxToken, SyntaxToken>(); // Reduce all the nodesAndTokensToReduce using the given reducers/rewriters and // store the reduced nodes and/or tokens in the reduced nodes/tokens maps. // Note that this method doesn't update the original syntax tree. await this.ReduceAsync(document, root, nodesAndTokensToReduce, reducers, optionSet, semanticModel, reducedNodesMap, reducedTokensMap, cancellationToken).ConfigureAwait(false); if (reducedNodesMap.Any() || reducedTokensMap.Any()) { // Update the syntax tree with reduced nodes/tokens. root = root.ReplaceSyntax( nodes: reducedNodesMap.Keys, computeReplacementNode: (o, n) => TransformReducedNode(reducedNodesMap[o], n), tokens: reducedTokensMap.Keys, computeReplacementToken: (o, n) => reducedTokensMap[o], trivia: SpecializedCollections.EmptyEnumerable<SyntaxTrivia>(), computeReplacementTrivia: null); document = document.WithSyntaxRoot(root); } } if (hasImportsToSimplify) { // remove any unused namespace imports that were marked for simplification document = await this.RemoveUnusedNamespaceImportsAsync(document, removeIfUnusedAnnotation, cancellationToken).ConfigureAwait(false); } return document; } private Task ReduceAsync( Document document, SyntaxNode root, ImmutableArray<NodeOrTokenToReduce> nodesAndTokensToReduce, ImmutableArray<AbstractReducer> reducers, OptionSet optionSet, SemanticModel semanticModel, ConcurrentDictionary<SyntaxNode, SyntaxNode> reducedNodesMap, ConcurrentDictionary<SyntaxToken, SyntaxToken> reducedTokensMap, CancellationToken cancellationToken) { Contract.ThrowIfFalse(nodesAndTokensToReduce.Any()); // Reduce each node or token in the given list by running it through each reducer. var simplifyTasks = new Task[nodesAndTokensToReduce.Length]; for (var i = 0; i < nodesAndTokensToReduce.Length; i++) { var nodeOrTokenToReduce = nodesAndTokensToReduce[i]; simplifyTasks[i] = Task.Run(async () => { var nodeOrToken = nodeOrTokenToReduce.OriginalNodeOrToken; var simplifyAllDescendants = nodeOrTokenToReduce.SimplifyAllDescendants; var semanticModelForReduce = semanticModel; var currentNodeOrToken = nodeOrTokenToReduce.NodeOrToken; var isNode = nodeOrToken.IsNode; foreach (var reducer in reducers) { cancellationToken.ThrowIfCancellationRequested(); using var rewriter = reducer.GetOrCreateRewriter(); rewriter.Initialize(document.Project.ParseOptions, optionSet, cancellationToken); do { if (currentNodeOrToken.SyntaxTree != semanticModelForReduce.SyntaxTree) { // currentNodeOrToken was simplified either by a previous reducer or // a previous iteration of the current reducer. // Create a speculative semantic model for the simplified node for semantic queries. // Certain node kinds (expressions/statements) require non-null parent nodes during simplification. // However, the reduced nodes haven't been parented yet, so do the required parenting using the original node's parent. if (currentNodeOrToken.Parent == null && nodeOrToken.Parent != null && (currentNodeOrToken.IsToken || currentNodeOrToken.AsNode() is TExpressionSyntax || currentNodeOrToken.AsNode() is TStatementSyntax || currentNodeOrToken.AsNode() is TCrefSyntax)) { var annotation = new SyntaxAnnotation(); currentNodeOrToken = currentNodeOrToken.WithAdditionalAnnotations(annotation); var replacedParent = isNode ? nodeOrToken.Parent.ReplaceNode(nodeOrToken.AsNode(), currentNodeOrToken.AsNode()) : nodeOrToken.Parent.ReplaceToken(nodeOrToken.AsToken(), currentNodeOrToken.AsToken()); currentNodeOrToken = replacedParent .ChildNodesAndTokens() .Single(c => c.HasAnnotation(annotation)); } if (isNode) { var currentNode = currentNodeOrToken.AsNode(); if (this.CanNodeBeSimplifiedWithoutSpeculation(nodeOrToken.AsNode())) { // Since this node cannot be speculated, we are replacing the Document with the changes and get a new SemanticModel var marker = new SyntaxAnnotation(); var newRoot = root.ReplaceNode(nodeOrToken.AsNode(), currentNode.WithAdditionalAnnotations(marker)); var newDocument = document.WithSyntaxRoot(newRoot); semanticModelForReduce = await newDocument.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false); newRoot = await semanticModelForReduce.SyntaxTree.GetRootAsync(cancellationToken).ConfigureAwait(false); currentNodeOrToken = newRoot.DescendantNodes().Single(c => c.HasAnnotation(marker)); } else { // Create speculative semantic model for simplified node. semanticModelForReduce = GetSpeculativeSemanticModel(ref currentNode, semanticModel, nodeOrToken.AsNode()); currentNodeOrToken = currentNode; } } } // Reduce the current node or token. currentNodeOrToken = rewriter.VisitNodeOrToken(currentNodeOrToken, semanticModelForReduce, simplifyAllDescendants); } while (rewriter.HasMoreWork); } // If nodeOrToken was simplified, add it to the appropriate dictionary of replaced nodes/tokens. if (currentNodeOrToken != nodeOrToken) { if (isNode) { reducedNodesMap[nodeOrToken.AsNode()] = currentNodeOrToken.AsNode(); } else { reducedTokensMap[nodeOrToken.AsToken()] = currentNodeOrToken.AsToken(); } } }, cancellationToken); } return Task.WhenAll(simplifyTasks); } // find any namespace imports / using directives marked for simplification in the specified spans // and add removeIfUnused annotation private static SyntaxNode PrepareNamespaceImportsForRemovalIfUnused( Document document, SyntaxNode root, SyntaxAnnotation removeIfUnusedAnnotation, Func<SyntaxNodeOrToken, bool> isNodeOrTokenOutsideSimplifySpan) { var gen = SyntaxGenerator.GetGenerator(document); var importsToSimplify = root.DescendantNodes().Where(n => !isNodeOrTokenOutsideSimplifySpan(n) && gen.GetDeclarationKind(n) == DeclarationKind.NamespaceImport && n.HasAnnotation(Simplifier.Annotation)); return root.ReplaceNodes(importsToSimplify, (o, r) => r.WithAdditionalAnnotations(removeIfUnusedAnnotation)); } private async Task<Document> RemoveUnusedNamespaceImportsAsync( Document document, SyntaxAnnotation removeIfUnusedAnnotation, CancellationToken cancellationToken) { var model = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false); var root = await model.SyntaxTree.GetRootAsync(cancellationToken).ConfigureAwait(false); var addedImports = root.GetAnnotatedNodes(removeIfUnusedAnnotation); var unusedImports = new HashSet<SyntaxNode>(); this.GetUnusedNamespaceImports(model, unusedImports, cancellationToken); // only remove the unused imports that we added unusedImports.IntersectWith(addedImports); if (unusedImports.Count > 0) { var gen = SyntaxGenerator.GetGenerator(document); var newRoot = gen.RemoveNodes(root, unusedImports); return document.WithSyntaxRoot(newRoot); } else { return document; } } protected abstract void GetUnusedNamespaceImports(SemanticModel model, HashSet<SyntaxNode> namespaceImports, CancellationToken cancellationToken); } internal struct NodeOrTokenToReduce { public readonly SyntaxNodeOrToken NodeOrToken; public readonly bool SimplifyAllDescendants; public readonly SyntaxNodeOrToken OriginalNodeOrToken; public readonly bool CanBeSpeculated; public NodeOrTokenToReduce(SyntaxNodeOrToken nodeOrToken, bool simplifyAllDescendants, SyntaxNodeOrToken originalNodeOrToken, bool canBeSpeculated = true) { this.NodeOrToken = nodeOrToken; this.SimplifyAllDescendants = simplifyAllDescendants; this.OriginalNodeOrToken = originalNodeOrToken; this.CanBeSpeculated = canBeSpeculated; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.Internal.Log; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Shared.Collections; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; #if DEBUG using Microsoft.CodeAnalysis.Shared.Extensions; #endif namespace Microsoft.CodeAnalysis.Simplification { internal abstract class AbstractSimplificationService<TExpressionSyntax, TStatementSyntax, TCrefSyntax> : ISimplificationService where TExpressionSyntax : SyntaxNode where TStatementSyntax : SyntaxNode where TCrefSyntax : SyntaxNode { private ImmutableArray<AbstractReducer> _reducers; protected AbstractSimplificationService(ImmutableArray<AbstractReducer> reducers) => _reducers = reducers; protected abstract ImmutableArray<NodeOrTokenToReduce> GetNodesAndTokensToReduce(SyntaxNode root, Func<SyntaxNodeOrToken, bool> isNodeOrTokenOutsideSimplifySpans); protected abstract SemanticModel GetSpeculativeSemanticModel(ref SyntaxNode nodeToSpeculate, SemanticModel originalSemanticModel, SyntaxNode originalNode); protected abstract bool CanNodeBeSimplifiedWithoutSpeculation(SyntaxNode node); protected virtual SyntaxNode TransformReducedNode(SyntaxNode reducedNode, SyntaxNode originalNode) => reducedNode; public abstract SyntaxNode Expand(SyntaxNode node, SemanticModel semanticModel, SyntaxAnnotation annotationForReplacedAliasIdentifier, Func<SyntaxNode, bool> expandInsideNode, bool expandParameter, CancellationToken cancellationToken); public abstract SyntaxToken Expand(SyntaxToken token, SemanticModel semanticModel, Func<SyntaxNode, bool> expandInsideNode, CancellationToken cancellationToken); public async Task<Document> ReduceAsync( Document document, ImmutableArray<TextSpan> spans, OptionSet optionSet = null, ImmutableArray<AbstractReducer> reducers = default, CancellationToken cancellationToken = default) { using (Logger.LogBlock(FunctionId.Simplifier_ReduceAsync, cancellationToken)) { var spanList = spans.NullToEmpty(); // we have no span if (!spanList.Any()) { return document; } optionSet ??= await document.GetOptionsAsync(cancellationToken).ConfigureAwait(false); var semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false); // Chaining of the Speculative SemanticModel (i.e. Generating a speculative SemanticModel from an existing Speculative SemanticModel) is not supported // Hence make sure we always start working off of the actual SemanticModel instead of a speculative SemanticModel. Debug.Assert(!semanticModel.IsSpeculativeSemanticModel); var root = await semanticModel.SyntaxTree.GetRootAsync(cancellationToken).ConfigureAwait(false); #if DEBUG var originalDocHasErrors = await document.HasAnyErrorsAsync(cancellationToken).ConfigureAwait(false); #endif var reduced = await this.ReduceCoreAsync(document, spanList, optionSet, reducers, cancellationToken).ConfigureAwait(false); if (reduced != document) { #if DEBUG if (!originalDocHasErrors) { await reduced.VerifyNoErrorsAsync("Error introduced by Simplification Service", cancellationToken).ConfigureAwait(false); } #endif } return reduced; } } private async Task<Document> ReduceCoreAsync( Document document, ImmutableArray<TextSpan> spans, OptionSet optionSet, ImmutableArray<AbstractReducer> reducers, CancellationToken cancellationToken) { // Create a simple interval tree for simplification spans. var spansTree = new SimpleIntervalTree<TextSpan, TextSpanIntervalIntrospector>(new TextSpanIntervalIntrospector(), spans); bool isNodeOrTokenOutsideSimplifySpans(SyntaxNodeOrToken nodeOrToken) => !spansTree.HasIntervalThatOverlapsWith(nodeOrToken.FullSpan.Start, nodeOrToken.FullSpan.Length); var semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false); var root = await semanticModel.SyntaxTree.GetRootAsync(cancellationToken).ConfigureAwait(false); // prep namespace imports marked for simplification var removeIfUnusedAnnotation = new SyntaxAnnotation(); var originalRoot = root; root = PrepareNamespaceImportsForRemovalIfUnused(document, root, removeIfUnusedAnnotation, isNodeOrTokenOutsideSimplifySpans); var hasImportsToSimplify = root != originalRoot; if (hasImportsToSimplify) { document = document.WithSyntaxRoot(root); semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false); root = await semanticModel.SyntaxTree.GetRootAsync(cancellationToken).ConfigureAwait(false); } // Get the list of syntax nodes and tokens that need to be reduced. var nodesAndTokensToReduce = this.GetNodesAndTokensToReduce(root, isNodeOrTokenOutsideSimplifySpans); if (nodesAndTokensToReduce.Any()) { if (reducers.IsDefault) { reducers = _reducers; } // Take out any reducers that don't even apply with the current // set of users options. i.e. no point running 'reduce to var' // if the user doesn't have the 'var' preference set. reducers = reducers.WhereAsArray(r => r.IsApplicable(optionSet)); var reducedNodesMap = new ConcurrentDictionary<SyntaxNode, SyntaxNode>(); var reducedTokensMap = new ConcurrentDictionary<SyntaxToken, SyntaxToken>(); // Reduce all the nodesAndTokensToReduce using the given reducers/rewriters and // store the reduced nodes and/or tokens in the reduced nodes/tokens maps. // Note that this method doesn't update the original syntax tree. await this.ReduceAsync(document, root, nodesAndTokensToReduce, reducers, optionSet, semanticModel, reducedNodesMap, reducedTokensMap, cancellationToken).ConfigureAwait(false); if (reducedNodesMap.Any() || reducedTokensMap.Any()) { // Update the syntax tree with reduced nodes/tokens. root = root.ReplaceSyntax( nodes: reducedNodesMap.Keys, computeReplacementNode: (o, n) => TransformReducedNode(reducedNodesMap[o], n), tokens: reducedTokensMap.Keys, computeReplacementToken: (o, n) => reducedTokensMap[o], trivia: SpecializedCollections.EmptyEnumerable<SyntaxTrivia>(), computeReplacementTrivia: null); document = document.WithSyntaxRoot(root); } } if (hasImportsToSimplify) { // remove any unused namespace imports that were marked for simplification document = await this.RemoveUnusedNamespaceImportsAsync(document, removeIfUnusedAnnotation, cancellationToken).ConfigureAwait(false); } return document; } private Task ReduceAsync( Document document, SyntaxNode root, ImmutableArray<NodeOrTokenToReduce> nodesAndTokensToReduce, ImmutableArray<AbstractReducer> reducers, OptionSet optionSet, SemanticModel semanticModel, ConcurrentDictionary<SyntaxNode, SyntaxNode> reducedNodesMap, ConcurrentDictionary<SyntaxToken, SyntaxToken> reducedTokensMap, CancellationToken cancellationToken) { Contract.ThrowIfFalse(nodesAndTokensToReduce.Any()); // Reduce each node or token in the given list by running it through each reducer. var simplifyTasks = new Task[nodesAndTokensToReduce.Length]; for (var i = 0; i < nodesAndTokensToReduce.Length; i++) { var nodeOrTokenToReduce = nodesAndTokensToReduce[i]; simplifyTasks[i] = Task.Run(async () => { var nodeOrToken = nodeOrTokenToReduce.OriginalNodeOrToken; var simplifyAllDescendants = nodeOrTokenToReduce.SimplifyAllDescendants; var semanticModelForReduce = semanticModel; var currentNodeOrToken = nodeOrTokenToReduce.NodeOrToken; var isNode = nodeOrToken.IsNode; foreach (var reducer in reducers) { cancellationToken.ThrowIfCancellationRequested(); using var rewriter = reducer.GetOrCreateRewriter(); rewriter.Initialize(document.Project.ParseOptions, optionSet, cancellationToken); do { if (currentNodeOrToken.SyntaxTree != semanticModelForReduce.SyntaxTree) { // currentNodeOrToken was simplified either by a previous reducer or // a previous iteration of the current reducer. // Create a speculative semantic model for the simplified node for semantic queries. // Certain node kinds (expressions/statements) require non-null parent nodes during simplification. // However, the reduced nodes haven't been parented yet, so do the required parenting using the original node's parent. if (currentNodeOrToken.Parent == null && nodeOrToken.Parent != null && (currentNodeOrToken.IsToken || currentNodeOrToken.AsNode() is TExpressionSyntax || currentNodeOrToken.AsNode() is TStatementSyntax || currentNodeOrToken.AsNode() is TCrefSyntax)) { var annotation = new SyntaxAnnotation(); currentNodeOrToken = currentNodeOrToken.WithAdditionalAnnotations(annotation); var replacedParent = isNode ? nodeOrToken.Parent.ReplaceNode(nodeOrToken.AsNode(), currentNodeOrToken.AsNode()) : nodeOrToken.Parent.ReplaceToken(nodeOrToken.AsToken(), currentNodeOrToken.AsToken()); currentNodeOrToken = replacedParent .ChildNodesAndTokens() .Single(c => c.HasAnnotation(annotation)); } if (isNode) { var currentNode = currentNodeOrToken.AsNode(); if (this.CanNodeBeSimplifiedWithoutSpeculation(nodeOrToken.AsNode())) { // Since this node cannot be speculated, we are replacing the Document with the changes and get a new SemanticModel var marker = new SyntaxAnnotation(); var newRoot = root.ReplaceNode(nodeOrToken.AsNode(), currentNode.WithAdditionalAnnotations(marker)); var newDocument = document.WithSyntaxRoot(newRoot); semanticModelForReduce = await newDocument.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false); newRoot = await semanticModelForReduce.SyntaxTree.GetRootAsync(cancellationToken).ConfigureAwait(false); currentNodeOrToken = newRoot.DescendantNodes().Single(c => c.HasAnnotation(marker)); } else { // Create speculative semantic model for simplified node. semanticModelForReduce = GetSpeculativeSemanticModel(ref currentNode, semanticModel, nodeOrToken.AsNode()); currentNodeOrToken = currentNode; } } } // Reduce the current node or token. currentNodeOrToken = rewriter.VisitNodeOrToken(currentNodeOrToken, semanticModelForReduce, simplifyAllDescendants); } while (rewriter.HasMoreWork); } // If nodeOrToken was simplified, add it to the appropriate dictionary of replaced nodes/tokens. if (currentNodeOrToken != nodeOrToken) { if (isNode) { reducedNodesMap[nodeOrToken.AsNode()] = currentNodeOrToken.AsNode(); } else { reducedTokensMap[nodeOrToken.AsToken()] = currentNodeOrToken.AsToken(); } } }, cancellationToken); } return Task.WhenAll(simplifyTasks); } // find any namespace imports / using directives marked for simplification in the specified spans // and add removeIfUnused annotation private static SyntaxNode PrepareNamespaceImportsForRemovalIfUnused( Document document, SyntaxNode root, SyntaxAnnotation removeIfUnusedAnnotation, Func<SyntaxNodeOrToken, bool> isNodeOrTokenOutsideSimplifySpan) { var gen = SyntaxGenerator.GetGenerator(document); var importsToSimplify = root.DescendantNodes().Where(n => !isNodeOrTokenOutsideSimplifySpan(n) && gen.GetDeclarationKind(n) == DeclarationKind.NamespaceImport && n.HasAnnotation(Simplifier.Annotation)); return root.ReplaceNodes(importsToSimplify, (o, r) => r.WithAdditionalAnnotations(removeIfUnusedAnnotation)); } private async Task<Document> RemoveUnusedNamespaceImportsAsync( Document document, SyntaxAnnotation removeIfUnusedAnnotation, CancellationToken cancellationToken) { var model = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false); var root = await model.SyntaxTree.GetRootAsync(cancellationToken).ConfigureAwait(false); var addedImports = root.GetAnnotatedNodes(removeIfUnusedAnnotation); var unusedImports = new HashSet<SyntaxNode>(); this.GetUnusedNamespaceImports(model, unusedImports, cancellationToken); // only remove the unused imports that we added unusedImports.IntersectWith(addedImports); if (unusedImports.Count > 0) { var gen = SyntaxGenerator.GetGenerator(document); var newRoot = gen.RemoveNodes(root, unusedImports); return document.WithSyntaxRoot(newRoot); } else { return document; } } protected abstract void GetUnusedNamespaceImports(SemanticModel model, HashSet<SyntaxNode> namespaceImports, CancellationToken cancellationToken); } internal struct NodeOrTokenToReduce { public readonly SyntaxNodeOrToken NodeOrToken; public readonly bool SimplifyAllDescendants; public readonly SyntaxNodeOrToken OriginalNodeOrToken; public readonly bool CanBeSpeculated; public NodeOrTokenToReduce(SyntaxNodeOrToken nodeOrToken, bool simplifyAllDescendants, SyntaxNodeOrToken originalNodeOrToken, bool canBeSpeculated = true) { this.NodeOrToken = nodeOrToken; this.SimplifyAllDescendants = simplifyAllDescendants; this.OriginalNodeOrToken = originalNodeOrToken; this.CanBeSpeculated = canBeSpeculated; } } }
-1
dotnet/roslyn
55,430
Fix LSP semantic tokens algorithm
This PR primarily accomplishes two tasks: 1) Overhauls the existing LSP semantic tokens edits processing algorithm to align with [Razor's](https://github.com/dotnet/aspnetcore-tooling/blob/main/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/Semantic/Services/SemanticTokensEditsDiffer.cs) (shoutout to Ryan and the rest of the Razor team for writing the original 😄). The main change here is going from calculating edits per token (i.e. five ints) to per int. The updated algorithm is much more efficient than our previous algorithm, and returns less edits back to the LSP client. 2) The interpretation of Roslyn's LongestCommonSubstring algorithm, which we use to calculate raw edits, was missing a critical piece. Namely, for insertions, we need to keep track of _where_ we should be inserting into the original token set. We don't keep track of this in the existing implementation, resulting in bugs such as #54671. Resolves #54671
allisonchou
2021-08-05T06:06:43Z
2021-08-06T23:44:44Z
b9200d03a76c74d404040d44b9bbe12b1d0a8ef2
f300a818940ea1acef66c946cfa83756729d5e59
Fix LSP semantic tokens algorithm. This PR primarily accomplishes two tasks: 1) Overhauls the existing LSP semantic tokens edits processing algorithm to align with [Razor's](https://github.com/dotnet/aspnetcore-tooling/blob/main/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/Semantic/Services/SemanticTokensEditsDiffer.cs) (shoutout to Ryan and the rest of the Razor team for writing the original 😄). The main change here is going from calculating edits per token (i.e. five ints) to per int. The updated algorithm is much more efficient than our previous algorithm, and returns less edits back to the LSP client. 2) The interpretation of Roslyn's LongestCommonSubstring algorithm, which we use to calculate raw edits, was missing a critical piece. Namely, for insertions, we need to keep track of _where_ we should be inserting into the original token set. We don't keep track of this in the existing implementation, resulting in bugs such as #54671. Resolves #54671
./src/VisualStudio/Core/Impl/CodeModel/FileCodeModel.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Runtime.InteropServices; using System.Threading; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Simplification; using Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.Collections; using Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.InternalElements; using Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.Interop; using Microsoft.VisualStudio.LanguageServices.Implementation.Interop; using Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem; using Microsoft.VisualStudio.LanguageServices.Implementation.Utilities; using Microsoft.VisualStudio.Shell; using Microsoft.VisualStudio.Threading; using Roslyn.Utilities; namespace Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel { /// <summary> /// Implementations of EnvDTE.FileCodeModel for both languages. /// </summary> public sealed partial class FileCodeModel : AbstractCodeModelObject, EnvDTE.FileCodeModel, EnvDTE80.FileCodeModel2, ICodeElementContainer<AbstractCodeElement>, IVBFileCodeModelEvents, ICSCodeModelRefactoring { internal static ComHandle<EnvDTE80.FileCodeModel2, FileCodeModel> Create( CodeModelState state, object parent, DocumentId documentId, ITextManagerAdapter textManagerAdapter) { return new FileCodeModel(state, parent, documentId, textManagerAdapter).GetComHandle<EnvDTE80.FileCodeModel2, FileCodeModel>(); } private readonly ComHandle<object, object> _parentHandle; /// <summary> /// Don't use directly. Instead, call <see cref="GetDocumentId()"/>. /// </summary> private DocumentId _documentId; // Note: these are only valid when the underlying file is being renamed. Do not use. private ProjectId _incomingProjectId; private string _incomingFilePath; private Document _previousDocument; private readonly CleanableWeakComHandleTable<SyntaxNodeKey, EnvDTE.CodeElement> _codeElementTable; // These are used during batching. private bool _batchMode; private List<AbstractKeyedCodeElement> _batchElements; private Document _batchDocument; // track state to make sure we open editor only once private int _editCount; private IInvisibleEditor _invisibleEditor; private SyntaxTree _lastSyntaxTree; private FileCodeModel( CodeModelState state, object parent, DocumentId documentId, ITextManagerAdapter textManagerAdapter) : base(state) { Debug.Assert(documentId != null); Debug.Assert(textManagerAdapter != null); _parentHandle = new ComHandle<object, object>(parent); _documentId = documentId; TextManagerAdapter = textManagerAdapter; _codeElementTable = new CleanableWeakComHandleTable<SyntaxNodeKey, EnvDTE.CodeElement>(state.ThreadingContext); _batchMode = false; _batchDocument = null; _lastSyntaxTree = GetSyntaxTree(); } internal ITextManagerAdapter TextManagerAdapter { get; set; } /// <summary> /// Internally, we store the DocumentId for the document that the FileCodeModel represents. If the underlying file /// is renamed, the DocumentId will become invalid because the Roslyn VS workspace treats file renames as a remove/add pair. /// To work around this, the FileCodeModel is notified when a file rename is about to occur. At that point, the /// <see cref="_documentId"/> field is null'd out and <see cref="_incomingFilePath"/> is set to the name of the new file. /// The next time that a FileCodeModel operation occurs that requires the DocumentId, it will be retrieved from the workspace /// using the <see cref="_incomingFilePath"/>. /// </summary> internal void OnRename(string newFilePath) { Debug.Assert(_editCount == 0, "FileCodeModel have an open edit and the underlying file is being renamed. This is a bug."); if (_documentId != null) { _previousDocument = Workspace.CurrentSolution.GetDocument(_documentId); } _incomingFilePath = newFilePath; _incomingProjectId = _documentId.ProjectId; _documentId = null; } internal override void Shutdown() { if (_invisibleEditor != null) { // we are shutting down, so do not worry about editCount. We will detach our format tracking from the text // buffer now; if anybody else had an invisible editor open to this file, we wouldn't want our format tracking // to trigger. We can safely do that on a background thread since it's just disconnecting a few event handlers. // We have to defer the shutdown of the invisible editor though as that requires talking to the UI thread. // We don't want to block up file removal on the UI thread since we want that path to stay asynchronous. CodeModelService.DetachFormatTrackingToBuffer(_invisibleEditor.TextBuffer); State.ProjectCodeModelFactory.ScheduleDeferredCleanupTask( cancellationToken => { // Ignore cancellationToken: we always need to call Dispose since it triggers the file save. _ = cancellationToken; _invisibleEditor.Dispose(); }); } base.Shutdown(); } private bool TryGetDocumentId(out DocumentId documentId) { if (_documentId != null) { documentId = _documentId; return true; } documentId = null; // We don't have DocumentId, so try to retrieve it from the workspace. if (_incomingProjectId == null || _incomingFilePath == null) { return false; } var project = this.State.Workspace.CurrentSolution.GetProject(_incomingProjectId); if (project == null) { return false; } documentId = project.Solution.GetDocumentIdsWithFilePath(_incomingFilePath).FirstOrDefault(d => d.ProjectId == project.Id); if (documentId == null) { return false; } _documentId = documentId; _incomingProjectId = null; _incomingFilePath = null; _previousDocument = null; return true; } internal DocumentId GetDocumentId() { if (_documentId != null) { return _documentId; } if (TryGetDocumentId(out var documentId)) { return documentId; } throw Exceptions.ThrowEUnexpected(); } internal void UpdateCodeElementNodeKey(AbstractKeyedCodeElement keyedElement, SyntaxNodeKey oldNodeKey, SyntaxNodeKey newNodeKey) { if (!_codeElementTable.TryGetValue(oldNodeKey, out var codeElement)) { throw new InvalidOperationException($"Could not find {oldNodeKey} in Code Model element table."); } _codeElementTable.Remove(oldNodeKey); var managedElement = ComAggregate.GetManagedObject<AbstractKeyedCodeElement>(codeElement); if (!object.Equals(managedElement, keyedElement)) { throw new InvalidOperationException($"Unexpected failure in Code Model while updating node keys {oldNodeKey} -> {newNodeKey}"); } // If we're updating this element with the same node key as an element that's already in the table, // just remove the old element. The old element will continue to function (through its node key), but // the new element will replace it in the cache. if (_codeElementTable.ContainsKey(newNodeKey)) { _codeElementTable.Remove(newNodeKey); } _codeElementTable.Add(newNodeKey, codeElement); } internal void OnCodeElementCreated(SyntaxNodeKey nodeKey, EnvDTE.CodeElement element) { // If we're updating this element with the same node key as an element that's already in the table, // just remove the old element. The old element will continue to function (through its node key), but // the new element will replace it in the cache. if (_codeElementTable.ContainsKey(nodeKey)) { _codeElementTable.Remove(nodeKey); } _codeElementTable.Add(nodeKey, element); } internal void OnCodeElementDeleted(SyntaxNodeKey nodeKey) => _codeElementTable.Remove(nodeKey); internal T GetOrCreateCodeElement<T>(SyntaxNode node) { var nodeKey = CodeModelService.TryGetNodeKey(node); if (!nodeKey.IsEmpty) { // Since the node already has a key, check to see if a code element already // exists for it. If so, return that element it it's still valid; otherwise, // remove it from the table. if (_codeElementTable.TryGetValue(nodeKey, out var codeElement)) { if (codeElement != null) { var element = ComAggregate.TryGetManagedObject<AbstractCodeElement>(codeElement); if (element.IsValidNode()) { if (codeElement is T tcodeElement) { return tcodeElement; } throw new InvalidOperationException($"Found a valid code element for {nodeKey}, but it is not of type, {typeof(T).ToString()}"); } } } // Go ahead and remove the nodeKey from the table. At this point, we'll be creating a new one. _codeElementTable.Remove(nodeKey); } return (T)CodeModelService.CreateInternalCodeElement(this.State, this, node); } private void InitializeEditor() { _editCount++; if (_editCount == 1) { Debug.Assert(_invisibleEditor == null); _invisibleEditor = Workspace.OpenInvisibleEditor(GetDocumentId()); CodeModelService.AttachFormatTrackingToBuffer(_invisibleEditor.TextBuffer); } } private void ReleaseEditor() { Debug.Assert(_editCount >= 1); _editCount--; if (_editCount == 0) { Debug.Assert(_invisibleEditor != null); CodeModelService.DetachFormatTrackingToBuffer(_invisibleEditor.TextBuffer); _invisibleEditor.Dispose(); _invisibleEditor = null; } } internal void EnsureEditor(Action action) { InitializeEditor(); try { action(); } finally { ReleaseEditor(); } } internal T EnsureEditor<T>(Func<T> action) { InitializeEditor(); try { return action(); } finally { ReleaseEditor(); } } internal void PerformEdit(Func<Document, Document> action) { EnsureEditor(() => { Debug.Assert(_invisibleEditor != null); var document = GetDocument(); var workspace = document.Project.Solution.Workspace; var result = action(document); var formatted = State.ThreadingContext.JoinableTaskFactory.Run(async () => { var formatted = await Formatter.FormatAsync(result, Formatter.Annotation).ConfigureAwait(true); formatted = await Formatter.FormatAsync(formatted, SyntaxAnnotation.ElasticAnnotation).ConfigureAwait(true); return formatted; }); ApplyChanges(workspace, formatted); }); } internal T PerformEdit<T>(Func<Document, Tuple<T, Document>> action) where T : SyntaxNode { return EnsureEditor(() => { Debug.Assert(_invisibleEditor != null); var document = GetDocument(); var workspace = document.Project.Solution.Workspace; var result = action(document); ApplyChanges(workspace, result.Item2); return result.Item1; }); } private void ApplyChanges(Workspace workspace, Document document) { if (IsBatchOpen) { _batchDocument = document; } else { workspace.TryApplyChanges(document.Project.Solution); } } internal Document GetDocument() { if (!TryGetDocument(out var document)) { throw Exceptions.ThrowEFail(); } return document; } internal bool TryGetDocument(out Document document) { if (IsBatchOpen && _batchDocument != null) { document = _batchDocument; return true; } if (!TryGetDocumentId(out _) && _previousDocument != null) { document = _previousDocument; } else { // HACK HACK HACK: Ensure we've processed all files being opened before we let designers work further. // In https://devdiv.visualstudio.com/DevDiv/_workitems/edit/728035, a file is opened in an invisible editor and contents are written // to it. The file isn't saved, but it's added to the workspace; we won't have yet hooked up to the open file since that work was deferred. // Since we're on the UI thread here, we can ensure those are all wired up since the analysis of this document may depend on that other file. // We choose to do this here rather than in the project system code when it's added because we don't want to pay the penalty of checking the RDT for // all files being opened on the UI thread if we really don't need it. This uses an 'as' cast, because in unit tests the workspace is a different // derived form of VisualStudioWorkspace, and there we aren't dealing with open files at all so it doesn't matter. (State.Workspace as VisualStudioWorkspaceImpl)?.ProcessQueuedWorkOnUIThread(); document = Workspace.CurrentSolution.GetDocument(GetDocumentId()); } return document != null; } internal SyntaxTree GetSyntaxTree() { return GetDocument().GetSyntaxTreeSynchronously(CancellationToken.None); } internal SyntaxNode GetSyntaxRoot() { return GetDocument().GetSyntaxRootSynchronously(CancellationToken.None); } internal SemanticModel GetSemanticModel() => State.ThreadingContext.JoinableTaskFactory.Run(() => { return GetDocument() .GetSemanticModelAsync(CancellationToken.None); }); internal Compilation GetCompilation() => State.ThreadingContext.JoinableTaskFactory.Run(() => { return GetDocument().Project .GetCompilationAsync(CancellationToken.None); }); internal ProjectId GetProjectId() => GetDocumentId().ProjectId; internal SyntaxNode LookupNode(SyntaxNodeKey nodeKey) => CodeModelService.LookupNode(nodeKey, GetSyntaxTree()); internal TSyntaxNode LookupNode<TSyntaxNode>(SyntaxNodeKey nodeKey) where TSyntaxNode : SyntaxNode { return CodeModelService.LookupNode(nodeKey, GetSyntaxTree()) as TSyntaxNode; } public EnvDTE.CodeAttribute AddAttribute(string name, string value, object position) { return EnsureEditor(() => { return AddAttribute(GetSyntaxRoot(), name, value, position, target: CodeModelService.AssemblyAttributeString); }); } public EnvDTE.CodeClass AddClass(string name, object position, object bases, object implementedInterfaces, EnvDTE.vsCMAccess access) { return EnsureEditor(() => { return AddClass(GetSyntaxRoot(), name, position, bases, implementedInterfaces, access); }); } public EnvDTE.CodeDelegate AddDelegate(string name, object type, object position, EnvDTE.vsCMAccess access) { return EnsureEditor(() => { return AddDelegate(GetSyntaxRoot(), name, type, position, access); }); } public EnvDTE.CodeEnum AddEnum(string name, object position, object bases, EnvDTE.vsCMAccess access) { return EnsureEditor(() => { return AddEnum(GetSyntaxRoot(), name, position, bases, access); }); } public EnvDTE.CodeFunction AddFunction(string name, EnvDTE.vsCMFunction kind, object type, object position, EnvDTE.vsCMAccess access) => throw Exceptions.ThrowEFail(); public EnvDTE80.CodeImport AddImport(string name, object position, string alias) { return EnsureEditor(() => { return AddImport(GetSyntaxRoot(), name, position, alias); }); } public EnvDTE.CodeInterface AddInterface(string name, object position, object bases, EnvDTE.vsCMAccess access) { return EnsureEditor(() => { return AddInterface(GetSyntaxRoot(), name, position, bases, access); }); } public EnvDTE.CodeNamespace AddNamespace(string name, object position) { return EnsureEditor(() => { return AddNamespace(GetSyntaxRoot(), name, position); }); } public EnvDTE.CodeStruct AddStruct(string name, object position, object bases, object implementedInterfaces, EnvDTE.vsCMAccess access) { return EnsureEditor(() => { return AddStruct(GetSyntaxRoot(), name, position, bases, implementedInterfaces, access); }); } public EnvDTE.CodeVariable AddVariable(string name, object type, object position, EnvDTE.vsCMAccess access) => throw Exceptions.ThrowEFail(); public EnvDTE.CodeElement CodeElementFromPoint(EnvDTE.TextPoint point, EnvDTE.vsCMElement scope) { // Can't use point.AbsoluteCharOffset because it's calculated by the native // implementation in GetAbsoluteOffset (in env\msenv\textmgr\autoutil.cpp) // to only count each newline as a single character. We need to ask for line and // column and calculate the right offset ourselves. See DevDiv2 530496 for details. var position = GetPositionFromTextPoint(point); var result = CodeElementFromPosition(position, scope); if (result == null) { throw Exceptions.ThrowEFail(); } return result; } private int GetPositionFromTextPoint(EnvDTE.TextPoint point) { var lineNumber = point.Line - 1; var column = point.LineCharOffset - 1; var line = GetDocument().GetTextSynchronously(CancellationToken.None).Lines[lineNumber]; var position = line.Start + column; return position; } internal EnvDTE.CodeElement CodeElementFromPosition(int position, EnvDTE.vsCMElement scope) { var root = GetSyntaxRoot(); var leftToken = SyntaxFactsService.FindTokenOnLeftOfPosition(root, position); var rightToken = SyntaxFactsService.FindTokenOnRightOfPosition(root, position); // We apply a set of heuristics to determine which member we pick to start searching. var token = leftToken; if (leftToken != rightToken) { if (leftToken.Span.End == position && rightToken.SpanStart == position) { // If both tokens are touching, we prefer identifiers and keywords to // separators. Note that the language doesn't allow both tokens to be a // keyword or identifier. if (SyntaxFactsService.IsReservedOrContextualKeyword(rightToken) || SyntaxFactsService.IsIdentifier(rightToken)) { token = rightToken; } } else if (leftToken.Span.End < position && rightToken.SpanStart <= position) { // If only the right token is touching, we have to use it. token = rightToken; } } // If we ended up using the left token but the position is after that token, // walk up to the first node who's last token is not the leftToken. By doing this, we // ensure that we don't find members when the position is actually between them. // In that case, we should find the enclosing type or namespace. var parent = token.Parent; if (token == leftToken && position > token.Span.End) { while (parent != null) { if (parent.GetLastToken() == token) { parent = parent.Parent; } else { break; } } } var node = parent?.AncestorsAndSelf().FirstOrDefault(n => CodeModelService.MatchesScope(n, scope)); if (node == null) { return null; } if (scope == EnvDTE.vsCMElement.vsCMElementAttribute || scope == EnvDTE.vsCMElement.vsCMElementImportStmt || scope == EnvDTE.vsCMElement.vsCMElementParameter || scope == EnvDTE.vsCMElement.vsCMElementOptionStmt || scope == EnvDTE.vsCMElement.vsCMElementInheritsStmt || scope == EnvDTE.vsCMElement.vsCMElementImplementsStmt || (scope == EnvDTE.vsCMElement.vsCMElementFunction && CodeModelService.IsAccessorNode(node))) { // Attributes, imports, parameters, Option, Inherits and Implements // don't have node keys of their own and won't be included in our // collection of elements. Delegate to the service to create these. return CodeModelService.CreateInternalCodeElement(State, this, node); } return GetOrCreateCodeElement<EnvDTE.CodeElement>(node); } public EnvDTE.CodeElements CodeElements { get { return NamespaceCollection.Create(this.State, this, this, SyntaxNodeKey.Empty); } } public EnvDTE.ProjectItem Parent { get { return _parentHandle.Object as EnvDTE.ProjectItem; } } public void Remove(object element) { var codeElement = ComAggregate.TryGetManagedObject<AbstractCodeElement>(element); if (codeElement == null) { codeElement = ComAggregate.TryGetManagedObject<AbstractCodeElement>(this.CodeElements.Item(element)); } if (codeElement == null) { throw new ArgumentException(ServicesVSResources.Element_is_not_valid, nameof(element)); } codeElement.Delete(); } int IVBFileCodeModelEvents.StartEdit() { try { InitializeEditor(); if (_editCount == 1) { _batchMode = true; _batchElements = new List<AbstractKeyedCodeElement>(); } return VSConstants.S_OK; } catch (Exception ex) { return Marshal.GetHRForException(ex); } } int IVBFileCodeModelEvents.EndEdit() { try { if (_editCount == 1) { List<ValueTuple<AbstractKeyedCodeElement, SyntaxPath>> elementAndPaths = null; if (_batchElements.Count > 0) { foreach (var element in _batchElements) { var node = element.LookupNode(); if (node != null) { elementAndPaths ??= new List<ValueTuple<AbstractKeyedCodeElement, SyntaxPath>>(); elementAndPaths.Add(ValueTuple.Create(element, new SyntaxPath(node))); } } } if (_batchDocument != null) { // perform expensive operations at once var newDocument = State.ThreadingContext.JoinableTaskFactory.Run(() => Simplifier.ReduceAsync(_batchDocument, Simplifier.Annotation, cancellationToken: CancellationToken.None)); _batchDocument.Project.Solution.Workspace.TryApplyChanges(newDocument.Project.Solution); // done using batch document _batchDocument = null; } // Ensure the file is prettylisted, even if we didn't make any edits CodeModelService.EnsureBufferFormatted(_invisibleEditor.TextBuffer); if (elementAndPaths != null) { foreach (var elementAndPath in elementAndPaths) { // make sure the element is there. if (_codeElementTable.TryGetValue(elementAndPath.Item1.NodeKey, out var existingElement)) { elementAndPath.Item1.ReacquireNodeKey(elementAndPath.Item2, CancellationToken.None); } // make sure existing element doesn't go away (weak reference) in the middle of // updating the node key GC.KeepAlive(existingElement); } } _batchMode = false; _batchElements = null; } return VSConstants.S_OK; } catch (Exception ex) { return Marshal.GetHRForException(ex); } finally { ReleaseEditor(); } } public void BeginBatch() { IVBFileCodeModelEvents temp = this; ErrorHandler.ThrowOnFailure(temp.StartEdit()); } public void EndBatch() { IVBFileCodeModelEvents temp = this; ErrorHandler.ThrowOnFailure(temp.EndEdit()); } public bool IsBatchOpen { get { return _batchMode && _editCount > 0; } } public EnvDTE.CodeElement ElementFromID(string id) => throw new NotImplementedException(); public EnvDTE80.vsCMParseStatus ParseStatus { get { var syntaxTree = GetSyntaxTree(); return syntaxTree.GetDiagnostics().Any(d => d.Severity == DiagnosticSeverity.Error) ? EnvDTE80.vsCMParseStatus.vsCMParseStatusError : EnvDTE80.vsCMParseStatus.vsCMParseStatusComplete; } } public void Synchronize() => FireEvents(); EnvDTE.CodeElements ICodeElementContainer<AbstractCodeElement>.GetCollection() => CodeElements; internal List<GlobalNodeKey> GetCurrentNodeKeys() { var currentNodeKeys = new List<GlobalNodeKey>(); foreach (var element in _codeElementTable.Values) { var keyedElement = ComAggregate.TryGetManagedObject<AbstractKeyedCodeElement>(element); if (keyedElement == null) { continue; } if (keyedElement.TryLookupNode(out var node)) { var nodeKey = keyedElement.NodeKey; currentNodeKeys.Add(new GlobalNodeKey(nodeKey, new SyntaxPath(node))); } } return currentNodeKeys; } internal void ResetElementKeys(List<GlobalNodeKey> globalNodeKeys) { foreach (var globalNodeKey in globalNodeKeys) { ResetElementKey(globalNodeKey); } } private void ResetElementKey(GlobalNodeKey globalNodeKey) { // Failure to find the element is not an error -- it just means the code // element didn't exist... if (_codeElementTable.TryGetValue(globalNodeKey.NodeKey, out var element)) { var keyedElement = ComAggregate.GetManagedObject<AbstractKeyedCodeElement>(element); if (keyedElement != null) { keyedElement.ReacquireNodeKey(globalNodeKey.Path, default); } } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Runtime.InteropServices; using System.Threading; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Simplification; using Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.Collections; using Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.InternalElements; using Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.Interop; using Microsoft.VisualStudio.LanguageServices.Implementation.Interop; using Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem; using Microsoft.VisualStudio.LanguageServices.Implementation.Utilities; using Microsoft.VisualStudio.Shell; using Microsoft.VisualStudio.Threading; using Roslyn.Utilities; namespace Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel { /// <summary> /// Implementations of EnvDTE.FileCodeModel for both languages. /// </summary> public sealed partial class FileCodeModel : AbstractCodeModelObject, EnvDTE.FileCodeModel, EnvDTE80.FileCodeModel2, ICodeElementContainer<AbstractCodeElement>, IVBFileCodeModelEvents, ICSCodeModelRefactoring { internal static ComHandle<EnvDTE80.FileCodeModel2, FileCodeModel> Create( CodeModelState state, object parent, DocumentId documentId, ITextManagerAdapter textManagerAdapter) { return new FileCodeModel(state, parent, documentId, textManagerAdapter).GetComHandle<EnvDTE80.FileCodeModel2, FileCodeModel>(); } private readonly ComHandle<object, object> _parentHandle; /// <summary> /// Don't use directly. Instead, call <see cref="GetDocumentId()"/>. /// </summary> private DocumentId _documentId; // Note: these are only valid when the underlying file is being renamed. Do not use. private ProjectId _incomingProjectId; private string _incomingFilePath; private Document _previousDocument; private readonly CleanableWeakComHandleTable<SyntaxNodeKey, EnvDTE.CodeElement> _codeElementTable; // These are used during batching. private bool _batchMode; private List<AbstractKeyedCodeElement> _batchElements; private Document _batchDocument; // track state to make sure we open editor only once private int _editCount; private IInvisibleEditor _invisibleEditor; private SyntaxTree _lastSyntaxTree; private FileCodeModel( CodeModelState state, object parent, DocumentId documentId, ITextManagerAdapter textManagerAdapter) : base(state) { Debug.Assert(documentId != null); Debug.Assert(textManagerAdapter != null); _parentHandle = new ComHandle<object, object>(parent); _documentId = documentId; TextManagerAdapter = textManagerAdapter; _codeElementTable = new CleanableWeakComHandleTable<SyntaxNodeKey, EnvDTE.CodeElement>(state.ThreadingContext); _batchMode = false; _batchDocument = null; _lastSyntaxTree = GetSyntaxTree(); } internal ITextManagerAdapter TextManagerAdapter { get; set; } /// <summary> /// Internally, we store the DocumentId for the document that the FileCodeModel represents. If the underlying file /// is renamed, the DocumentId will become invalid because the Roslyn VS workspace treats file renames as a remove/add pair. /// To work around this, the FileCodeModel is notified when a file rename is about to occur. At that point, the /// <see cref="_documentId"/> field is null'd out and <see cref="_incomingFilePath"/> is set to the name of the new file. /// The next time that a FileCodeModel operation occurs that requires the DocumentId, it will be retrieved from the workspace /// using the <see cref="_incomingFilePath"/>. /// </summary> internal void OnRename(string newFilePath) { Debug.Assert(_editCount == 0, "FileCodeModel have an open edit and the underlying file is being renamed. This is a bug."); if (_documentId != null) { _previousDocument = Workspace.CurrentSolution.GetDocument(_documentId); } _incomingFilePath = newFilePath; _incomingProjectId = _documentId.ProjectId; _documentId = null; } internal override void Shutdown() { if (_invisibleEditor != null) { // we are shutting down, so do not worry about editCount. We will detach our format tracking from the text // buffer now; if anybody else had an invisible editor open to this file, we wouldn't want our format tracking // to trigger. We can safely do that on a background thread since it's just disconnecting a few event handlers. // We have to defer the shutdown of the invisible editor though as that requires talking to the UI thread. // We don't want to block up file removal on the UI thread since we want that path to stay asynchronous. CodeModelService.DetachFormatTrackingToBuffer(_invisibleEditor.TextBuffer); State.ProjectCodeModelFactory.ScheduleDeferredCleanupTask( cancellationToken => { // Ignore cancellationToken: we always need to call Dispose since it triggers the file save. _ = cancellationToken; _invisibleEditor.Dispose(); }); } base.Shutdown(); } private bool TryGetDocumentId(out DocumentId documentId) { if (_documentId != null) { documentId = _documentId; return true; } documentId = null; // We don't have DocumentId, so try to retrieve it from the workspace. if (_incomingProjectId == null || _incomingFilePath == null) { return false; } var project = this.State.Workspace.CurrentSolution.GetProject(_incomingProjectId); if (project == null) { return false; } documentId = project.Solution.GetDocumentIdsWithFilePath(_incomingFilePath).FirstOrDefault(d => d.ProjectId == project.Id); if (documentId == null) { return false; } _documentId = documentId; _incomingProjectId = null; _incomingFilePath = null; _previousDocument = null; return true; } internal DocumentId GetDocumentId() { if (_documentId != null) { return _documentId; } if (TryGetDocumentId(out var documentId)) { return documentId; } throw Exceptions.ThrowEUnexpected(); } internal void UpdateCodeElementNodeKey(AbstractKeyedCodeElement keyedElement, SyntaxNodeKey oldNodeKey, SyntaxNodeKey newNodeKey) { if (!_codeElementTable.TryGetValue(oldNodeKey, out var codeElement)) { throw new InvalidOperationException($"Could not find {oldNodeKey} in Code Model element table."); } _codeElementTable.Remove(oldNodeKey); var managedElement = ComAggregate.GetManagedObject<AbstractKeyedCodeElement>(codeElement); if (!object.Equals(managedElement, keyedElement)) { throw new InvalidOperationException($"Unexpected failure in Code Model while updating node keys {oldNodeKey} -> {newNodeKey}"); } // If we're updating this element with the same node key as an element that's already in the table, // just remove the old element. The old element will continue to function (through its node key), but // the new element will replace it in the cache. if (_codeElementTable.ContainsKey(newNodeKey)) { _codeElementTable.Remove(newNodeKey); } _codeElementTable.Add(newNodeKey, codeElement); } internal void OnCodeElementCreated(SyntaxNodeKey nodeKey, EnvDTE.CodeElement element) { // If we're updating this element with the same node key as an element that's already in the table, // just remove the old element. The old element will continue to function (through its node key), but // the new element will replace it in the cache. if (_codeElementTable.ContainsKey(nodeKey)) { _codeElementTable.Remove(nodeKey); } _codeElementTable.Add(nodeKey, element); } internal void OnCodeElementDeleted(SyntaxNodeKey nodeKey) => _codeElementTable.Remove(nodeKey); internal T GetOrCreateCodeElement<T>(SyntaxNode node) { var nodeKey = CodeModelService.TryGetNodeKey(node); if (!nodeKey.IsEmpty) { // Since the node already has a key, check to see if a code element already // exists for it. If so, return that element it it's still valid; otherwise, // remove it from the table. if (_codeElementTable.TryGetValue(nodeKey, out var codeElement)) { if (codeElement != null) { var element = ComAggregate.TryGetManagedObject<AbstractCodeElement>(codeElement); if (element.IsValidNode()) { if (codeElement is T tcodeElement) { return tcodeElement; } throw new InvalidOperationException($"Found a valid code element for {nodeKey}, but it is not of type, {typeof(T).ToString()}"); } } } // Go ahead and remove the nodeKey from the table. At this point, we'll be creating a new one. _codeElementTable.Remove(nodeKey); } return (T)CodeModelService.CreateInternalCodeElement(this.State, this, node); } private void InitializeEditor() { _editCount++; if (_editCount == 1) { Debug.Assert(_invisibleEditor == null); _invisibleEditor = Workspace.OpenInvisibleEditor(GetDocumentId()); CodeModelService.AttachFormatTrackingToBuffer(_invisibleEditor.TextBuffer); } } private void ReleaseEditor() { Debug.Assert(_editCount >= 1); _editCount--; if (_editCount == 0) { Debug.Assert(_invisibleEditor != null); CodeModelService.DetachFormatTrackingToBuffer(_invisibleEditor.TextBuffer); _invisibleEditor.Dispose(); _invisibleEditor = null; } } internal void EnsureEditor(Action action) { InitializeEditor(); try { action(); } finally { ReleaseEditor(); } } internal T EnsureEditor<T>(Func<T> action) { InitializeEditor(); try { return action(); } finally { ReleaseEditor(); } } internal void PerformEdit(Func<Document, Document> action) { EnsureEditor(() => { Debug.Assert(_invisibleEditor != null); var document = GetDocument(); var workspace = document.Project.Solution.Workspace; var result = action(document); var formatted = State.ThreadingContext.JoinableTaskFactory.Run(async () => { var formatted = await Formatter.FormatAsync(result, Formatter.Annotation).ConfigureAwait(true); formatted = await Formatter.FormatAsync(formatted, SyntaxAnnotation.ElasticAnnotation).ConfigureAwait(true); return formatted; }); ApplyChanges(workspace, formatted); }); } internal T PerformEdit<T>(Func<Document, Tuple<T, Document>> action) where T : SyntaxNode { return EnsureEditor(() => { Debug.Assert(_invisibleEditor != null); var document = GetDocument(); var workspace = document.Project.Solution.Workspace; var result = action(document); ApplyChanges(workspace, result.Item2); return result.Item1; }); } private void ApplyChanges(Workspace workspace, Document document) { if (IsBatchOpen) { _batchDocument = document; } else { workspace.TryApplyChanges(document.Project.Solution); } } internal Document GetDocument() { if (!TryGetDocument(out var document)) { throw Exceptions.ThrowEFail(); } return document; } internal bool TryGetDocument(out Document document) { if (IsBatchOpen && _batchDocument != null) { document = _batchDocument; return true; } if (!TryGetDocumentId(out _) && _previousDocument != null) { document = _previousDocument; } else { // HACK HACK HACK: Ensure we've processed all files being opened before we let designers work further. // In https://devdiv.visualstudio.com/DevDiv/_workitems/edit/728035, a file is opened in an invisible editor and contents are written // to it. The file isn't saved, but it's added to the workspace; we won't have yet hooked up to the open file since that work was deferred. // Since we're on the UI thread here, we can ensure those are all wired up since the analysis of this document may depend on that other file. // We choose to do this here rather than in the project system code when it's added because we don't want to pay the penalty of checking the RDT for // all files being opened on the UI thread if we really don't need it. This uses an 'as' cast, because in unit tests the workspace is a different // derived form of VisualStudioWorkspace, and there we aren't dealing with open files at all so it doesn't matter. (State.Workspace as VisualStudioWorkspaceImpl)?.ProcessQueuedWorkOnUIThread(); document = Workspace.CurrentSolution.GetDocument(GetDocumentId()); } return document != null; } internal SyntaxTree GetSyntaxTree() { return GetDocument().GetSyntaxTreeSynchronously(CancellationToken.None); } internal SyntaxNode GetSyntaxRoot() { return GetDocument().GetSyntaxRootSynchronously(CancellationToken.None); } internal SemanticModel GetSemanticModel() => State.ThreadingContext.JoinableTaskFactory.Run(() => { return GetDocument() .GetSemanticModelAsync(CancellationToken.None); }); internal Compilation GetCompilation() => State.ThreadingContext.JoinableTaskFactory.Run(() => { return GetDocument().Project .GetCompilationAsync(CancellationToken.None); }); internal ProjectId GetProjectId() => GetDocumentId().ProjectId; internal SyntaxNode LookupNode(SyntaxNodeKey nodeKey) => CodeModelService.LookupNode(nodeKey, GetSyntaxTree()); internal TSyntaxNode LookupNode<TSyntaxNode>(SyntaxNodeKey nodeKey) where TSyntaxNode : SyntaxNode { return CodeModelService.LookupNode(nodeKey, GetSyntaxTree()) as TSyntaxNode; } public EnvDTE.CodeAttribute AddAttribute(string name, string value, object position) { return EnsureEditor(() => { return AddAttribute(GetSyntaxRoot(), name, value, position, target: CodeModelService.AssemblyAttributeString); }); } public EnvDTE.CodeClass AddClass(string name, object position, object bases, object implementedInterfaces, EnvDTE.vsCMAccess access) { return EnsureEditor(() => { return AddClass(GetSyntaxRoot(), name, position, bases, implementedInterfaces, access); }); } public EnvDTE.CodeDelegate AddDelegate(string name, object type, object position, EnvDTE.vsCMAccess access) { return EnsureEditor(() => { return AddDelegate(GetSyntaxRoot(), name, type, position, access); }); } public EnvDTE.CodeEnum AddEnum(string name, object position, object bases, EnvDTE.vsCMAccess access) { return EnsureEditor(() => { return AddEnum(GetSyntaxRoot(), name, position, bases, access); }); } public EnvDTE.CodeFunction AddFunction(string name, EnvDTE.vsCMFunction kind, object type, object position, EnvDTE.vsCMAccess access) => throw Exceptions.ThrowEFail(); public EnvDTE80.CodeImport AddImport(string name, object position, string alias) { return EnsureEditor(() => { return AddImport(GetSyntaxRoot(), name, position, alias); }); } public EnvDTE.CodeInterface AddInterface(string name, object position, object bases, EnvDTE.vsCMAccess access) { return EnsureEditor(() => { return AddInterface(GetSyntaxRoot(), name, position, bases, access); }); } public EnvDTE.CodeNamespace AddNamespace(string name, object position) { return EnsureEditor(() => { return AddNamespace(GetSyntaxRoot(), name, position); }); } public EnvDTE.CodeStruct AddStruct(string name, object position, object bases, object implementedInterfaces, EnvDTE.vsCMAccess access) { return EnsureEditor(() => { return AddStruct(GetSyntaxRoot(), name, position, bases, implementedInterfaces, access); }); } public EnvDTE.CodeVariable AddVariable(string name, object type, object position, EnvDTE.vsCMAccess access) => throw Exceptions.ThrowEFail(); public EnvDTE.CodeElement CodeElementFromPoint(EnvDTE.TextPoint point, EnvDTE.vsCMElement scope) { // Can't use point.AbsoluteCharOffset because it's calculated by the native // implementation in GetAbsoluteOffset (in env\msenv\textmgr\autoutil.cpp) // to only count each newline as a single character. We need to ask for line and // column and calculate the right offset ourselves. See DevDiv2 530496 for details. var position = GetPositionFromTextPoint(point); var result = CodeElementFromPosition(position, scope); if (result == null) { throw Exceptions.ThrowEFail(); } return result; } private int GetPositionFromTextPoint(EnvDTE.TextPoint point) { var lineNumber = point.Line - 1; var column = point.LineCharOffset - 1; var line = GetDocument().GetTextSynchronously(CancellationToken.None).Lines[lineNumber]; var position = line.Start + column; return position; } internal EnvDTE.CodeElement CodeElementFromPosition(int position, EnvDTE.vsCMElement scope) { var root = GetSyntaxRoot(); var leftToken = SyntaxFactsService.FindTokenOnLeftOfPosition(root, position); var rightToken = SyntaxFactsService.FindTokenOnRightOfPosition(root, position); // We apply a set of heuristics to determine which member we pick to start searching. var token = leftToken; if (leftToken != rightToken) { if (leftToken.Span.End == position && rightToken.SpanStart == position) { // If both tokens are touching, we prefer identifiers and keywords to // separators. Note that the language doesn't allow both tokens to be a // keyword or identifier. if (SyntaxFactsService.IsReservedOrContextualKeyword(rightToken) || SyntaxFactsService.IsIdentifier(rightToken)) { token = rightToken; } } else if (leftToken.Span.End < position && rightToken.SpanStart <= position) { // If only the right token is touching, we have to use it. token = rightToken; } } // If we ended up using the left token but the position is after that token, // walk up to the first node who's last token is not the leftToken. By doing this, we // ensure that we don't find members when the position is actually between them. // In that case, we should find the enclosing type or namespace. var parent = token.Parent; if (token == leftToken && position > token.Span.End) { while (parent != null) { if (parent.GetLastToken() == token) { parent = parent.Parent; } else { break; } } } var node = parent?.AncestorsAndSelf().FirstOrDefault(n => CodeModelService.MatchesScope(n, scope)); if (node == null) { return null; } if (scope == EnvDTE.vsCMElement.vsCMElementAttribute || scope == EnvDTE.vsCMElement.vsCMElementImportStmt || scope == EnvDTE.vsCMElement.vsCMElementParameter || scope == EnvDTE.vsCMElement.vsCMElementOptionStmt || scope == EnvDTE.vsCMElement.vsCMElementInheritsStmt || scope == EnvDTE.vsCMElement.vsCMElementImplementsStmt || (scope == EnvDTE.vsCMElement.vsCMElementFunction && CodeModelService.IsAccessorNode(node))) { // Attributes, imports, parameters, Option, Inherits and Implements // don't have node keys of their own and won't be included in our // collection of elements. Delegate to the service to create these. return CodeModelService.CreateInternalCodeElement(State, this, node); } return GetOrCreateCodeElement<EnvDTE.CodeElement>(node); } public EnvDTE.CodeElements CodeElements { get { return NamespaceCollection.Create(this.State, this, this, SyntaxNodeKey.Empty); } } public EnvDTE.ProjectItem Parent { get { return _parentHandle.Object as EnvDTE.ProjectItem; } } public void Remove(object element) { var codeElement = ComAggregate.TryGetManagedObject<AbstractCodeElement>(element); if (codeElement == null) { codeElement = ComAggregate.TryGetManagedObject<AbstractCodeElement>(this.CodeElements.Item(element)); } if (codeElement == null) { throw new ArgumentException(ServicesVSResources.Element_is_not_valid, nameof(element)); } codeElement.Delete(); } int IVBFileCodeModelEvents.StartEdit() { try { InitializeEditor(); if (_editCount == 1) { _batchMode = true; _batchElements = new List<AbstractKeyedCodeElement>(); } return VSConstants.S_OK; } catch (Exception ex) { return Marshal.GetHRForException(ex); } } int IVBFileCodeModelEvents.EndEdit() { try { if (_editCount == 1) { List<ValueTuple<AbstractKeyedCodeElement, SyntaxPath>> elementAndPaths = null; if (_batchElements.Count > 0) { foreach (var element in _batchElements) { var node = element.LookupNode(); if (node != null) { elementAndPaths ??= new List<ValueTuple<AbstractKeyedCodeElement, SyntaxPath>>(); elementAndPaths.Add(ValueTuple.Create(element, new SyntaxPath(node))); } } } if (_batchDocument != null) { // perform expensive operations at once var newDocument = State.ThreadingContext.JoinableTaskFactory.Run(() => Simplifier.ReduceAsync(_batchDocument, Simplifier.Annotation, cancellationToken: CancellationToken.None)); _batchDocument.Project.Solution.Workspace.TryApplyChanges(newDocument.Project.Solution); // done using batch document _batchDocument = null; } // Ensure the file is prettylisted, even if we didn't make any edits CodeModelService.EnsureBufferFormatted(_invisibleEditor.TextBuffer); if (elementAndPaths != null) { foreach (var elementAndPath in elementAndPaths) { // make sure the element is there. if (_codeElementTable.TryGetValue(elementAndPath.Item1.NodeKey, out var existingElement)) { elementAndPath.Item1.ReacquireNodeKey(elementAndPath.Item2, CancellationToken.None); } // make sure existing element doesn't go away (weak reference) in the middle of // updating the node key GC.KeepAlive(existingElement); } } _batchMode = false; _batchElements = null; } return VSConstants.S_OK; } catch (Exception ex) { return Marshal.GetHRForException(ex); } finally { ReleaseEditor(); } } public void BeginBatch() { IVBFileCodeModelEvents temp = this; ErrorHandler.ThrowOnFailure(temp.StartEdit()); } public void EndBatch() { IVBFileCodeModelEvents temp = this; ErrorHandler.ThrowOnFailure(temp.EndEdit()); } public bool IsBatchOpen { get { return _batchMode && _editCount > 0; } } public EnvDTE.CodeElement ElementFromID(string id) => throw new NotImplementedException(); public EnvDTE80.vsCMParseStatus ParseStatus { get { var syntaxTree = GetSyntaxTree(); return syntaxTree.GetDiagnostics().Any(d => d.Severity == DiagnosticSeverity.Error) ? EnvDTE80.vsCMParseStatus.vsCMParseStatusError : EnvDTE80.vsCMParseStatus.vsCMParseStatusComplete; } } public void Synchronize() => FireEvents(); EnvDTE.CodeElements ICodeElementContainer<AbstractCodeElement>.GetCollection() => CodeElements; internal List<GlobalNodeKey> GetCurrentNodeKeys() { var currentNodeKeys = new List<GlobalNodeKey>(); foreach (var element in _codeElementTable.Values) { var keyedElement = ComAggregate.TryGetManagedObject<AbstractKeyedCodeElement>(element); if (keyedElement == null) { continue; } if (keyedElement.TryLookupNode(out var node)) { var nodeKey = keyedElement.NodeKey; currentNodeKeys.Add(new GlobalNodeKey(nodeKey, new SyntaxPath(node))); } } return currentNodeKeys; } internal void ResetElementKeys(List<GlobalNodeKey> globalNodeKeys) { foreach (var globalNodeKey in globalNodeKeys) { ResetElementKey(globalNodeKey); } } private void ResetElementKey(GlobalNodeKey globalNodeKey) { // Failure to find the element is not an error -- it just means the code // element didn't exist... if (_codeElementTable.TryGetValue(globalNodeKey.NodeKey, out var element)) { var keyedElement = ComAggregate.GetManagedObject<AbstractKeyedCodeElement>(element); if (keyedElement != null) { keyedElement.ReacquireNodeKey(globalNodeKey.Path, default); } } } } }
-1
dotnet/roslyn
55,430
Fix LSP semantic tokens algorithm
This PR primarily accomplishes two tasks: 1) Overhauls the existing LSP semantic tokens edits processing algorithm to align with [Razor's](https://github.com/dotnet/aspnetcore-tooling/blob/main/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/Semantic/Services/SemanticTokensEditsDiffer.cs) (shoutout to Ryan and the rest of the Razor team for writing the original 😄). The main change here is going from calculating edits per token (i.e. five ints) to per int. The updated algorithm is much more efficient than our previous algorithm, and returns less edits back to the LSP client. 2) The interpretation of Roslyn's LongestCommonSubstring algorithm, which we use to calculate raw edits, was missing a critical piece. Namely, for insertions, we need to keep track of _where_ we should be inserting into the original token set. We don't keep track of this in the existing implementation, resulting in bugs such as #54671. Resolves #54671
allisonchou
2021-08-05T06:06:43Z
2021-08-06T23:44:44Z
b9200d03a76c74d404040d44b9bbe12b1d0a8ef2
f300a818940ea1acef66c946cfa83756729d5e59
Fix LSP semantic tokens algorithm. This PR primarily accomplishes two tasks: 1) Overhauls the existing LSP semantic tokens edits processing algorithm to align with [Razor's](https://github.com/dotnet/aspnetcore-tooling/blob/main/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/Semantic/Services/SemanticTokensEditsDiffer.cs) (shoutout to Ryan and the rest of the Razor team for writing the original 😄). The main change here is going from calculating edits per token (i.e. five ints) to per int. The updated algorithm is much more efficient than our previous algorithm, and returns less edits back to the LSP client. 2) The interpretation of Roslyn's LongestCommonSubstring algorithm, which we use to calculate raw edits, was missing a critical piece. Namely, for insertions, we need to keep track of _where_ we should be inserting into the original token set. We don't keep track of this in the existing implementation, resulting in bugs such as #54671. Resolves #54671
./src/VisualStudio/IntegrationTest/IntegrationTests/CSharp/CSharpAddMissingReference.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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 System.Xml.Linq; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.VisualStudio.IntegrationTest.Utilities; using Roslyn.Test.Utilities; using Xunit; using Xunit.Abstractions; using ProjectUtils = Microsoft.VisualStudio.IntegrationTest.Utilities.Common.ProjectUtils; namespace Roslyn.VisualStudio.IntegrationTests.CSharp { [Collection(nameof(SharedIntegrationHostFixture))] public class CSharpAddMissingReference : AbstractEditorTest { private const string FileInLibraryProject1 = @"Public Class Class1 Inherits System.Windows.Forms.Form Public Sub goo() End Sub End Class Public Class class2 Public Sub goo(ByVal x As System.Windows.Forms.Form) End Sub Public Event ee As System.Windows.Forms.ColumnClickEventHandler End Class Public Class class3 Implements System.Windows.Forms.IButtonControl Public Property DialogResult() As System.Windows.Forms.DialogResult Implements System.Windows.Forms.IButtonControl.DialogResult Get End Get Set(ByVal Value As System.Windows.Forms.DialogResult) End Set End Property Public Sub NotifyDefault(ByVal value As Boolean) Implements System.Windows.Forms.IButtonControl.NotifyDefault End Sub Public Sub PerformClick() Implements System.Windows.Forms.IButtonControl.PerformClick End Sub End Class "; private const string FileInLibraryProject2 = @"Public Class Class1 Inherits System.Xml.XmlAttribute Sub New() MyBase.New(Nothing, Nothing, Nothing, Nothing) End Sub Sub goo() End Sub Public bar As ClassLibrary3.Class1 End Class "; private const string FileInLibraryProject3 = @"Public Class Class1 Public Enum E E1 E2 End Enum Public Function Goo() As ADODB.Recordset Dim x As ADODB.Recordset = Nothing Return x End Function End Class "; private const string FileInConsoleProject1 = @" class Program { static void Main(string[] args) { var y = new ClassLibrary1.class2(); y.goo(null); y.ee += (_, __) => { }; var x = new ClassLibrary1.Class1(); ClassLibrary1.class3 z = null; var a = new ClassLibrary2.Class1(); var d = a.bar; } } "; private const string ClassLibrary1Name = "ClassLibrary1"; private const string ClassLibrary2Name = "ClassLibrary2"; private const string ClassLibrary3Name = "ClassLibrary3"; private const string ConsoleProjectName = "ConsoleApplication1"; protected override string LanguageName => LanguageNames.CSharp; public CSharpAddMissingReference(VisualStudioInstanceFactory instanceFactory) : base(instanceFactory) { } public override async Task InitializeAsync() { await base.InitializeAsync().ConfigureAwait(true); VisualStudio.SolutionExplorer.CreateSolution("ReferenceErrors", solutionElement: XElement.Parse( "<Solution>" + $" <Project ProjectName=\"{ClassLibrary1Name}\" ProjectTemplate=\"{WellKnownProjectTemplates.WinFormsApplication}\" Language=\"{LanguageNames.VisualBasic}\">" + " <Document FileName=\"Class1.vb\"><![CDATA[" + FileInLibraryProject1 + "]]>" + " </Document>" + " </Project>" + $" <Project ProjectName=\"{ClassLibrary2Name}\" ProjectReferences=\"{ClassLibrary3Name}\" ProjectTemplate=\"{WellKnownProjectTemplates.ClassLibrary}\" Language=\"{LanguageNames.VisualBasic}\">" + " <Document FileName=\"Class1.vb\"><![CDATA[" + FileInLibraryProject2 + "]]>" + " </Document>" + " </Project>" + $" <Project ProjectName=\"{ClassLibrary3Name}\" ProjectTemplate=\"{WellKnownProjectTemplates.ClassLibrary}\" Language=\"{LanguageNames.VisualBasic}\">" + " <Document FileName=\"Class1.vb\"><![CDATA[" + FileInLibraryProject3 + "]]>" + " </Document>" + " </Project>" + $" <Project ProjectName=\"{ConsoleProjectName}\" ProjectReferences=\"{ClassLibrary1Name};{ClassLibrary2Name}\" ProjectTemplate=\"{WellKnownProjectTemplates.ConsoleApplication}\" Language=\"{LanguageNames.CSharp}\">" + " <Document FileName=\"Program.cs\"><![CDATA[" + FileInConsoleProject1 + "]]>" + " </Document>" + " </Project>" + "</Solution>")); } [WpfFact, Trait(Traits.Feature, Traits.Features.AddMissingReference)] public void VerifyAvailableCodeActions() { var consoleProject = new ProjectUtils.Project(ConsoleProjectName); VisualStudio.SolutionExplorer.OpenFile(consoleProject, "Program.cs"); VisualStudio.Editor.PlaceCaret("y.goo", charsOffset: 1); VisualStudio.Editor.InvokeCodeActionList(); VisualStudio.Editor.Verify.CodeAction("Add reference to 'System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'.", applyFix: false); VisualStudio.Editor.PlaceCaret("y.ee", charsOffset: 1); VisualStudio.Editor.InvokeCodeActionList(); VisualStudio.Editor.Verify.CodeAction("Add reference to 'System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'.", applyFix: false); VisualStudio.Editor.PlaceCaret("a.bar", charsOffset: 1); VisualStudio.Editor.InvokeCodeActionList(); VisualStudio.Editor.Verify.CodeAction("Add project reference to 'ClassLibrary3'.", applyFix: false); } [WpfFact, Trait(Traits.Feature, Traits.Features.AddMissingReference)] public void InvokeSomeFixesInCSharpThenVerifyReferences() { var consoleProject = new ProjectUtils.Project(ConsoleProjectName); VisualStudio.SolutionExplorer.OpenFile(consoleProject, "Program.cs"); VisualStudio.Editor.PlaceCaret("y.goo", charsOffset: 1); VisualStudio.Editor.InvokeCodeActionList(); VisualStudio.Editor.Verify.CodeAction("Add reference to 'System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'.", applyFix: true); VisualStudio.SolutionExplorer.Verify.AssemblyReferencePresent( project: consoleProject, assemblyName: "System.Windows.Forms", assemblyVersion: "4.0.0.0", assemblyPublicKeyToken: "b77a5c561934e089"); VisualStudio.Editor.PlaceCaret("a.bar", charsOffset: 1); VisualStudio.Editor.InvokeCodeActionList(); VisualStudio.Editor.Verify.CodeAction("Add project reference to 'ClassLibrary3'.", applyFix: true); VisualStudio.SolutionExplorer.Verify.ProjectReferencePresent( project: consoleProject, referencedProjectName: ClassLibrary3Name); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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 System.Xml.Linq; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.VisualStudio.IntegrationTest.Utilities; using Roslyn.Test.Utilities; using Xunit; using Xunit.Abstractions; using ProjectUtils = Microsoft.VisualStudio.IntegrationTest.Utilities.Common.ProjectUtils; namespace Roslyn.VisualStudio.IntegrationTests.CSharp { [Collection(nameof(SharedIntegrationHostFixture))] public class CSharpAddMissingReference : AbstractEditorTest { private const string FileInLibraryProject1 = @"Public Class Class1 Inherits System.Windows.Forms.Form Public Sub goo() End Sub End Class Public Class class2 Public Sub goo(ByVal x As System.Windows.Forms.Form) End Sub Public Event ee As System.Windows.Forms.ColumnClickEventHandler End Class Public Class class3 Implements System.Windows.Forms.IButtonControl Public Property DialogResult() As System.Windows.Forms.DialogResult Implements System.Windows.Forms.IButtonControl.DialogResult Get End Get Set(ByVal Value As System.Windows.Forms.DialogResult) End Set End Property Public Sub NotifyDefault(ByVal value As Boolean) Implements System.Windows.Forms.IButtonControl.NotifyDefault End Sub Public Sub PerformClick() Implements System.Windows.Forms.IButtonControl.PerformClick End Sub End Class "; private const string FileInLibraryProject2 = @"Public Class Class1 Inherits System.Xml.XmlAttribute Sub New() MyBase.New(Nothing, Nothing, Nothing, Nothing) End Sub Sub goo() End Sub Public bar As ClassLibrary3.Class1 End Class "; private const string FileInLibraryProject3 = @"Public Class Class1 Public Enum E E1 E2 End Enum Public Function Goo() As ADODB.Recordset Dim x As ADODB.Recordset = Nothing Return x End Function End Class "; private const string FileInConsoleProject1 = @" class Program { static void Main(string[] args) { var y = new ClassLibrary1.class2(); y.goo(null); y.ee += (_, __) => { }; var x = new ClassLibrary1.Class1(); ClassLibrary1.class3 z = null; var a = new ClassLibrary2.Class1(); var d = a.bar; } } "; private const string ClassLibrary1Name = "ClassLibrary1"; private const string ClassLibrary2Name = "ClassLibrary2"; private const string ClassLibrary3Name = "ClassLibrary3"; private const string ConsoleProjectName = "ConsoleApplication1"; protected override string LanguageName => LanguageNames.CSharp; public CSharpAddMissingReference(VisualStudioInstanceFactory instanceFactory) : base(instanceFactory) { } public override async Task InitializeAsync() { await base.InitializeAsync().ConfigureAwait(true); VisualStudio.SolutionExplorer.CreateSolution("ReferenceErrors", solutionElement: XElement.Parse( "<Solution>" + $" <Project ProjectName=\"{ClassLibrary1Name}\" ProjectTemplate=\"{WellKnownProjectTemplates.WinFormsApplication}\" Language=\"{LanguageNames.VisualBasic}\">" + " <Document FileName=\"Class1.vb\"><![CDATA[" + FileInLibraryProject1 + "]]>" + " </Document>" + " </Project>" + $" <Project ProjectName=\"{ClassLibrary2Name}\" ProjectReferences=\"{ClassLibrary3Name}\" ProjectTemplate=\"{WellKnownProjectTemplates.ClassLibrary}\" Language=\"{LanguageNames.VisualBasic}\">" + " <Document FileName=\"Class1.vb\"><![CDATA[" + FileInLibraryProject2 + "]]>" + " </Document>" + " </Project>" + $" <Project ProjectName=\"{ClassLibrary3Name}\" ProjectTemplate=\"{WellKnownProjectTemplates.ClassLibrary}\" Language=\"{LanguageNames.VisualBasic}\">" + " <Document FileName=\"Class1.vb\"><![CDATA[" + FileInLibraryProject3 + "]]>" + " </Document>" + " </Project>" + $" <Project ProjectName=\"{ConsoleProjectName}\" ProjectReferences=\"{ClassLibrary1Name};{ClassLibrary2Name}\" ProjectTemplate=\"{WellKnownProjectTemplates.ConsoleApplication}\" Language=\"{LanguageNames.CSharp}\">" + " <Document FileName=\"Program.cs\"><![CDATA[" + FileInConsoleProject1 + "]]>" + " </Document>" + " </Project>" + "</Solution>")); } [WpfFact, Trait(Traits.Feature, Traits.Features.AddMissingReference)] public void VerifyAvailableCodeActions() { var consoleProject = new ProjectUtils.Project(ConsoleProjectName); VisualStudio.SolutionExplorer.OpenFile(consoleProject, "Program.cs"); VisualStudio.Editor.PlaceCaret("y.goo", charsOffset: 1); VisualStudio.Editor.InvokeCodeActionList(); VisualStudio.Editor.Verify.CodeAction("Add reference to 'System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'.", applyFix: false); VisualStudio.Editor.PlaceCaret("y.ee", charsOffset: 1); VisualStudio.Editor.InvokeCodeActionList(); VisualStudio.Editor.Verify.CodeAction("Add reference to 'System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'.", applyFix: false); VisualStudio.Editor.PlaceCaret("a.bar", charsOffset: 1); VisualStudio.Editor.InvokeCodeActionList(); VisualStudio.Editor.Verify.CodeAction("Add project reference to 'ClassLibrary3'.", applyFix: false); } [WpfFact, Trait(Traits.Feature, Traits.Features.AddMissingReference)] public void InvokeSomeFixesInCSharpThenVerifyReferences() { var consoleProject = new ProjectUtils.Project(ConsoleProjectName); VisualStudio.SolutionExplorer.OpenFile(consoleProject, "Program.cs"); VisualStudio.Editor.PlaceCaret("y.goo", charsOffset: 1); VisualStudio.Editor.InvokeCodeActionList(); VisualStudio.Editor.Verify.CodeAction("Add reference to 'System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'.", applyFix: true); VisualStudio.SolutionExplorer.Verify.AssemblyReferencePresent( project: consoleProject, assemblyName: "System.Windows.Forms", assemblyVersion: "4.0.0.0", assemblyPublicKeyToken: "b77a5c561934e089"); VisualStudio.Editor.PlaceCaret("a.bar", charsOffset: 1); VisualStudio.Editor.InvokeCodeActionList(); VisualStudio.Editor.Verify.CodeAction("Add project reference to 'ClassLibrary3'.", applyFix: true); VisualStudio.SolutionExplorer.Verify.ProjectReferencePresent( project: consoleProject, referencedProjectName: ClassLibrary3Name); } } }
-1
dotnet/roslyn
55,430
Fix LSP semantic tokens algorithm
This PR primarily accomplishes two tasks: 1) Overhauls the existing LSP semantic tokens edits processing algorithm to align with [Razor's](https://github.com/dotnet/aspnetcore-tooling/blob/main/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/Semantic/Services/SemanticTokensEditsDiffer.cs) (shoutout to Ryan and the rest of the Razor team for writing the original 😄). The main change here is going from calculating edits per token (i.e. five ints) to per int. The updated algorithm is much more efficient than our previous algorithm, and returns less edits back to the LSP client. 2) The interpretation of Roslyn's LongestCommonSubstring algorithm, which we use to calculate raw edits, was missing a critical piece. Namely, for insertions, we need to keep track of _where_ we should be inserting into the original token set. We don't keep track of this in the existing implementation, resulting in bugs such as #54671. Resolves #54671
allisonchou
2021-08-05T06:06:43Z
2021-08-06T23:44:44Z
b9200d03a76c74d404040d44b9bbe12b1d0a8ef2
f300a818940ea1acef66c946cfa83756729d5e59
Fix LSP semantic tokens algorithm. This PR primarily accomplishes two tasks: 1) Overhauls the existing LSP semantic tokens edits processing algorithm to align with [Razor's](https://github.com/dotnet/aspnetcore-tooling/blob/main/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/Semantic/Services/SemanticTokensEditsDiffer.cs) (shoutout to Ryan and the rest of the Razor team for writing the original 😄). The main change here is going from calculating edits per token (i.e. five ints) to per int. The updated algorithm is much more efficient than our previous algorithm, and returns less edits back to the LSP client. 2) The interpretation of Roslyn's LongestCommonSubstring algorithm, which we use to calculate raw edits, was missing a critical piece. Namely, for insertions, we need to keep track of _where_ we should be inserting into the original token set. We don't keep track of this in the existing implementation, resulting in bugs such as #54671. Resolves #54671
./src/EditorFeatures/CSharpTest/ConvertForToForEach/ConvertForToForEachTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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; using Microsoft.CodeAnalysis.CSharp.CodeStyle; using Microsoft.CodeAnalysis.CSharp.ConvertForToForEach; 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.ConvertForToForEach { public class ConvertForToForEachTests : AbstractCSharpCodeActionTest { protected override CodeRefactoringProvider CreateCodeRefactoringProvider(Workspace workspace, TestParameters parameters) => new CSharpConvertForToForEachCodeRefactoringProvider(); private readonly CodeStyleOption2<bool> onWithSilent = new CodeStyleOption2<bool>(true, NotificationOption2.Silent); private OptionsCollection ImplicitTypeEverywhere() => new OptionsCollection(GetLanguage()) { { CSharpCodeStyleOptions.VarElsewhere, onWithSilent }, { CSharpCodeStyleOptions.VarWhenTypeIsApparent, onWithSilent }, { CSharpCodeStyleOptions.VarForBuiltInTypes, onWithSilent }, }; [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForToForEach)] public async Task TestArray1() { await TestInRegularAndScript1Async( @"using System; class C { void Test(string[] array) { [||]for (int i = 0; i < array.Length; i++) { Console.WriteLine(array[i]); } } }", @"using System; class C { void Test(string[] array) { foreach (string {|Rename:v|} in array) { Console.WriteLine(v); } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForToForEach)] public async Task TestWarnIfCrossesFunctionBoundary() { await TestInRegularAndScript1Async( @"using System; class C { void Test(string[] array) { [||]for (int i = 0; i < array.Length; i++) { Action a = () => { Console.WriteLine(array[i]); }; } } }", @"using System; class C { void Test(string[] array) { foreach (string {|Rename:v|} in array) { Action a = () => { Console.WriteLine({|Warning:v|}); }; } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForToForEach)] public async Task TestWarnIfCollectionPotentiallyMutated1() { await TestInRegularAndScript1Async( @"using System; using System.Collections.Generic; class C { void Test(IList<string> list) { [||]for (int i = 0; i < list.Count; i++) { Console.WriteLine(list[i]); list.Add(null); } } }", @"using System; using System.Collections.Generic; class C { void Test(IList<string> list) { foreach (string {|Rename:v|} in list) { Console.WriteLine(v); {|Warning:list|}.Add(null); } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForToForEach)] public async Task TestWarnIfCollectionPotentiallyMutated2() { await TestInRegularAndScript1Async( @"using System; using System.Collections.Generic; class C { void Test(IList<string> list) { [||]for (int i = 0; i < list.Count; i++) { Console.WriteLine(list[i]); list = null; } } }", @"using System; using System.Collections.Generic; class C { void Test(IList<string> list) { foreach (string {|Rename:v|} in list) { Console.WriteLine(v); {|Warning:list|} = null; } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForToForEach)] public async Task TestNoWarnIfCollectionPropertyAccess() { await TestInRegularAndScript1Async( @"using System; using System.Collections.Generic; class C { void Test(IList<string> list) { [||]for (int i = 0; i < list.Count; i++) { Console.WriteLine(list[i]); Console.WriteLine(list.Count); } } }", @"using System; using System.Collections.Generic; class C { void Test(IList<string> list) { foreach (string {|Rename:v|} in list) { Console.WriteLine(v); Console.WriteLine(list.Count); } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForToForEach)] public async Task TestNoWarnIfDoesNotCrossFunctionBoundary() { await TestInRegularAndScript1Async( @"using System; class C { void Test(string[] array) { Action a = () => { [||]for (int i = 0; i < array.Length; i++) { Console.WriteLine(array[i]); } }; } }", @"using System; class C { void Test(string[] array) { Action a = () => { foreach (string {|Rename:v|} in array) { Console.WriteLine(v); } }; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForToForEach)] public async Task TestMultipleReferences() { await TestInRegularAndScript1Async( @"using System; class C { void Test(string[] array) { [||]for (int i = 0; i < array.Length; i++) { Console.WriteLine(array[i]); Console.WriteLine(array[i]); } } }", @"using System; class C { void Test(string[] array) { foreach (string {|Rename:v|} in array) { Console.WriteLine(v); Console.WriteLine(v); } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForToForEach)] public async Task TestEmbeddedStatement() { await TestInRegularAndScript1Async( @"using System; class C { void Test(string[] array) { [||]for (int i = 0; i < array.Length; i++) Console.WriteLine(array[i]); } }", @"using System; class C { void Test(string[] array) { foreach (string {|Rename:v|} in array) Console.WriteLine(v); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForToForEach)] public async Task TestPostIncrement() { await TestInRegularAndScript1Async( @"using System; class C { void Test(string[] array) { [||]for (int i = 0; i < array.Length; ++i) { Console.WriteLine(array[i]); } } }", @"using System; class C { void Test(string[] array) { foreach (string {|Rename:v|} in array) { Console.WriteLine(v); } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForToForEach)] public async Task TestArrayPlusEqualsIncrementor() { await TestInRegularAndScript1Async( @"using System; class C { void Test(string[] array) { [||]for (int i = 0; i < array.Length; i += 1) { Console.WriteLine(array[i]); } } }", @"using System; class C { void Test(string[] array) { foreach (string {|Rename:v|} in array) { Console.WriteLine(v); } } }"); } [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForToForEach)] public async Task TestBeforeKeyword() { await TestInRegularAndScript1Async( @"using System; class C { void Test(string[] array) { [||] for (int i = 0; i < array.Length; i++) { Console.WriteLine(array[i]); } } }", @"using System; class C { void Test(string[] array) { foreach (string {|Rename:v|} in array) { Console.WriteLine(v); } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForToForEach)] public async Task TestMissingAfterOpenParen() { await TestMissingInRegularAndScriptAsync( @"using System; class C { void Test(string[] array) { for ( [||]int i = 0; i < array.Length; i++) { Console.WriteLine(array[i]); } } }"); } [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForToForEach)] public async Task TestInParentheses() { await TestInRegularAndScript1Async( @"using System; class C { void Test(string[] array) { for ([||]int i = 0; i < array.Length; i++) { Console.WriteLine(array[i]); } } }", @"using System; class C { void Test(string[] array) { foreach (string {|Rename:v|} in array) { Console.WriteLine(v); } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForToForEach)] public async Task TestMissingBeforeCloseParen() { await TestMissingInRegularAndScriptAsync( @"using System; class C { void Test(string[] array) { for (int i = 0; i < array.Length; i++[||] ) { Console.WriteLine(array[i]); } } }"); } [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForToForEach)] public async Task TestInParentheses2() { await TestInRegularAndScript1Async( @"using System; class C { void Test(string[] array) { for (int i = 0; i < array.Length; i++[||]) { Console.WriteLine(array[i]); } } }", @"using System; class C { void Test(string[] array) { foreach (string {|Rename:v|} in array) { Console.WriteLine(v); } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForToForEach)] public async Task TestAtEndOfFor() { await TestInRegularAndScript1Async( @"using System; class C { void Test(string[] array) { for[||] (int i = 0; i < array.Length; i++) { Console.WriteLine(array[i]); } } }", @"using System; class C { void Test(string[] array) { foreach (string {|Rename:v|} in array) { Console.WriteLine(v); } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForToForEach)] public async Task TestForSelected() { await TestInRegularAndScript1Async( @"using System; class C { void Test(string[] array) { [|for|] (int i = 0; i < array.Length; i++) { Console.WriteLine(array[i]); } } }", @"using System; class C { void Test(string[] array) { foreach (string {|Rename:v|} in array) { Console.WriteLine(v); } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForToForEach)] public async Task TestBeforeOpenParen() { await TestInRegularAndScript1Async( @"using System; class C { void Test(string[] array) { for [||](int i = 0; i < array.Length; i++) { Console.WriteLine(array[i]); } } }", @"using System; class C { void Test(string[] array) { foreach (string {|Rename:v|} in array) { Console.WriteLine(v); } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForToForEach)] public async Task TestAfterCloseParen() { await TestInRegularAndScript1Async( @"using System; class C { void Test(string[] array) { for (int i = 0; i < array.Length; i++)[||] { Console.WriteLine(array[i]); } } }", @"using System; class C { void Test(string[] array) { foreach (string {|Rename:v|} in array) { Console.WriteLine(v); } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForToForEach)] public async Task TestMissingWithoutIncrementor() { await TestMissingInRegularAndScriptAsync( @"using System; class C { void Test(string[] array) { [||]for (int i = 0; i < array.Length; ) { Console.WriteLine(array[i]); } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForToForEach)] public async Task TestMissingWithoutIncorrectIncrementor1() { await TestMissingInRegularAndScriptAsync( @"using System; class C { void Test(string[] array) { [||]for (int i = 0; i < array.Length; i += 2) { Console.WriteLine(array[i]); } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForToForEach)] public async Task TestMissingWithoutIncorrectIncrementor2() { await TestMissingInRegularAndScriptAsync( @"using System; class C { void Test(string[] array) { [||]for (int i = 0; i < array.Length; j += 2) { Console.WriteLine(array[i]); } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForToForEach)] public async Task TestMissingWithoutCondition() { await TestMissingInRegularAndScriptAsync( @"using System; class C { void Test(string[] array) { [||]for (int i = 0; ; i++) { Console.WriteLine(array[i]); } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForToForEach)] public async Task TestMissingWithIncorrectCondition1() { await TestMissingInRegularAndScriptAsync( @"using System; class C { void Test(string[] array) { [||]for (int i = 0; j < array.Length; i++) { Console.WriteLine(array[i]); } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForToForEach)] public async Task TestMissingWithIncorrectCondition2() { await TestMissingInRegularAndScriptAsync( @"using System; class C { void Test(string[] array) { [||]for (int i = 0; i < GetLength(array); i++) { Console.WriteLine(array[i]); } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForToForEach)] public async Task TestWithoutInitializer() { await TestMissingInRegularAndScriptAsync( @"using System; class C { void Test(string[] array) { [||]for (; i < array.Length; i++) { Console.WriteLine(array[i]); } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForToForEach)] public async Task TestWithInitializerOfVariableOutsideLoop() { await TestMissingInRegularAndScriptAsync( @"using System; class C { void Test(string[] array) { int i; [||]for (i = 0; i < array.Length; i++) { Console.WriteLine(array[i]); } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForToForEach)] public async Task TestWithUninitializedVariable() { await TestMissingInRegularAndScriptAsync( @"using System; class C { void Test(string[] array) { [||]for (int i; i < array.Length; i++) { Console.WriteLine(array[i]); } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForToForEach)] public async Task TestNotStartingAtZero() { await TestMissingInRegularAndScriptAsync( @"using System; class C { void Test(string[] array) { [||]for (int i = 1; i < array.Length; i++) { Console.WriteLine(array[i]); } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForToForEach)] public async Task TestWithMultipleVariables() { await TestMissingInRegularAndScriptAsync( @"using System; class C { void Test(string[] array) { [||]for (int i = 0, j = 0; i < array.Length; i++) { Console.WriteLine(array[i]); } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForToForEach)] public async Task TestList1() { await TestInRegularAndScript1Async( @"using System; using System.Collections.Generic; class C { void Test(IList<string> list) { [||]for (int i = 0; i < list.Count; i++) { Console.WriteLine(list[i]); } } }", @"using System; using System.Collections.Generic; class C { void Test(IList<string> list) { foreach (string {|Rename:v|} in list) { Console.WriteLine(v); } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForToForEach)] public async Task TestChooseNameFromDeclarationStatement() { await TestInRegularAndScript1Async( @"using System; using System.Collections.Generic; class C { void Test(IList<string> list) { [||]for (int i = 0; i < list.Count; i++) { var val = list[i]; Console.WriteLine(list[i]); } } }", @"using System; using System.Collections.Generic; class C { void Test(IList<string> list) { foreach (var val in list) { Console.WriteLine(val); } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForToForEach)] public async Task TestIgnoreFormattingForReferences() { await TestInRegularAndScript1Async( @"using System; using System.Collections.Generic; class C { void Test(IList<string> list) { [||]for (int i = 0; i < list.Count; i++) { var val = list [ i ]; Console.WriteLine(list [ /*find me*/ i ]); } } }", @"using System; using System.Collections.Generic; class C { void Test(IList<string> list) { foreach (var val in list) { Console.WriteLine(val); } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForToForEach)] public async Task TestChooseNameFromDeclarationStatement_PreserveComments() { await TestInRegularAndScript1Async( @"using System; using System.Collections.Generic; class C { void Test(IList<string> list) { [||]for (int i = 0; i < list.Count; i++) { // loop comment var val = list[i]; Console.WriteLine(list[i]); } } }", @"using System; using System.Collections.Generic; class C { void Test(IList<string> list) { foreach (var val in list) { // loop comment Console.WriteLine(val); } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForToForEach)] public async Task TestChooseNameFromDeclarationStatement_PreserveDirectives() { await TestInRegularAndScript1Async( @"using System; using System.Collections.Generic; class C { void Test(IList<string> list) { [||]for (int i = 0; i < list.Count; i++) { #if true var val = list[i]; Console.WriteLine(list[i]); #endif } } }", @"using System; using System.Collections.Generic; class C { void Test(IList<string> list) { foreach (var val in list) { #if true Console.WriteLine(val); #endif } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForToForEach)] public async Task TestMissingIfVariableUsedNotForIndexing() { await TestMissingInRegularAndScriptAsync( @"using System; class C { void Test(string[] array) { [||]for (int i = 0; i < array.Length; i++) { Console.WriteLine(i); } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForToForEach)] public async Task TestMissingIfVariableUsedForIndexingNonCollection() { await TestMissingInRegularAndScriptAsync( @"using System; class C { void Test(string[] array) { [||]for (int i = 0; i < array.Length; i++) { Console.WriteLine(other[i]); } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForToForEach)] public async Task TestWarningIfCollectionWrittenTo() { await TestInRegularAndScript1Async( @"using System; class C { void Test(string[] array) { [||]for (int i = 0; i < array.Length; i++) { array[i] = 1; } } }", @"using System; class C { void Test(string[] array) { foreach (string {|Rename:v|} in array) { {|Warning:v|} = 1; } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForToForEach)] public async Task UseVarIfPreferred1() { await TestInRegularAndScriptAsync( @"using System; class C { void Test(string[] array) { [||]for (int i = 0; i < array.Length; i++) { Console.WriteLine(array[i]); } } }", @"using System; class C { void Test(string[] array) { foreach (var {|Rename:v|} in array) { Console.WriteLine(v); } } }", options: ImplicitTypeEverywhere()); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForToForEach)] public async Task TestDifferentIndexerAndEnumeratorType() { await TestInRegularAndScriptAsync( @"using System; class MyList { public string this[int i] { get; } public Enumerator GetEnumerator() { } public struct Enumerator { public object Current { get; } } } class C { void Test(MyList list) { // need to use 'string' here to preserve original index semantics. [||]for (int i = 0; i < list.Length; i++) { Console.WriteLine(list[i]); } } }", @"using System; class MyList { public string this[int i] { get; } public Enumerator GetEnumerator() { } public struct Enumerator { public object Current { get; } } } class C { void Test(MyList list) { // need to use 'string' here to preserve original index semantics. foreach (string {|Rename:v|} in list) { Console.WriteLine(v); } } }", options: ImplicitTypeEverywhere()); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForToForEach)] public async Task TestSameIndexerAndEnumeratorType() { await TestInRegularAndScriptAsync( @"using System; class MyList { public object this[int i] { get => default; } public Enumerator GetEnumerator() { return default; } public struct Enumerator { public object Current { get; } public bool MoveNext() => true; } } class C { void Test(MyList list) { // can use 'var' here since hte type stayed the same. [||]for (int i = 0; i < list.Length; i++) { Console.WriteLine(list[i]); } } }", @"using System; class MyList { public object this[int i] { get => default; } public Enumerator GetEnumerator() { return default; } public struct Enumerator { public object Current { get; } public bool MoveNext() => true; } } class C { void Test(MyList list) { // can use 'var' here since hte type stayed the same. foreach (var {|Rename:v|} in list) { Console.WriteLine(v); } } }", options: ImplicitTypeEverywhere()); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForToForEach)] public async Task TestTrivia() { await TestInRegularAndScript1Async( @"using System; class C { void Test(string[] array) { // trivia 1 [||]for /*trivia 2*/ ( /*trivia 3*/ int i = 0; i < array.Length; i++) /*trivia 4*/ // trivia 5 { Console.WriteLine(array[i]); } // trivia 6 } }", @"using System; class C { void Test(string[] array) { // trivia 1 foreach /*trivia 2*/ ( /*trivia 3*/ string {|Rename:v|} in array) /*trivia 4*/ // trivia 5 { Console.WriteLine(v); } // trivia 6 } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForToForEach)] public async Task TestNotWithDeconstruction() { await TestMissingInRegularAndScriptAsync( @"using System; class C { void Test(string[] array) { [||]for (var (i, j) = (0, 0); i < array.Length; i++) { Console.WriteLine(array[i]); } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForToForEach)] public async Task TestMultidimensionalArray1() { await TestMissingInRegularAndScriptAsync( @"using System; class C { void Test(string[,] array) { [||]for (int i = 0; i < array.Length; i++) { Console.WriteLine(array[i, 0]); } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForToForEach)] public async Task TestMultidimensionalArray2() { await TestMissingInRegularAndScriptAsync( @"using System; class C { void Test(string[,] array) { [||]for (int i = 0; i < array.Length; i++) { Console.WriteLine(array[i, i]); } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForToForEach)] public async Task TestJaggedArray1() { await TestInRegularAndScript1Async( @"using System; class C { void Test(string[][] array) { [||]for (int i = 0; i < array.Length; i++) { Console.WriteLine(array[i]); } } }", @"using System; class C { void Test(string[][] array) { foreach (string[] {|Rename:v|} in array) { Console.WriteLine(v); } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForToForEach)] public async Task TestJaggedArray2() { await TestInRegularAndScript1Async( @"using System; class C { void Test(string[][] array) { [||]for (int i = 0; i < array.Length; i++) { Console.WriteLine(array[i][0]); } } }", @"using System; class C { void Test(string[][] array) { foreach (string[] {|Rename:v|} in array) { Console.WriteLine(v[0]); } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForToForEach)] public async Task TestJaggedArray3() { await TestInRegularAndScript1Async( @"using System; class C { void Test(string[][] array) { [||]for (int i = 0; i < array.Length; i++) { var subArray = array[i]; for (int j = 0; j < subArray.Length; j++) { Console.WriteLine(array[i][j]); } } } }", @"using System; class C { void Test(string[][] array) { foreach (var subArray in array) { for (int j = 0; j < subArray.Length; j++) { Console.WriteLine(subArray[j]); } } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForToForEach)] public async Task TestJaggedArray4() { await TestInRegularAndScript1Async( @"using System; class C { void Test(string[][] array) { [||]for (int i = 0; i < array.Length; i++) { for (int j = 0; j < array[i].Length; j++) { Console.WriteLine(array[i][j]); } } } }", @"using System; class C { void Test(string[][] array) { foreach (string[] {|Rename:v|} in array) { for (int j = 0; j < v.Length; j++) { Console.WriteLine(v[j]); } } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForToForEach)] public async Task TestJaggedArray5() { await TestInRegularAndScript1Async( @"using System; class C { void Test(string[][] array) { for (int i = 0; i < array.Length; i++) { [||]for (int j = 0; j < array[i].Length; j++) { Console.WriteLine(array[i][j]); } } } }", @"using System; class C { void Test(string[][] array) { for (int i = 0; i < array.Length; i++) { foreach (string {|Rename:v|} in array[i]) { Console.WriteLine(v); } } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForToForEach)] public async Task TestJaggedArray6() { await TestMissingInRegularAndScriptAsync( @"using System; class C { void Test(string[][] array) { [||]for (int i = 0; i < array.Length; i++) { Console.WriteLine(array[i][i]); } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForToForEach)] public async Task TestDoesNotUseLocalFunctionName() { await TestInRegularAndScript1Async( @"using System; class C { void Test(string[] array) { [||]for (int i = 0; i < array.Length; i++) { Console.WriteLine(array[i]); } void v() { } } }", @"using System; class C { void Test(string[] array) { foreach (string {|Rename:v1|} in array) { Console.WriteLine(v1); } void v() { } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForToForEach)] public async Task TestUsesLocalFunctionParameterName() { await TestInRegularAndScript1Async( @"using System; class C { void Test(string[] array) { [||]for (int i = 0; i < array.Length; i++) { Console.WriteLine(array[i]); } void M(string v) { } } }", @"using System; class C { void Test(string[] array) { foreach (string {|Rename:v|} in array) { Console.WriteLine(v); } void M(string v) { } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForToForEach)] public async Task TestDoesNotUseLambdaParameterWithCSharpLessThan8() { await TestInRegularAndScript1Async( @"using System; class C { void Test(string[] array) { [||]for (int i = 0; i < array.Length; i++) { Console.WriteLine(array[i]); } Action<int> myLambda = v => { }; } }", @"using System; class C { void Test(string[] array) { foreach (string {|Rename:v1|} in array) { Console.WriteLine(v1); } Action<int> myLambda = v => { }; } }", parameters: new TestParameters(new CSharpParseOptions(LanguageVersion.CSharp7_3))); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForToForEach)] public async Task TestUsesLambdaParameterNameInCSharp8() { await TestInRegularAndScript1Async( @"using System; class C { void Test(string[] array) { [||]for (int i = 0; i < array.Length; i++) { Console.WriteLine(array[i]); } Action<int> myLambda = v => { }; } }", @"using System; class C { void Test(string[] array) { foreach (string {|Rename:v|} in array) { Console.WriteLine(v); } Action<int> myLambda = v => { }; } }", parameters: new TestParameters(new CSharpParseOptions(LanguageVersion.CSharp8))); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForToForEach)] public async Task TestNotWhenIteratingDifferentLists() { await TestMissingAsync( @"using System; using System.Collection.Generic; class Item { public string Value; } class C { static void Test() { var first = new { list = new List<Item>() }; var second = new { list = new List<Item>() }; [||]for (var i = 0; i < first.list.Count; i++) { first.list[i].Value = second.list[i].Value; } } }"); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeRefactorings; using Microsoft.CodeAnalysis.CodeStyle; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.CodeStyle; using Microsoft.CodeAnalysis.CSharp.ConvertForToForEach; 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.ConvertForToForEach { public class ConvertForToForEachTests : AbstractCSharpCodeActionTest { protected override CodeRefactoringProvider CreateCodeRefactoringProvider(Workspace workspace, TestParameters parameters) => new CSharpConvertForToForEachCodeRefactoringProvider(); private readonly CodeStyleOption2<bool> onWithSilent = new CodeStyleOption2<bool>(true, NotificationOption2.Silent); private OptionsCollection ImplicitTypeEverywhere() => new OptionsCollection(GetLanguage()) { { CSharpCodeStyleOptions.VarElsewhere, onWithSilent }, { CSharpCodeStyleOptions.VarWhenTypeIsApparent, onWithSilent }, { CSharpCodeStyleOptions.VarForBuiltInTypes, onWithSilent }, }; [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForToForEach)] public async Task TestArray1() { await TestInRegularAndScript1Async( @"using System; class C { void Test(string[] array) { [||]for (int i = 0; i < array.Length; i++) { Console.WriteLine(array[i]); } } }", @"using System; class C { void Test(string[] array) { foreach (string {|Rename:v|} in array) { Console.WriteLine(v); } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForToForEach)] public async Task TestWarnIfCrossesFunctionBoundary() { await TestInRegularAndScript1Async( @"using System; class C { void Test(string[] array) { [||]for (int i = 0; i < array.Length; i++) { Action a = () => { Console.WriteLine(array[i]); }; } } }", @"using System; class C { void Test(string[] array) { foreach (string {|Rename:v|} in array) { Action a = () => { Console.WriteLine({|Warning:v|}); }; } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForToForEach)] public async Task TestWarnIfCollectionPotentiallyMutated1() { await TestInRegularAndScript1Async( @"using System; using System.Collections.Generic; class C { void Test(IList<string> list) { [||]for (int i = 0; i < list.Count; i++) { Console.WriteLine(list[i]); list.Add(null); } } }", @"using System; using System.Collections.Generic; class C { void Test(IList<string> list) { foreach (string {|Rename:v|} in list) { Console.WriteLine(v); {|Warning:list|}.Add(null); } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForToForEach)] public async Task TestWarnIfCollectionPotentiallyMutated2() { await TestInRegularAndScript1Async( @"using System; using System.Collections.Generic; class C { void Test(IList<string> list) { [||]for (int i = 0; i < list.Count; i++) { Console.WriteLine(list[i]); list = null; } } }", @"using System; using System.Collections.Generic; class C { void Test(IList<string> list) { foreach (string {|Rename:v|} in list) { Console.WriteLine(v); {|Warning:list|} = null; } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForToForEach)] public async Task TestNoWarnIfCollectionPropertyAccess() { await TestInRegularAndScript1Async( @"using System; using System.Collections.Generic; class C { void Test(IList<string> list) { [||]for (int i = 0; i < list.Count; i++) { Console.WriteLine(list[i]); Console.WriteLine(list.Count); } } }", @"using System; using System.Collections.Generic; class C { void Test(IList<string> list) { foreach (string {|Rename:v|} in list) { Console.WriteLine(v); Console.WriteLine(list.Count); } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForToForEach)] public async Task TestNoWarnIfDoesNotCrossFunctionBoundary() { await TestInRegularAndScript1Async( @"using System; class C { void Test(string[] array) { Action a = () => { [||]for (int i = 0; i < array.Length; i++) { Console.WriteLine(array[i]); } }; } }", @"using System; class C { void Test(string[] array) { Action a = () => { foreach (string {|Rename:v|} in array) { Console.WriteLine(v); } }; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForToForEach)] public async Task TestMultipleReferences() { await TestInRegularAndScript1Async( @"using System; class C { void Test(string[] array) { [||]for (int i = 0; i < array.Length; i++) { Console.WriteLine(array[i]); Console.WriteLine(array[i]); } } }", @"using System; class C { void Test(string[] array) { foreach (string {|Rename:v|} in array) { Console.WriteLine(v); Console.WriteLine(v); } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForToForEach)] public async Task TestEmbeddedStatement() { await TestInRegularAndScript1Async( @"using System; class C { void Test(string[] array) { [||]for (int i = 0; i < array.Length; i++) Console.WriteLine(array[i]); } }", @"using System; class C { void Test(string[] array) { foreach (string {|Rename:v|} in array) Console.WriteLine(v); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForToForEach)] public async Task TestPostIncrement() { await TestInRegularAndScript1Async( @"using System; class C { void Test(string[] array) { [||]for (int i = 0; i < array.Length; ++i) { Console.WriteLine(array[i]); } } }", @"using System; class C { void Test(string[] array) { foreach (string {|Rename:v|} in array) { Console.WriteLine(v); } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForToForEach)] public async Task TestArrayPlusEqualsIncrementor() { await TestInRegularAndScript1Async( @"using System; class C { void Test(string[] array) { [||]for (int i = 0; i < array.Length; i += 1) { Console.WriteLine(array[i]); } } }", @"using System; class C { void Test(string[] array) { foreach (string {|Rename:v|} in array) { Console.WriteLine(v); } } }"); } [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForToForEach)] public async Task TestBeforeKeyword() { await TestInRegularAndScript1Async( @"using System; class C { void Test(string[] array) { [||] for (int i = 0; i < array.Length; i++) { Console.WriteLine(array[i]); } } }", @"using System; class C { void Test(string[] array) { foreach (string {|Rename:v|} in array) { Console.WriteLine(v); } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForToForEach)] public async Task TestMissingAfterOpenParen() { await TestMissingInRegularAndScriptAsync( @"using System; class C { void Test(string[] array) { for ( [||]int i = 0; i < array.Length; i++) { Console.WriteLine(array[i]); } } }"); } [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForToForEach)] public async Task TestInParentheses() { await TestInRegularAndScript1Async( @"using System; class C { void Test(string[] array) { for ([||]int i = 0; i < array.Length; i++) { Console.WriteLine(array[i]); } } }", @"using System; class C { void Test(string[] array) { foreach (string {|Rename:v|} in array) { Console.WriteLine(v); } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForToForEach)] public async Task TestMissingBeforeCloseParen() { await TestMissingInRegularAndScriptAsync( @"using System; class C { void Test(string[] array) { for (int i = 0; i < array.Length; i++[||] ) { Console.WriteLine(array[i]); } } }"); } [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForToForEach)] public async Task TestInParentheses2() { await TestInRegularAndScript1Async( @"using System; class C { void Test(string[] array) { for (int i = 0; i < array.Length; i++[||]) { Console.WriteLine(array[i]); } } }", @"using System; class C { void Test(string[] array) { foreach (string {|Rename:v|} in array) { Console.WriteLine(v); } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForToForEach)] public async Task TestAtEndOfFor() { await TestInRegularAndScript1Async( @"using System; class C { void Test(string[] array) { for[||] (int i = 0; i < array.Length; i++) { Console.WriteLine(array[i]); } } }", @"using System; class C { void Test(string[] array) { foreach (string {|Rename:v|} in array) { Console.WriteLine(v); } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForToForEach)] public async Task TestForSelected() { await TestInRegularAndScript1Async( @"using System; class C { void Test(string[] array) { [|for|] (int i = 0; i < array.Length; i++) { Console.WriteLine(array[i]); } } }", @"using System; class C { void Test(string[] array) { foreach (string {|Rename:v|} in array) { Console.WriteLine(v); } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForToForEach)] public async Task TestBeforeOpenParen() { await TestInRegularAndScript1Async( @"using System; class C { void Test(string[] array) { for [||](int i = 0; i < array.Length; i++) { Console.WriteLine(array[i]); } } }", @"using System; class C { void Test(string[] array) { foreach (string {|Rename:v|} in array) { Console.WriteLine(v); } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForToForEach)] public async Task TestAfterCloseParen() { await TestInRegularAndScript1Async( @"using System; class C { void Test(string[] array) { for (int i = 0; i < array.Length; i++)[||] { Console.WriteLine(array[i]); } } }", @"using System; class C { void Test(string[] array) { foreach (string {|Rename:v|} in array) { Console.WriteLine(v); } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForToForEach)] public async Task TestMissingWithoutIncrementor() { await TestMissingInRegularAndScriptAsync( @"using System; class C { void Test(string[] array) { [||]for (int i = 0; i < array.Length; ) { Console.WriteLine(array[i]); } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForToForEach)] public async Task TestMissingWithoutIncorrectIncrementor1() { await TestMissingInRegularAndScriptAsync( @"using System; class C { void Test(string[] array) { [||]for (int i = 0; i < array.Length; i += 2) { Console.WriteLine(array[i]); } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForToForEach)] public async Task TestMissingWithoutIncorrectIncrementor2() { await TestMissingInRegularAndScriptAsync( @"using System; class C { void Test(string[] array) { [||]for (int i = 0; i < array.Length; j += 2) { Console.WriteLine(array[i]); } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForToForEach)] public async Task TestMissingWithoutCondition() { await TestMissingInRegularAndScriptAsync( @"using System; class C { void Test(string[] array) { [||]for (int i = 0; ; i++) { Console.WriteLine(array[i]); } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForToForEach)] public async Task TestMissingWithIncorrectCondition1() { await TestMissingInRegularAndScriptAsync( @"using System; class C { void Test(string[] array) { [||]for (int i = 0; j < array.Length; i++) { Console.WriteLine(array[i]); } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForToForEach)] public async Task TestMissingWithIncorrectCondition2() { await TestMissingInRegularAndScriptAsync( @"using System; class C { void Test(string[] array) { [||]for (int i = 0; i < GetLength(array); i++) { Console.WriteLine(array[i]); } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForToForEach)] public async Task TestWithoutInitializer() { await TestMissingInRegularAndScriptAsync( @"using System; class C { void Test(string[] array) { [||]for (; i < array.Length; i++) { Console.WriteLine(array[i]); } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForToForEach)] public async Task TestWithInitializerOfVariableOutsideLoop() { await TestMissingInRegularAndScriptAsync( @"using System; class C { void Test(string[] array) { int i; [||]for (i = 0; i < array.Length; i++) { Console.WriteLine(array[i]); } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForToForEach)] public async Task TestWithUninitializedVariable() { await TestMissingInRegularAndScriptAsync( @"using System; class C { void Test(string[] array) { [||]for (int i; i < array.Length; i++) { Console.WriteLine(array[i]); } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForToForEach)] public async Task TestNotStartingAtZero() { await TestMissingInRegularAndScriptAsync( @"using System; class C { void Test(string[] array) { [||]for (int i = 1; i < array.Length; i++) { Console.WriteLine(array[i]); } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForToForEach)] public async Task TestWithMultipleVariables() { await TestMissingInRegularAndScriptAsync( @"using System; class C { void Test(string[] array) { [||]for (int i = 0, j = 0; i < array.Length; i++) { Console.WriteLine(array[i]); } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForToForEach)] public async Task TestList1() { await TestInRegularAndScript1Async( @"using System; using System.Collections.Generic; class C { void Test(IList<string> list) { [||]for (int i = 0; i < list.Count; i++) { Console.WriteLine(list[i]); } } }", @"using System; using System.Collections.Generic; class C { void Test(IList<string> list) { foreach (string {|Rename:v|} in list) { Console.WriteLine(v); } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForToForEach)] public async Task TestChooseNameFromDeclarationStatement() { await TestInRegularAndScript1Async( @"using System; using System.Collections.Generic; class C { void Test(IList<string> list) { [||]for (int i = 0; i < list.Count; i++) { var val = list[i]; Console.WriteLine(list[i]); } } }", @"using System; using System.Collections.Generic; class C { void Test(IList<string> list) { foreach (var val in list) { Console.WriteLine(val); } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForToForEach)] public async Task TestIgnoreFormattingForReferences() { await TestInRegularAndScript1Async( @"using System; using System.Collections.Generic; class C { void Test(IList<string> list) { [||]for (int i = 0; i < list.Count; i++) { var val = list [ i ]; Console.WriteLine(list [ /*find me*/ i ]); } } }", @"using System; using System.Collections.Generic; class C { void Test(IList<string> list) { foreach (var val in list) { Console.WriteLine(val); } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForToForEach)] public async Task TestChooseNameFromDeclarationStatement_PreserveComments() { await TestInRegularAndScript1Async( @"using System; using System.Collections.Generic; class C { void Test(IList<string> list) { [||]for (int i = 0; i < list.Count; i++) { // loop comment var val = list[i]; Console.WriteLine(list[i]); } } }", @"using System; using System.Collections.Generic; class C { void Test(IList<string> list) { foreach (var val in list) { // loop comment Console.WriteLine(val); } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForToForEach)] public async Task TestChooseNameFromDeclarationStatement_PreserveDirectives() { await TestInRegularAndScript1Async( @"using System; using System.Collections.Generic; class C { void Test(IList<string> list) { [||]for (int i = 0; i < list.Count; i++) { #if true var val = list[i]; Console.WriteLine(list[i]); #endif } } }", @"using System; using System.Collections.Generic; class C { void Test(IList<string> list) { foreach (var val in list) { #if true Console.WriteLine(val); #endif } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForToForEach)] public async Task TestMissingIfVariableUsedNotForIndexing() { await TestMissingInRegularAndScriptAsync( @"using System; class C { void Test(string[] array) { [||]for (int i = 0; i < array.Length; i++) { Console.WriteLine(i); } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForToForEach)] public async Task TestMissingIfVariableUsedForIndexingNonCollection() { await TestMissingInRegularAndScriptAsync( @"using System; class C { void Test(string[] array) { [||]for (int i = 0; i < array.Length; i++) { Console.WriteLine(other[i]); } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForToForEach)] public async Task TestWarningIfCollectionWrittenTo() { await TestInRegularAndScript1Async( @"using System; class C { void Test(string[] array) { [||]for (int i = 0; i < array.Length; i++) { array[i] = 1; } } }", @"using System; class C { void Test(string[] array) { foreach (string {|Rename:v|} in array) { {|Warning:v|} = 1; } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForToForEach)] public async Task UseVarIfPreferred1() { await TestInRegularAndScriptAsync( @"using System; class C { void Test(string[] array) { [||]for (int i = 0; i < array.Length; i++) { Console.WriteLine(array[i]); } } }", @"using System; class C { void Test(string[] array) { foreach (var {|Rename:v|} in array) { Console.WriteLine(v); } } }", options: ImplicitTypeEverywhere()); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForToForEach)] public async Task TestDifferentIndexerAndEnumeratorType() { await TestInRegularAndScriptAsync( @"using System; class MyList { public string this[int i] { get; } public Enumerator GetEnumerator() { } public struct Enumerator { public object Current { get; } } } class C { void Test(MyList list) { // need to use 'string' here to preserve original index semantics. [||]for (int i = 0; i < list.Length; i++) { Console.WriteLine(list[i]); } } }", @"using System; class MyList { public string this[int i] { get; } public Enumerator GetEnumerator() { } public struct Enumerator { public object Current { get; } } } class C { void Test(MyList list) { // need to use 'string' here to preserve original index semantics. foreach (string {|Rename:v|} in list) { Console.WriteLine(v); } } }", options: ImplicitTypeEverywhere()); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForToForEach)] public async Task TestSameIndexerAndEnumeratorType() { await TestInRegularAndScriptAsync( @"using System; class MyList { public object this[int i] { get => default; } public Enumerator GetEnumerator() { return default; } public struct Enumerator { public object Current { get; } public bool MoveNext() => true; } } class C { void Test(MyList list) { // can use 'var' here since hte type stayed the same. [||]for (int i = 0; i < list.Length; i++) { Console.WriteLine(list[i]); } } }", @"using System; class MyList { public object this[int i] { get => default; } public Enumerator GetEnumerator() { return default; } public struct Enumerator { public object Current { get; } public bool MoveNext() => true; } } class C { void Test(MyList list) { // can use 'var' here since hte type stayed the same. foreach (var {|Rename:v|} in list) { Console.WriteLine(v); } } }", options: ImplicitTypeEverywhere()); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForToForEach)] public async Task TestTrivia() { await TestInRegularAndScript1Async( @"using System; class C { void Test(string[] array) { // trivia 1 [||]for /*trivia 2*/ ( /*trivia 3*/ int i = 0; i < array.Length; i++) /*trivia 4*/ // trivia 5 { Console.WriteLine(array[i]); } // trivia 6 } }", @"using System; class C { void Test(string[] array) { // trivia 1 foreach /*trivia 2*/ ( /*trivia 3*/ string {|Rename:v|} in array) /*trivia 4*/ // trivia 5 { Console.WriteLine(v); } // trivia 6 } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForToForEach)] public async Task TestNotWithDeconstruction() { await TestMissingInRegularAndScriptAsync( @"using System; class C { void Test(string[] array) { [||]for (var (i, j) = (0, 0); i < array.Length; i++) { Console.WriteLine(array[i]); } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForToForEach)] public async Task TestMultidimensionalArray1() { await TestMissingInRegularAndScriptAsync( @"using System; class C { void Test(string[,] array) { [||]for (int i = 0; i < array.Length; i++) { Console.WriteLine(array[i, 0]); } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForToForEach)] public async Task TestMultidimensionalArray2() { await TestMissingInRegularAndScriptAsync( @"using System; class C { void Test(string[,] array) { [||]for (int i = 0; i < array.Length; i++) { Console.WriteLine(array[i, i]); } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForToForEach)] public async Task TestJaggedArray1() { await TestInRegularAndScript1Async( @"using System; class C { void Test(string[][] array) { [||]for (int i = 0; i < array.Length; i++) { Console.WriteLine(array[i]); } } }", @"using System; class C { void Test(string[][] array) { foreach (string[] {|Rename:v|} in array) { Console.WriteLine(v); } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForToForEach)] public async Task TestJaggedArray2() { await TestInRegularAndScript1Async( @"using System; class C { void Test(string[][] array) { [||]for (int i = 0; i < array.Length; i++) { Console.WriteLine(array[i][0]); } } }", @"using System; class C { void Test(string[][] array) { foreach (string[] {|Rename:v|} in array) { Console.WriteLine(v[0]); } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForToForEach)] public async Task TestJaggedArray3() { await TestInRegularAndScript1Async( @"using System; class C { void Test(string[][] array) { [||]for (int i = 0; i < array.Length; i++) { var subArray = array[i]; for (int j = 0; j < subArray.Length; j++) { Console.WriteLine(array[i][j]); } } } }", @"using System; class C { void Test(string[][] array) { foreach (var subArray in array) { for (int j = 0; j < subArray.Length; j++) { Console.WriteLine(subArray[j]); } } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForToForEach)] public async Task TestJaggedArray4() { await TestInRegularAndScript1Async( @"using System; class C { void Test(string[][] array) { [||]for (int i = 0; i < array.Length; i++) { for (int j = 0; j < array[i].Length; j++) { Console.WriteLine(array[i][j]); } } } }", @"using System; class C { void Test(string[][] array) { foreach (string[] {|Rename:v|} in array) { for (int j = 0; j < v.Length; j++) { Console.WriteLine(v[j]); } } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForToForEach)] public async Task TestJaggedArray5() { await TestInRegularAndScript1Async( @"using System; class C { void Test(string[][] array) { for (int i = 0; i < array.Length; i++) { [||]for (int j = 0; j < array[i].Length; j++) { Console.WriteLine(array[i][j]); } } } }", @"using System; class C { void Test(string[][] array) { for (int i = 0; i < array.Length; i++) { foreach (string {|Rename:v|} in array[i]) { Console.WriteLine(v); } } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForToForEach)] public async Task TestJaggedArray6() { await TestMissingInRegularAndScriptAsync( @"using System; class C { void Test(string[][] array) { [||]for (int i = 0; i < array.Length; i++) { Console.WriteLine(array[i][i]); } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForToForEach)] public async Task TestDoesNotUseLocalFunctionName() { await TestInRegularAndScript1Async( @"using System; class C { void Test(string[] array) { [||]for (int i = 0; i < array.Length; i++) { Console.WriteLine(array[i]); } void v() { } } }", @"using System; class C { void Test(string[] array) { foreach (string {|Rename:v1|} in array) { Console.WriteLine(v1); } void v() { } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForToForEach)] public async Task TestUsesLocalFunctionParameterName() { await TestInRegularAndScript1Async( @"using System; class C { void Test(string[] array) { [||]for (int i = 0; i < array.Length; i++) { Console.WriteLine(array[i]); } void M(string v) { } } }", @"using System; class C { void Test(string[] array) { foreach (string {|Rename:v|} in array) { Console.WriteLine(v); } void M(string v) { } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForToForEach)] public async Task TestDoesNotUseLambdaParameterWithCSharpLessThan8() { await TestInRegularAndScript1Async( @"using System; class C { void Test(string[] array) { [||]for (int i = 0; i < array.Length; i++) { Console.WriteLine(array[i]); } Action<int> myLambda = v => { }; } }", @"using System; class C { void Test(string[] array) { foreach (string {|Rename:v1|} in array) { Console.WriteLine(v1); } Action<int> myLambda = v => { }; } }", parameters: new TestParameters(new CSharpParseOptions(LanguageVersion.CSharp7_3))); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForToForEach)] public async Task TestUsesLambdaParameterNameInCSharp8() { await TestInRegularAndScript1Async( @"using System; class C { void Test(string[] array) { [||]for (int i = 0; i < array.Length; i++) { Console.WriteLine(array[i]); } Action<int> myLambda = v => { }; } }", @"using System; class C { void Test(string[] array) { foreach (string {|Rename:v|} in array) { Console.WriteLine(v); } Action<int> myLambda = v => { }; } }", parameters: new TestParameters(new CSharpParseOptions(LanguageVersion.CSharp8))); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForToForEach)] public async Task TestNotWhenIteratingDifferentLists() { await TestMissingAsync( @"using System; using System.Collection.Generic; class Item { public string Value; } class C { static void Test() { var first = new { list = new List<Item>() }; var second = new { list = new List<Item>() }; [||]for (var i = 0; i < first.list.Count; i++) { first.list[i].Value = second.list[i].Value; } } }"); } } }
-1
dotnet/roslyn
55,430
Fix LSP semantic tokens algorithm
This PR primarily accomplishes two tasks: 1) Overhauls the existing LSP semantic tokens edits processing algorithm to align with [Razor's](https://github.com/dotnet/aspnetcore-tooling/blob/main/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/Semantic/Services/SemanticTokensEditsDiffer.cs) (shoutout to Ryan and the rest of the Razor team for writing the original 😄). The main change here is going from calculating edits per token (i.e. five ints) to per int. The updated algorithm is much more efficient than our previous algorithm, and returns less edits back to the LSP client. 2) The interpretation of Roslyn's LongestCommonSubstring algorithm, which we use to calculate raw edits, was missing a critical piece. Namely, for insertions, we need to keep track of _where_ we should be inserting into the original token set. We don't keep track of this in the existing implementation, resulting in bugs such as #54671. Resolves #54671
allisonchou
2021-08-05T06:06:43Z
2021-08-06T23:44:44Z
b9200d03a76c74d404040d44b9bbe12b1d0a8ef2
f300a818940ea1acef66c946cfa83756729d5e59
Fix LSP semantic tokens algorithm. This PR primarily accomplishes two tasks: 1) Overhauls the existing LSP semantic tokens edits processing algorithm to align with [Razor's](https://github.com/dotnet/aspnetcore-tooling/blob/main/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/Semantic/Services/SemanticTokensEditsDiffer.cs) (shoutout to Ryan and the rest of the Razor team for writing the original 😄). The main change here is going from calculating edits per token (i.e. five ints) to per int. The updated algorithm is much more efficient than our previous algorithm, and returns less edits back to the LSP client. 2) The interpretation of Roslyn's LongestCommonSubstring algorithm, which we use to calculate raw edits, was missing a critical piece. Namely, for insertions, we need to keep track of _where_ we should be inserting into the original token set. We don't keep track of this in the existing implementation, resulting in bugs such as #54671. Resolves #54671
./src/Compilers/Core/Portable/DiagnosticAnalyzer/AnalyzerManager.AnalyzerExecutionContext.cs
// Licensed to the .NET Foundation under one or more agreements. // 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.Text; using System.Threading.Tasks; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Diagnostics { internal partial class AnalyzerManager { private sealed class AnalyzerExecutionContext { private readonly DiagnosticAnalyzer _analyzer; private readonly object _gate; /// <summary> /// Map from (symbol, analyzer) to count of its member symbols whose symbol declared events are not yet processed. /// </summary> private Dictionary<ISymbol, HashSet<ISymbol>?>? _lazyPendingMemberSymbolsMap; /// <summary> /// Symbol declared events for symbols with pending symbol end analysis for given analyzer. /// </summary> private Dictionary<ISymbol, (ImmutableArray<SymbolEndAnalyzerAction>, SymbolDeclaredCompilationEvent)>? _lazyPendingSymbolEndActionsMap; /// <summary> /// Task to compute HostSessionStartAnalysisScope for session wide analyzer actions, i.e. AnalyzerActions registered by analyzer's Initialize method. /// These are run only once per every analyzer. /// </summary> private Task<HostSessionStartAnalysisScope>? _lazySessionScopeTask; /// <summary> /// Task to compute HostCompilationStartAnalysisScope for per-compilation analyzer actions, i.e. AnalyzerActions registered by analyzer's CompilationStartActions. /// </summary> private Task<HostCompilationStartAnalysisScope>? _lazyCompilationScopeTask; /// <summary> /// Task to compute HostSymbolStartAnalysisScope for per-symbol analyzer actions, i.e. AnalyzerActions registered by analyzer's SymbolStartActions. /// </summary> private Dictionary<ISymbol, Task<HostSymbolStartAnalysisScope>>? _lazySymbolScopeTasks; /// <summary> /// Supported diagnostic descriptors for diagnostic analyzer, if any. /// </summary> private ImmutableArray<DiagnosticDescriptor> _lazyDiagnosticDescriptors; /// <summary> /// Supported suppression descriptors for diagnostic suppressor, if any. /// </summary> private ImmutableArray<SuppressionDescriptor> _lazySuppressionDescriptors; public AnalyzerExecutionContext(DiagnosticAnalyzer analyzer) { _analyzer = analyzer; _gate = new object(); } [PerformanceSensitive( "https://github.com/dotnet/roslyn/issues/26778", AllowCaptures = false)] public Task<HostSessionStartAnalysisScope> GetSessionAnalysisScopeAsync(AnalyzerExecutor analyzerExecutor) { lock (_gate) { Task<HostSessionStartAnalysisScope> task; if (_lazySessionScopeTask != null) { return _lazySessionScopeTask; } task = getSessionAnalysisScopeTaskSlow(this, analyzerExecutor); _lazySessionScopeTask = task; return task; static Task<HostSessionStartAnalysisScope> getSessionAnalysisScopeTaskSlow(AnalyzerExecutionContext context, AnalyzerExecutor executor) { return Task.Run(() => { var sessionScope = new HostSessionStartAnalysisScope(); executor.ExecuteInitializeMethod(context._analyzer, sessionScope); return sessionScope; }, executor.CancellationToken); } } } public void ClearSessionScopeTask() { lock (_gate) { _lazySessionScopeTask = null; } } public Task<HostCompilationStartAnalysisScope> GetCompilationAnalysisScopeAsync( HostSessionStartAnalysisScope sessionScope, AnalyzerExecutor analyzerExecutor) { lock (_gate) { if (_lazyCompilationScopeTask == null) { _lazyCompilationScopeTask = Task.Run(() => { var compilationAnalysisScope = new HostCompilationStartAnalysisScope(sessionScope); analyzerExecutor.ExecuteCompilationStartActions(sessionScope.GetAnalyzerActions(_analyzer).CompilationStartActions, compilationAnalysisScope); return compilationAnalysisScope; }, analyzerExecutor.CancellationToken); } return _lazyCompilationScopeTask; } } public void ClearCompilationScopeTask() { lock (_gate) { _lazyCompilationScopeTask = null; } } public Task<HostSymbolStartAnalysisScope> GetSymbolAnalysisScopeAsync( ISymbol symbol, ImmutableArray<SymbolStartAnalyzerAction> symbolStartActions, AnalyzerExecutor analyzerExecutor) { lock (_gate) { _lazySymbolScopeTasks ??= new Dictionary<ISymbol, Task<HostSymbolStartAnalysisScope>>(); if (!_lazySymbolScopeTasks.TryGetValue(symbol, out var symbolScopeTask)) { symbolScopeTask = Task.Run(() => getSymbolAnalysisScopeCore(), analyzerExecutor.CancellationToken); _lazySymbolScopeTasks.Add(symbol, symbolScopeTask); } return symbolScopeTask; HostSymbolStartAnalysisScope getSymbolAnalysisScopeCore() { var symbolAnalysisScope = new HostSymbolStartAnalysisScope(); analyzerExecutor.ExecuteSymbolStartActions(symbol, _analyzer, symbolStartActions, symbolAnalysisScope); var symbolEndActions = symbolAnalysisScope.GetAnalyzerActions(_analyzer); if (symbolEndActions.SymbolEndActionsCount > 0) { var dependentSymbols = getDependentSymbols(); lock (_gate) { _lazyPendingMemberSymbolsMap ??= new Dictionary<ISymbol, HashSet<ISymbol>?>(); // Guard against entry added from another thread. VerifyNewEntryForPendingMemberSymbolsMap(symbol, dependentSymbols); _lazyPendingMemberSymbolsMap[symbol] = dependentSymbols; } } return symbolAnalysisScope; } } HashSet<ISymbol>? getDependentSymbols() { HashSet<ISymbol>? memberSet = null; switch (symbol.Kind) { case SymbolKind.NamedType: processMembers(((INamedTypeSymbol)symbol).GetMembers()); break; case SymbolKind.Namespace: processMembers(((INamespaceSymbol)symbol).GetMembers()); break; } return memberSet; void processMembers(IEnumerable<ISymbol> members) { foreach (var member in members) { if (!member.IsImplicitlyDeclared && member.IsInSource()) { memberSet ??= new HashSet<ISymbol>(); memberSet.Add(member); // Ensure that we include symbols for both parts of partial methods. if (member is IMethodSymbol method && !(method.PartialImplementationPart is null)) { memberSet.Add(method.PartialImplementationPart); } } if (member.Kind != symbol.Kind && member is INamedTypeSymbol typeMember) { processMembers(typeMember.GetMembers()); } } } } } [Conditional("DEBUG")] private void VerifyNewEntryForPendingMemberSymbolsMap(ISymbol symbol, HashSet<ISymbol>? dependentSymbols) { Debug.Assert(_lazyPendingMemberSymbolsMap != null, $"{nameof(_lazyPendingMemberSymbolsMap)} was expected to be a non-null value."); if (_lazyPendingMemberSymbolsMap.TryGetValue(symbol, out var existingDependentSymbols)) { if (existingDependentSymbols == null) { Debug.Assert(dependentSymbols == null, $"{nameof(dependentSymbols)} was expected to be null."); } else { Debug.Assert(dependentSymbols != null, $"{nameof(dependentSymbols)} was expected to be a non-null value."); Debug.Assert(existingDependentSymbols.IsSubsetOf(dependentSymbols), $"{nameof(existingDependentSymbols)} was expected to be a subset of {nameof(dependentSymbols)}"); } } } public void ClearSymbolScopeTask(ISymbol symbol) { lock (_gate) { _lazySymbolScopeTasks?.Remove(symbol); } } public ImmutableArray<DiagnosticDescriptor> GetOrComputeDiagnosticDescriptors(DiagnosticAnalyzer analyzer, AnalyzerExecutor analyzerExecutor) => GetOrComputeDescriptors(ref _lazyDiagnosticDescriptors, ComputeDiagnosticDescriptors, analyzer, analyzerExecutor); public ImmutableArray<SuppressionDescriptor> GetOrComputeSuppressionDescriptors(DiagnosticSuppressor suppressor, AnalyzerExecutor analyzerExecutor) => GetOrComputeDescriptors(ref _lazySuppressionDescriptors, ComputeSuppressionDescriptors, suppressor, analyzerExecutor); private static ImmutableArray<TDescriptor> GetOrComputeDescriptors<TDescriptor>( ref ImmutableArray<TDescriptor> lazyDescriptors, Func<DiagnosticAnalyzer, AnalyzerExecutor, ImmutableArray<TDescriptor>> computeDescriptors, DiagnosticAnalyzer analyzer, AnalyzerExecutor analyzerExecutor) { if (!lazyDescriptors.IsDefault) { return lazyDescriptors; } // Otherwise, compute the value. // We do so outside the lock statement as we are calling into user code, which may be a long running operation. var descriptors = computeDescriptors(analyzer, analyzerExecutor); ImmutableInterlocked.InterlockedInitialize(ref lazyDescriptors, descriptors); return lazyDescriptors; } /// <summary> /// Compute <see cref="DiagnosticAnalyzer.SupportedDiagnostics"/> and exception handler for the given <paramref name="analyzer"/>. /// </summary> private static ImmutableArray<DiagnosticDescriptor> ComputeDiagnosticDescriptors( DiagnosticAnalyzer analyzer, AnalyzerExecutor analyzerExecutor) { var supportedDiagnostics = ImmutableArray<DiagnosticDescriptor>.Empty; // Catch Exception from analyzer.SupportedDiagnostics analyzerExecutor.ExecuteAndCatchIfThrows( analyzer, _ => { var supportedDiagnosticsLocal = analyzer.SupportedDiagnostics; if (!supportedDiagnosticsLocal.IsDefaultOrEmpty) { foreach (var descriptor in supportedDiagnosticsLocal) { if (descriptor == null) { // Disallow null descriptors. throw new ArgumentException(string.Format(CodeAnalysisResources.SupportedDiagnosticsHasNullDescriptor, analyzer.ToString()), nameof(DiagnosticAnalyzer.SupportedDiagnostics)); } } supportedDiagnostics = supportedDiagnosticsLocal; } }, argument: (object?)null); // Force evaluate and report exception diagnostics from LocalizableString.ToString(). Action<Exception, DiagnosticAnalyzer, Diagnostic> onAnalyzerException = analyzerExecutor.OnAnalyzerException; if (onAnalyzerException != null) { var handler = new EventHandler<Exception>((sender, ex) => { var diagnostic = AnalyzerExecutor.CreateAnalyzerExceptionDiagnostic(analyzer, ex); onAnalyzerException(ex, analyzer, diagnostic); }); foreach (var descriptor in supportedDiagnostics) { ForceLocalizableStringExceptions(descriptor.Title, handler); ForceLocalizableStringExceptions(descriptor.MessageFormat, handler); ForceLocalizableStringExceptions(descriptor.Description, handler); } } return supportedDiagnostics; } private static ImmutableArray<SuppressionDescriptor> ComputeSuppressionDescriptors( DiagnosticAnalyzer analyzer, AnalyzerExecutor analyzerExecutor) { var descriptors = ImmutableArray<SuppressionDescriptor>.Empty; if (analyzer is DiagnosticSuppressor suppressor) { // Catch Exception from suppressor.SupportedSuppressions analyzerExecutor.ExecuteAndCatchIfThrows( analyzer, _ => { var descriptorsLocal = suppressor.SupportedSuppressions; if (!descriptorsLocal.IsDefaultOrEmpty) { foreach (var descriptor in descriptorsLocal) { if (descriptor == null) { // Disallow null descriptors. throw new ArgumentException(string.Format(CodeAnalysisResources.SupportedSuppressionsHasNullDescriptor, analyzer.ToString()), nameof(DiagnosticSuppressor.SupportedSuppressions)); } } descriptors = descriptorsLocal; } }, argument: (object?)null); } return descriptors; } public bool TryProcessCompletedMemberAndGetPendingSymbolEndActionsForContainer( ISymbol containingSymbol, ISymbol processedMemberSymbol, out (ImmutableArray<SymbolEndAnalyzerAction> symbolEndActions, SymbolDeclaredCompilationEvent symbolDeclaredEvent) containerEndActionsAndEvent) { containerEndActionsAndEvent = default; lock (_gate) { if (_lazyPendingMemberSymbolsMap == null || !_lazyPendingMemberSymbolsMap.TryGetValue(containingSymbol, out var pendingMemberSymbols)) { return false; } Debug.Assert(pendingMemberSymbols != null); var removed = pendingMemberSymbols.Remove(processedMemberSymbol); if (pendingMemberSymbols.Count > 0 || _lazyPendingSymbolEndActionsMap == null || !_lazyPendingSymbolEndActionsMap.TryGetValue(containingSymbol, out containerEndActionsAndEvent)) { return false; } _lazyPendingSymbolEndActionsMap.Remove(containingSymbol); return true; } } public bool TryStartExecuteSymbolEndActions(ImmutableArray<SymbolEndAnalyzerAction> symbolEndActions, SymbolDeclaredCompilationEvent symbolDeclaredEvent) { Debug.Assert(!symbolEndActions.IsEmpty); var symbol = symbolDeclaredEvent.Symbol; lock (_gate) { Debug.Assert(_lazyPendingMemberSymbolsMap != null); if (_lazyPendingMemberSymbolsMap.TryGetValue(symbol, out var pendingMemberSymbols) && pendingMemberSymbols?.Count > 0) { // At least one member is not complete, so mark the event for later processing of symbol end actions. MarkSymbolEndAnalysisPending_NoLock(symbol, symbolEndActions, symbolDeclaredEvent); return false; } // Try remove the pending event in case it was marked pending by another thread when members were not yet complete. _lazyPendingSymbolEndActionsMap?.Remove(symbol); return true; } } public void MarkSymbolEndAnalysisComplete(ISymbol symbol) { lock (_gate) { _lazyPendingMemberSymbolsMap?.Remove(symbol); } } public void MarkSymbolEndAnalysisPending(ISymbol symbol, ImmutableArray<SymbolEndAnalyzerAction> symbolEndActions, SymbolDeclaredCompilationEvent symbolDeclaredEvent) { lock (_gate) { MarkSymbolEndAnalysisPending_NoLock(symbol, symbolEndActions, symbolDeclaredEvent); } } private void MarkSymbolEndAnalysisPending_NoLock(ISymbol symbol, ImmutableArray<SymbolEndAnalyzerAction> symbolEndActions, SymbolDeclaredCompilationEvent symbolDeclaredEvent) { _lazyPendingSymbolEndActionsMap ??= new Dictionary<ISymbol, (ImmutableArray<SymbolEndAnalyzerAction>, SymbolDeclaredCompilationEvent)>(); _lazyPendingSymbolEndActionsMap[symbol] = (symbolEndActions, symbolDeclaredEvent); } [Conditional("DEBUG")] public void VerifyAllSymbolEndActionsExecuted() { lock (_gate) { Debug.Assert(_lazyPendingMemberSymbolsMap == null || _lazyPendingMemberSymbolsMap.Count == 0); Debug.Assert(_lazyPendingSymbolEndActionsMap == null || _lazyPendingSymbolEndActionsMap.Count == 0); } } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Text; using System.Threading.Tasks; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Diagnostics { internal partial class AnalyzerManager { private sealed class AnalyzerExecutionContext { private readonly DiagnosticAnalyzer _analyzer; private readonly object _gate; /// <summary> /// Map from (symbol, analyzer) to count of its member symbols whose symbol declared events are not yet processed. /// </summary> private Dictionary<ISymbol, HashSet<ISymbol>?>? _lazyPendingMemberSymbolsMap; /// <summary> /// Symbol declared events for symbols with pending symbol end analysis for given analyzer. /// </summary> private Dictionary<ISymbol, (ImmutableArray<SymbolEndAnalyzerAction>, SymbolDeclaredCompilationEvent)>? _lazyPendingSymbolEndActionsMap; /// <summary> /// Task to compute HostSessionStartAnalysisScope for session wide analyzer actions, i.e. AnalyzerActions registered by analyzer's Initialize method. /// These are run only once per every analyzer. /// </summary> private Task<HostSessionStartAnalysisScope>? _lazySessionScopeTask; /// <summary> /// Task to compute HostCompilationStartAnalysisScope for per-compilation analyzer actions, i.e. AnalyzerActions registered by analyzer's CompilationStartActions. /// </summary> private Task<HostCompilationStartAnalysisScope>? _lazyCompilationScopeTask; /// <summary> /// Task to compute HostSymbolStartAnalysisScope for per-symbol analyzer actions, i.e. AnalyzerActions registered by analyzer's SymbolStartActions. /// </summary> private Dictionary<ISymbol, Task<HostSymbolStartAnalysisScope>>? _lazySymbolScopeTasks; /// <summary> /// Supported diagnostic descriptors for diagnostic analyzer, if any. /// </summary> private ImmutableArray<DiagnosticDescriptor> _lazyDiagnosticDescriptors; /// <summary> /// Supported suppression descriptors for diagnostic suppressor, if any. /// </summary> private ImmutableArray<SuppressionDescriptor> _lazySuppressionDescriptors; public AnalyzerExecutionContext(DiagnosticAnalyzer analyzer) { _analyzer = analyzer; _gate = new object(); } [PerformanceSensitive( "https://github.com/dotnet/roslyn/issues/26778", AllowCaptures = false)] public Task<HostSessionStartAnalysisScope> GetSessionAnalysisScopeAsync(AnalyzerExecutor analyzerExecutor) { lock (_gate) { Task<HostSessionStartAnalysisScope> task; if (_lazySessionScopeTask != null) { return _lazySessionScopeTask; } task = getSessionAnalysisScopeTaskSlow(this, analyzerExecutor); _lazySessionScopeTask = task; return task; static Task<HostSessionStartAnalysisScope> getSessionAnalysisScopeTaskSlow(AnalyzerExecutionContext context, AnalyzerExecutor executor) { return Task.Run(() => { var sessionScope = new HostSessionStartAnalysisScope(); executor.ExecuteInitializeMethod(context._analyzer, sessionScope); return sessionScope; }, executor.CancellationToken); } } } public void ClearSessionScopeTask() { lock (_gate) { _lazySessionScopeTask = null; } } public Task<HostCompilationStartAnalysisScope> GetCompilationAnalysisScopeAsync( HostSessionStartAnalysisScope sessionScope, AnalyzerExecutor analyzerExecutor) { lock (_gate) { if (_lazyCompilationScopeTask == null) { _lazyCompilationScopeTask = Task.Run(() => { var compilationAnalysisScope = new HostCompilationStartAnalysisScope(sessionScope); analyzerExecutor.ExecuteCompilationStartActions(sessionScope.GetAnalyzerActions(_analyzer).CompilationStartActions, compilationAnalysisScope); return compilationAnalysisScope; }, analyzerExecutor.CancellationToken); } return _lazyCompilationScopeTask; } } public void ClearCompilationScopeTask() { lock (_gate) { _lazyCompilationScopeTask = null; } } public Task<HostSymbolStartAnalysisScope> GetSymbolAnalysisScopeAsync( ISymbol symbol, ImmutableArray<SymbolStartAnalyzerAction> symbolStartActions, AnalyzerExecutor analyzerExecutor) { lock (_gate) { _lazySymbolScopeTasks ??= new Dictionary<ISymbol, Task<HostSymbolStartAnalysisScope>>(); if (!_lazySymbolScopeTasks.TryGetValue(symbol, out var symbolScopeTask)) { symbolScopeTask = Task.Run(() => getSymbolAnalysisScopeCore(), analyzerExecutor.CancellationToken); _lazySymbolScopeTasks.Add(symbol, symbolScopeTask); } return symbolScopeTask; HostSymbolStartAnalysisScope getSymbolAnalysisScopeCore() { var symbolAnalysisScope = new HostSymbolStartAnalysisScope(); analyzerExecutor.ExecuteSymbolStartActions(symbol, _analyzer, symbolStartActions, symbolAnalysisScope); var symbolEndActions = symbolAnalysisScope.GetAnalyzerActions(_analyzer); if (symbolEndActions.SymbolEndActionsCount > 0) { var dependentSymbols = getDependentSymbols(); lock (_gate) { _lazyPendingMemberSymbolsMap ??= new Dictionary<ISymbol, HashSet<ISymbol>?>(); // Guard against entry added from another thread. VerifyNewEntryForPendingMemberSymbolsMap(symbol, dependentSymbols); _lazyPendingMemberSymbolsMap[symbol] = dependentSymbols; } } return symbolAnalysisScope; } } HashSet<ISymbol>? getDependentSymbols() { HashSet<ISymbol>? memberSet = null; switch (symbol.Kind) { case SymbolKind.NamedType: processMembers(((INamedTypeSymbol)symbol).GetMembers()); break; case SymbolKind.Namespace: processMembers(((INamespaceSymbol)symbol).GetMembers()); break; } return memberSet; void processMembers(IEnumerable<ISymbol> members) { foreach (var member in members) { if (!member.IsImplicitlyDeclared && member.IsInSource()) { memberSet ??= new HashSet<ISymbol>(); memberSet.Add(member); // Ensure that we include symbols for both parts of partial methods. if (member is IMethodSymbol method && !(method.PartialImplementationPart is null)) { memberSet.Add(method.PartialImplementationPart); } } if (member.Kind != symbol.Kind && member is INamedTypeSymbol typeMember) { processMembers(typeMember.GetMembers()); } } } } } [Conditional("DEBUG")] private void VerifyNewEntryForPendingMemberSymbolsMap(ISymbol symbol, HashSet<ISymbol>? dependentSymbols) { Debug.Assert(_lazyPendingMemberSymbolsMap != null, $"{nameof(_lazyPendingMemberSymbolsMap)} was expected to be a non-null value."); if (_lazyPendingMemberSymbolsMap.TryGetValue(symbol, out var existingDependentSymbols)) { if (existingDependentSymbols == null) { Debug.Assert(dependentSymbols == null, $"{nameof(dependentSymbols)} was expected to be null."); } else { Debug.Assert(dependentSymbols != null, $"{nameof(dependentSymbols)} was expected to be a non-null value."); Debug.Assert(existingDependentSymbols.IsSubsetOf(dependentSymbols), $"{nameof(existingDependentSymbols)} was expected to be a subset of {nameof(dependentSymbols)}"); } } } public void ClearSymbolScopeTask(ISymbol symbol) { lock (_gate) { _lazySymbolScopeTasks?.Remove(symbol); } } public ImmutableArray<DiagnosticDescriptor> GetOrComputeDiagnosticDescriptors(DiagnosticAnalyzer analyzer, AnalyzerExecutor analyzerExecutor) => GetOrComputeDescriptors(ref _lazyDiagnosticDescriptors, ComputeDiagnosticDescriptors, analyzer, analyzerExecutor); public ImmutableArray<SuppressionDescriptor> GetOrComputeSuppressionDescriptors(DiagnosticSuppressor suppressor, AnalyzerExecutor analyzerExecutor) => GetOrComputeDescriptors(ref _lazySuppressionDescriptors, ComputeSuppressionDescriptors, suppressor, analyzerExecutor); private static ImmutableArray<TDescriptor> GetOrComputeDescriptors<TDescriptor>( ref ImmutableArray<TDescriptor> lazyDescriptors, Func<DiagnosticAnalyzer, AnalyzerExecutor, ImmutableArray<TDescriptor>> computeDescriptors, DiagnosticAnalyzer analyzer, AnalyzerExecutor analyzerExecutor) { if (!lazyDescriptors.IsDefault) { return lazyDescriptors; } // Otherwise, compute the value. // We do so outside the lock statement as we are calling into user code, which may be a long running operation. var descriptors = computeDescriptors(analyzer, analyzerExecutor); ImmutableInterlocked.InterlockedInitialize(ref lazyDescriptors, descriptors); return lazyDescriptors; } /// <summary> /// Compute <see cref="DiagnosticAnalyzer.SupportedDiagnostics"/> and exception handler for the given <paramref name="analyzer"/>. /// </summary> private static ImmutableArray<DiagnosticDescriptor> ComputeDiagnosticDescriptors( DiagnosticAnalyzer analyzer, AnalyzerExecutor analyzerExecutor) { var supportedDiagnostics = ImmutableArray<DiagnosticDescriptor>.Empty; // Catch Exception from analyzer.SupportedDiagnostics analyzerExecutor.ExecuteAndCatchIfThrows( analyzer, _ => { var supportedDiagnosticsLocal = analyzer.SupportedDiagnostics; if (!supportedDiagnosticsLocal.IsDefaultOrEmpty) { foreach (var descriptor in supportedDiagnosticsLocal) { if (descriptor == null) { // Disallow null descriptors. throw new ArgumentException(string.Format(CodeAnalysisResources.SupportedDiagnosticsHasNullDescriptor, analyzer.ToString()), nameof(DiagnosticAnalyzer.SupportedDiagnostics)); } } supportedDiagnostics = supportedDiagnosticsLocal; } }, argument: (object?)null); // Force evaluate and report exception diagnostics from LocalizableString.ToString(). Action<Exception, DiagnosticAnalyzer, Diagnostic> onAnalyzerException = analyzerExecutor.OnAnalyzerException; if (onAnalyzerException != null) { var handler = new EventHandler<Exception>((sender, ex) => { var diagnostic = AnalyzerExecutor.CreateAnalyzerExceptionDiagnostic(analyzer, ex); onAnalyzerException(ex, analyzer, diagnostic); }); foreach (var descriptor in supportedDiagnostics) { ForceLocalizableStringExceptions(descriptor.Title, handler); ForceLocalizableStringExceptions(descriptor.MessageFormat, handler); ForceLocalizableStringExceptions(descriptor.Description, handler); } } return supportedDiagnostics; } private static ImmutableArray<SuppressionDescriptor> ComputeSuppressionDescriptors( DiagnosticAnalyzer analyzer, AnalyzerExecutor analyzerExecutor) { var descriptors = ImmutableArray<SuppressionDescriptor>.Empty; if (analyzer is DiagnosticSuppressor suppressor) { // Catch Exception from suppressor.SupportedSuppressions analyzerExecutor.ExecuteAndCatchIfThrows( analyzer, _ => { var descriptorsLocal = suppressor.SupportedSuppressions; if (!descriptorsLocal.IsDefaultOrEmpty) { foreach (var descriptor in descriptorsLocal) { if (descriptor == null) { // Disallow null descriptors. throw new ArgumentException(string.Format(CodeAnalysisResources.SupportedSuppressionsHasNullDescriptor, analyzer.ToString()), nameof(DiagnosticSuppressor.SupportedSuppressions)); } } descriptors = descriptorsLocal; } }, argument: (object?)null); } return descriptors; } public bool TryProcessCompletedMemberAndGetPendingSymbolEndActionsForContainer( ISymbol containingSymbol, ISymbol processedMemberSymbol, out (ImmutableArray<SymbolEndAnalyzerAction> symbolEndActions, SymbolDeclaredCompilationEvent symbolDeclaredEvent) containerEndActionsAndEvent) { containerEndActionsAndEvent = default; lock (_gate) { if (_lazyPendingMemberSymbolsMap == null || !_lazyPendingMemberSymbolsMap.TryGetValue(containingSymbol, out var pendingMemberSymbols)) { return false; } Debug.Assert(pendingMemberSymbols != null); var removed = pendingMemberSymbols.Remove(processedMemberSymbol); if (pendingMemberSymbols.Count > 0 || _lazyPendingSymbolEndActionsMap == null || !_lazyPendingSymbolEndActionsMap.TryGetValue(containingSymbol, out containerEndActionsAndEvent)) { return false; } _lazyPendingSymbolEndActionsMap.Remove(containingSymbol); return true; } } public bool TryStartExecuteSymbolEndActions(ImmutableArray<SymbolEndAnalyzerAction> symbolEndActions, SymbolDeclaredCompilationEvent symbolDeclaredEvent) { Debug.Assert(!symbolEndActions.IsEmpty); var symbol = symbolDeclaredEvent.Symbol; lock (_gate) { Debug.Assert(_lazyPendingMemberSymbolsMap != null); if (_lazyPendingMemberSymbolsMap.TryGetValue(symbol, out var pendingMemberSymbols) && pendingMemberSymbols?.Count > 0) { // At least one member is not complete, so mark the event for later processing of symbol end actions. MarkSymbolEndAnalysisPending_NoLock(symbol, symbolEndActions, symbolDeclaredEvent); return false; } // Try remove the pending event in case it was marked pending by another thread when members were not yet complete. _lazyPendingSymbolEndActionsMap?.Remove(symbol); return true; } } public void MarkSymbolEndAnalysisComplete(ISymbol symbol) { lock (_gate) { _lazyPendingMemberSymbolsMap?.Remove(symbol); } } public void MarkSymbolEndAnalysisPending(ISymbol symbol, ImmutableArray<SymbolEndAnalyzerAction> symbolEndActions, SymbolDeclaredCompilationEvent symbolDeclaredEvent) { lock (_gate) { MarkSymbolEndAnalysisPending_NoLock(symbol, symbolEndActions, symbolDeclaredEvent); } } private void MarkSymbolEndAnalysisPending_NoLock(ISymbol symbol, ImmutableArray<SymbolEndAnalyzerAction> symbolEndActions, SymbolDeclaredCompilationEvent symbolDeclaredEvent) { _lazyPendingSymbolEndActionsMap ??= new Dictionary<ISymbol, (ImmutableArray<SymbolEndAnalyzerAction>, SymbolDeclaredCompilationEvent)>(); _lazyPendingSymbolEndActionsMap[symbol] = (symbolEndActions, symbolDeclaredEvent); } [Conditional("DEBUG")] public void VerifyAllSymbolEndActionsExecuted() { lock (_gate) { Debug.Assert(_lazyPendingMemberSymbolsMap == null || _lazyPendingMemberSymbolsMap.Count == 0); Debug.Assert(_lazyPendingSymbolEndActionsMap == null || _lazyPendingSymbolEndActionsMap.Count == 0); } } } } }
-1
dotnet/roslyn
55,430
Fix LSP semantic tokens algorithm
This PR primarily accomplishes two tasks: 1) Overhauls the existing LSP semantic tokens edits processing algorithm to align with [Razor's](https://github.com/dotnet/aspnetcore-tooling/blob/main/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/Semantic/Services/SemanticTokensEditsDiffer.cs) (shoutout to Ryan and the rest of the Razor team for writing the original 😄). The main change here is going from calculating edits per token (i.e. five ints) to per int. The updated algorithm is much more efficient than our previous algorithm, and returns less edits back to the LSP client. 2) The interpretation of Roslyn's LongestCommonSubstring algorithm, which we use to calculate raw edits, was missing a critical piece. Namely, for insertions, we need to keep track of _where_ we should be inserting into the original token set. We don't keep track of this in the existing implementation, resulting in bugs such as #54671. Resolves #54671
allisonchou
2021-08-05T06:06:43Z
2021-08-06T23:44:44Z
b9200d03a76c74d404040d44b9bbe12b1d0a8ef2
f300a818940ea1acef66c946cfa83756729d5e59
Fix LSP semantic tokens algorithm. This PR primarily accomplishes two tasks: 1) Overhauls the existing LSP semantic tokens edits processing algorithm to align with [Razor's](https://github.com/dotnet/aspnetcore-tooling/blob/main/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/Semantic/Services/SemanticTokensEditsDiffer.cs) (shoutout to Ryan and the rest of the Razor team for writing the original 😄). The main change here is going from calculating edits per token (i.e. five ints) to per int. The updated algorithm is much more efficient than our previous algorithm, and returns less edits back to the LSP client. 2) The interpretation of Roslyn's LongestCommonSubstring algorithm, which we use to calculate raw edits, was missing a critical piece. Namely, for insertions, we need to keep track of _where_ we should be inserting into the original token set. We don't keep track of this in the existing implementation, resulting in bugs such as #54671. Resolves #54671
./src/Workspaces/Core/MSBuild/MSBuild/PathResolver.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Diagnostics.CodeAnalysis; using System.IO; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.MSBuild { internal class PathResolver { private readonly DiagnosticReporter _diagnosticReporter; public PathResolver(DiagnosticReporter diagnosticReporter) { _diagnosticReporter = diagnosticReporter; } public bool TryGetAbsoluteSolutionPath(string path, string baseDirectory, DiagnosticReportingMode reportingMode, [NotNullWhen(true)] out string? absolutePath) { try { absolutePath = GetAbsolutePath(path, baseDirectory); } catch (Exception) { _diagnosticReporter.Report(reportingMode, string.Format(WorkspacesResources.Invalid_solution_file_path_colon_0, path)); absolutePath = null; return false; } if (!File.Exists(absolutePath)) { _diagnosticReporter.Report( reportingMode, string.Format(WorkspacesResources.Solution_file_not_found_colon_0, absolutePath), msg => new FileNotFoundException(msg)); return false; } return true; } public bool TryGetAbsoluteProjectPath(string path, string baseDirectory, DiagnosticReportingMode reportingMode, [NotNullWhen(true)] out string? absolutePath) { try { absolutePath = GetAbsolutePath(path, baseDirectory); } catch (Exception) { _diagnosticReporter.Report(reportingMode, string.Format(WorkspacesResources.Invalid_project_file_path_colon_0, path)); absolutePath = null; return false; } if (!File.Exists(absolutePath)) { _diagnosticReporter.Report( reportingMode, string.Format(WorkspacesResources.Project_file_not_found_colon_0, absolutePath), msg => new FileNotFoundException(msg)); return false; } return true; } private static string GetAbsolutePath(string path, string baseDirectory) => FileUtilities.NormalizeAbsolutePath(FileUtilities.ResolveRelativePath(path, baseDirectory) ?? path); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Diagnostics.CodeAnalysis; using System.IO; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.MSBuild { internal class PathResolver { private readonly DiagnosticReporter _diagnosticReporter; public PathResolver(DiagnosticReporter diagnosticReporter) { _diagnosticReporter = diagnosticReporter; } public bool TryGetAbsoluteSolutionPath(string path, string baseDirectory, DiagnosticReportingMode reportingMode, [NotNullWhen(true)] out string? absolutePath) { try { absolutePath = GetAbsolutePath(path, baseDirectory); } catch (Exception) { _diagnosticReporter.Report(reportingMode, string.Format(WorkspacesResources.Invalid_solution_file_path_colon_0, path)); absolutePath = null; return false; } if (!File.Exists(absolutePath)) { _diagnosticReporter.Report( reportingMode, string.Format(WorkspacesResources.Solution_file_not_found_colon_0, absolutePath), msg => new FileNotFoundException(msg)); return false; } return true; } public bool TryGetAbsoluteProjectPath(string path, string baseDirectory, DiagnosticReportingMode reportingMode, [NotNullWhen(true)] out string? absolutePath) { try { absolutePath = GetAbsolutePath(path, baseDirectory); } catch (Exception) { _diagnosticReporter.Report(reportingMode, string.Format(WorkspacesResources.Invalid_project_file_path_colon_0, path)); absolutePath = null; return false; } if (!File.Exists(absolutePath)) { _diagnosticReporter.Report( reportingMode, string.Format(WorkspacesResources.Project_file_not_found_colon_0, absolutePath), msg => new FileNotFoundException(msg)); return false; } return true; } private static string GetAbsolutePath(string path, string baseDirectory) => FileUtilities.NormalizeAbsolutePath(FileUtilities.ResolveRelativePath(path, baseDirectory) ?? path); } }
-1
dotnet/roslyn
55,430
Fix LSP semantic tokens algorithm
This PR primarily accomplishes two tasks: 1) Overhauls the existing LSP semantic tokens edits processing algorithm to align with [Razor's](https://github.com/dotnet/aspnetcore-tooling/blob/main/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/Semantic/Services/SemanticTokensEditsDiffer.cs) (shoutout to Ryan and the rest of the Razor team for writing the original 😄). The main change here is going from calculating edits per token (i.e. five ints) to per int. The updated algorithm is much more efficient than our previous algorithm, and returns less edits back to the LSP client. 2) The interpretation of Roslyn's LongestCommonSubstring algorithm, which we use to calculate raw edits, was missing a critical piece. Namely, for insertions, we need to keep track of _where_ we should be inserting into the original token set. We don't keep track of this in the existing implementation, resulting in bugs such as #54671. Resolves #54671
allisonchou
2021-08-05T06:06:43Z
2021-08-06T23:44:44Z
b9200d03a76c74d404040d44b9bbe12b1d0a8ef2
f300a818940ea1acef66c946cfa83756729d5e59
Fix LSP semantic tokens algorithm. This PR primarily accomplishes two tasks: 1) Overhauls the existing LSP semantic tokens edits processing algorithm to align with [Razor's](https://github.com/dotnet/aspnetcore-tooling/blob/main/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/Semantic/Services/SemanticTokensEditsDiffer.cs) (shoutout to Ryan and the rest of the Razor team for writing the original 😄). The main change here is going from calculating edits per token (i.e. five ints) to per int. The updated algorithm is much more efficient than our previous algorithm, and returns less edits back to the LSP client. 2) The interpretation of Roslyn's LongestCommonSubstring algorithm, which we use to calculate raw edits, was missing a critical piece. Namely, for insertions, we need to keep track of _where_ we should be inserting into the original token set. We don't keep track of this in the existing implementation, resulting in bugs such as #54671. Resolves #54671
./src/Features/Core/Portable/CodeFixes/Suppression/AbstractSuppressionCodeFixProvider.PragmaBatchFixHelpers.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CodeFixes.Suppression { internal partial class AbstractSuppressionCodeFixProvider { /// <summary> /// Helper methods for pragma suppression add/remove batch fixers. /// </summary> private static class PragmaBatchFixHelpers { public static CodeAction CreateBatchPragmaFix( AbstractSuppressionCodeFixProvider suppressionFixProvider, Document document, ImmutableArray<IPragmaBasedCodeAction> pragmaActions, ImmutableArray<Diagnostic> pragmaDiagnostics, FixAllState fixAllState, CancellationToken cancellationToken) { // This is a temporary generated code action, which doesn't need telemetry, hence suppressing RS0005. #pragma warning disable RS0005 // Do not use generic CodeAction.Create to create CodeAction return CodeAction.Create( ((CodeAction)pragmaActions[0]).Title, createChangedDocument: ct => BatchPragmaFixesAsync(suppressionFixProvider, document, pragmaActions, pragmaDiagnostics, cancellationToken), equivalenceKey: fixAllState.CodeActionEquivalenceKey); #pragma warning restore RS0005 // Do not use generic CodeAction.Create to create CodeAction } private static async Task<Document> BatchPragmaFixesAsync( AbstractSuppressionCodeFixProvider suppressionFixProvider, Document document, ImmutableArray<IPragmaBasedCodeAction> pragmaActions, ImmutableArray<Diagnostic> diagnostics, CancellationToken cancellationToken) { // We apply all the pragma suppression fixes sequentially. // At every application, we track the updated locations for remaining diagnostics in the document. var currentDiagnosticSpans = new Dictionary<Diagnostic, TextSpan>(); foreach (var diagnostic in diagnostics) { currentDiagnosticSpans.Add(diagnostic, diagnostic.Location.SourceSpan); } var currentDocument = document; for (var i = 0; i < pragmaActions.Length; i++) { var originalpragmaAction = pragmaActions[i]; var diagnostic = diagnostics[i]; // Get the diagnostic span for the diagnostic in latest document snapshot. if (!currentDiagnosticSpans.TryGetValue(diagnostic, out var currentDiagnosticSpan)) { // Diagnostic whose location conflicts with a prior fix. continue; } // Compute and apply pragma suppression fix. var currentTree = await currentDocument.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false); var currentLocation = Location.Create(currentTree, currentDiagnosticSpan); diagnostic = Diagnostic.Create( id: diagnostic.Id, category: diagnostic.Descriptor.Category, message: diagnostic.GetMessage(), severity: diagnostic.Severity, defaultSeverity: diagnostic.DefaultSeverity, isEnabledByDefault: diagnostic.Descriptor.IsEnabledByDefault, warningLevel: diagnostic.WarningLevel, title: diagnostic.Descriptor.Title, description: diagnostic.Descriptor.Description, helpLink: diagnostic.Descriptor.HelpLinkUri, location: currentLocation, additionalLocations: diagnostic.AdditionalLocations, customTags: diagnostic.Descriptor.CustomTags, properties: diagnostic.Properties, isSuppressed: diagnostic.IsSuppressed); var newSuppressionFixes = await suppressionFixProvider.GetFixesAsync(currentDocument, currentDiagnosticSpan, SpecializedCollections.SingletonEnumerable(diagnostic), cancellationToken).ConfigureAwait(false); var newSuppressionFix = newSuppressionFixes.SingleOrDefault(); if (newSuppressionFix != null) { var newPragmaAction = newSuppressionFix.Action as IPragmaBasedCodeAction ?? newSuppressionFix.Action.NestedCodeActions.OfType<IPragmaBasedCodeAction>().SingleOrDefault(); if (newPragmaAction != null) { // Get the text changes with pragma suppression add/removals. // Note: We do it one token at a time to ensure we get single text change in the new document, otherwise UpdateDiagnosticSpans won't function as expected. // Update the diagnostics spans based on the text changes. var startTokenChanges = await GetTextChangesAsync(newPragmaAction, currentDocument, includeStartTokenChange: true, includeEndTokenChange: false, cancellationToken: cancellationToken).ConfigureAwait(false); var endTokenChanges = await GetTextChangesAsync(newPragmaAction, currentDocument, includeStartTokenChange: false, includeEndTokenChange: true, cancellationToken: cancellationToken).ConfigureAwait(false); var currentText = await currentDocument.GetTextAsync(cancellationToken).ConfigureAwait(false); var orderedChanges = startTokenChanges.Concat(endTokenChanges).OrderBy(change => change.Span).Distinct(); var newText = currentText.WithChanges(orderedChanges); currentDocument = currentDocument.WithText(newText); // Update the diagnostics spans based on the text changes. UpdateDiagnosticSpans(diagnostics, currentDiagnosticSpans, orderedChanges); } } } return currentDocument; } private static async Task<IEnumerable<TextChange>> GetTextChangesAsync( IPragmaBasedCodeAction pragmaAction, Document currentDocument, bool includeStartTokenChange, bool includeEndTokenChange, CancellationToken cancellationToken) { var newDocument = await pragmaAction.GetChangedDocumentAsync(includeStartTokenChange, includeEndTokenChange, cancellationToken).ConfigureAwait(false); return await newDocument.GetTextChangesAsync(currentDocument, cancellationToken).ConfigureAwait(false); } private static void UpdateDiagnosticSpans(ImmutableArray<Diagnostic> diagnostics, Dictionary<Diagnostic, TextSpan> currentDiagnosticSpans, IEnumerable<TextChange> textChanges) { static bool IsPriorSpan(TextSpan span, TextChange textChange) => span.End <= textChange.Span.Start; static bool IsFollowingSpan(TextSpan span, TextChange textChange) => span.Start >= textChange.Span.End; static bool IsEnclosingSpan(TextSpan span, TextChange textChange) => span.Contains(textChange.Span); foreach (var diagnostic in diagnostics) { // We use 'originalSpan' to identify if the diagnostic is prior/following/enclosing with respect to each text change. // We use 'currentSpan' to track updates made to the originalSpan by each text change. if (!currentDiagnosticSpans.TryGetValue(diagnostic, out var originalSpan)) { continue; } var currentSpan = originalSpan; foreach (var textChange in textChanges) { if (IsPriorSpan(originalSpan, textChange)) { // Prior span, needs no update. continue; } var delta = textChange.NewText.Length - textChange.Span.Length; if (delta != 0) { if (IsFollowingSpan(originalSpan, textChange)) { // Following span. var newStart = currentSpan.Start + delta; currentSpan = new TextSpan(newStart, currentSpan.Length); currentDiagnosticSpans[diagnostic] = currentSpan; } else if (IsEnclosingSpan(originalSpan, textChange)) { // Enclosing span. var newLength = currentSpan.Length + delta; currentSpan = new TextSpan(currentSpan.Start, newLength); currentDiagnosticSpans[diagnostic] = currentSpan; } else { // Overlapping span. // Drop conflicting diagnostics. currentDiagnosticSpans.Remove(diagnostic); 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. #nullable disable using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CodeFixes.Suppression { internal partial class AbstractSuppressionCodeFixProvider { /// <summary> /// Helper methods for pragma suppression add/remove batch fixers. /// </summary> private static class PragmaBatchFixHelpers { public static CodeAction CreateBatchPragmaFix( AbstractSuppressionCodeFixProvider suppressionFixProvider, Document document, ImmutableArray<IPragmaBasedCodeAction> pragmaActions, ImmutableArray<Diagnostic> pragmaDiagnostics, FixAllState fixAllState, CancellationToken cancellationToken) { // This is a temporary generated code action, which doesn't need telemetry, hence suppressing RS0005. #pragma warning disable RS0005 // Do not use generic CodeAction.Create to create CodeAction return CodeAction.Create( ((CodeAction)pragmaActions[0]).Title, createChangedDocument: ct => BatchPragmaFixesAsync(suppressionFixProvider, document, pragmaActions, pragmaDiagnostics, cancellationToken), equivalenceKey: fixAllState.CodeActionEquivalenceKey); #pragma warning restore RS0005 // Do not use generic CodeAction.Create to create CodeAction } private static async Task<Document> BatchPragmaFixesAsync( AbstractSuppressionCodeFixProvider suppressionFixProvider, Document document, ImmutableArray<IPragmaBasedCodeAction> pragmaActions, ImmutableArray<Diagnostic> diagnostics, CancellationToken cancellationToken) { // We apply all the pragma suppression fixes sequentially. // At every application, we track the updated locations for remaining diagnostics in the document. var currentDiagnosticSpans = new Dictionary<Diagnostic, TextSpan>(); foreach (var diagnostic in diagnostics) { currentDiagnosticSpans.Add(diagnostic, diagnostic.Location.SourceSpan); } var currentDocument = document; for (var i = 0; i < pragmaActions.Length; i++) { var originalpragmaAction = pragmaActions[i]; var diagnostic = diagnostics[i]; // Get the diagnostic span for the diagnostic in latest document snapshot. if (!currentDiagnosticSpans.TryGetValue(diagnostic, out var currentDiagnosticSpan)) { // Diagnostic whose location conflicts with a prior fix. continue; } // Compute and apply pragma suppression fix. var currentTree = await currentDocument.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false); var currentLocation = Location.Create(currentTree, currentDiagnosticSpan); diagnostic = Diagnostic.Create( id: diagnostic.Id, category: diagnostic.Descriptor.Category, message: diagnostic.GetMessage(), severity: diagnostic.Severity, defaultSeverity: diagnostic.DefaultSeverity, isEnabledByDefault: diagnostic.Descriptor.IsEnabledByDefault, warningLevel: diagnostic.WarningLevel, title: diagnostic.Descriptor.Title, description: diagnostic.Descriptor.Description, helpLink: diagnostic.Descriptor.HelpLinkUri, location: currentLocation, additionalLocations: diagnostic.AdditionalLocations, customTags: diagnostic.Descriptor.CustomTags, properties: diagnostic.Properties, isSuppressed: diagnostic.IsSuppressed); var newSuppressionFixes = await suppressionFixProvider.GetFixesAsync(currentDocument, currentDiagnosticSpan, SpecializedCollections.SingletonEnumerable(diagnostic), cancellationToken).ConfigureAwait(false); var newSuppressionFix = newSuppressionFixes.SingleOrDefault(); if (newSuppressionFix != null) { var newPragmaAction = newSuppressionFix.Action as IPragmaBasedCodeAction ?? newSuppressionFix.Action.NestedCodeActions.OfType<IPragmaBasedCodeAction>().SingleOrDefault(); if (newPragmaAction != null) { // Get the text changes with pragma suppression add/removals. // Note: We do it one token at a time to ensure we get single text change in the new document, otherwise UpdateDiagnosticSpans won't function as expected. // Update the diagnostics spans based on the text changes. var startTokenChanges = await GetTextChangesAsync(newPragmaAction, currentDocument, includeStartTokenChange: true, includeEndTokenChange: false, cancellationToken: cancellationToken).ConfigureAwait(false); var endTokenChanges = await GetTextChangesAsync(newPragmaAction, currentDocument, includeStartTokenChange: false, includeEndTokenChange: true, cancellationToken: cancellationToken).ConfigureAwait(false); var currentText = await currentDocument.GetTextAsync(cancellationToken).ConfigureAwait(false); var orderedChanges = startTokenChanges.Concat(endTokenChanges).OrderBy(change => change.Span).Distinct(); var newText = currentText.WithChanges(orderedChanges); currentDocument = currentDocument.WithText(newText); // Update the diagnostics spans based on the text changes. UpdateDiagnosticSpans(diagnostics, currentDiagnosticSpans, orderedChanges); } } } return currentDocument; } private static async Task<IEnumerable<TextChange>> GetTextChangesAsync( IPragmaBasedCodeAction pragmaAction, Document currentDocument, bool includeStartTokenChange, bool includeEndTokenChange, CancellationToken cancellationToken) { var newDocument = await pragmaAction.GetChangedDocumentAsync(includeStartTokenChange, includeEndTokenChange, cancellationToken).ConfigureAwait(false); return await newDocument.GetTextChangesAsync(currentDocument, cancellationToken).ConfigureAwait(false); } private static void UpdateDiagnosticSpans(ImmutableArray<Diagnostic> diagnostics, Dictionary<Diagnostic, TextSpan> currentDiagnosticSpans, IEnumerable<TextChange> textChanges) { static bool IsPriorSpan(TextSpan span, TextChange textChange) => span.End <= textChange.Span.Start; static bool IsFollowingSpan(TextSpan span, TextChange textChange) => span.Start >= textChange.Span.End; static bool IsEnclosingSpan(TextSpan span, TextChange textChange) => span.Contains(textChange.Span); foreach (var diagnostic in diagnostics) { // We use 'originalSpan' to identify if the diagnostic is prior/following/enclosing with respect to each text change. // We use 'currentSpan' to track updates made to the originalSpan by each text change. if (!currentDiagnosticSpans.TryGetValue(diagnostic, out var originalSpan)) { continue; } var currentSpan = originalSpan; foreach (var textChange in textChanges) { if (IsPriorSpan(originalSpan, textChange)) { // Prior span, needs no update. continue; } var delta = textChange.NewText.Length - textChange.Span.Length; if (delta != 0) { if (IsFollowingSpan(originalSpan, textChange)) { // Following span. var newStart = currentSpan.Start + delta; currentSpan = new TextSpan(newStart, currentSpan.Length); currentDiagnosticSpans[diagnostic] = currentSpan; } else if (IsEnclosingSpan(originalSpan, textChange)) { // Enclosing span. var newLength = currentSpan.Length + delta; currentSpan = new TextSpan(currentSpan.Start, newLength); currentDiagnosticSpans[diagnostic] = currentSpan; } else { // Overlapping span. // Drop conflicting diagnostics. currentDiagnosticSpans.Remove(diagnostic); break; } } } } } } } }
-1
dotnet/roslyn
55,430
Fix LSP semantic tokens algorithm
This PR primarily accomplishes two tasks: 1) Overhauls the existing LSP semantic tokens edits processing algorithm to align with [Razor's](https://github.com/dotnet/aspnetcore-tooling/blob/main/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/Semantic/Services/SemanticTokensEditsDiffer.cs) (shoutout to Ryan and the rest of the Razor team for writing the original 😄). The main change here is going from calculating edits per token (i.e. five ints) to per int. The updated algorithm is much more efficient than our previous algorithm, and returns less edits back to the LSP client. 2) The interpretation of Roslyn's LongestCommonSubstring algorithm, which we use to calculate raw edits, was missing a critical piece. Namely, for insertions, we need to keep track of _where_ we should be inserting into the original token set. We don't keep track of this in the existing implementation, resulting in bugs such as #54671. Resolves #54671
allisonchou
2021-08-05T06:06:43Z
2021-08-06T23:44:44Z
b9200d03a76c74d404040d44b9bbe12b1d0a8ef2
f300a818940ea1acef66c946cfa83756729d5e59
Fix LSP semantic tokens algorithm. This PR primarily accomplishes two tasks: 1) Overhauls the existing LSP semantic tokens edits processing algorithm to align with [Razor's](https://github.com/dotnet/aspnetcore-tooling/blob/main/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/Semantic/Services/SemanticTokensEditsDiffer.cs) (shoutout to Ryan and the rest of the Razor team for writing the original 😄). The main change here is going from calculating edits per token (i.e. five ints) to per int. The updated algorithm is much more efficient than our previous algorithm, and returns less edits back to the LSP client. 2) The interpretation of Roslyn's LongestCommonSubstring algorithm, which we use to calculate raw edits, was missing a critical piece. Namely, for insertions, we need to keep track of _where_ we should be inserting into the original token set. We don't keep track of this in the existing implementation, resulting in bugs such as #54671. Resolves #54671
./src/Compilers/CSharp/Test/IOperation/IOperation/IOperationTests_ILocalFunctionStatement.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.Syntax; using Microsoft.CodeAnalysis.FlowAnalysis; using Microsoft.CodeAnalysis.Operations; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public class IOperationTests_ILocalFunctionStatement : SemanticModelTestBase { [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void TestLocalFunction_ContainingMethodParameterReference() { string source = @" class C { public void M(int x) { /*<bind>*/int Local(int p1) { return x++; }/*</bind>*/ Local(0); } } "; string expectedOperationTree = @" ILocalFunctionOperation (Symbol: System.Int32 Local(System.Int32 p1)) (OperationKind.LocalFunction, Type: null) (Syntax: 'int Local(i ... }') IBlockOperation (1 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }') IReturnOperation (OperationKind.Return, Type: null) (Syntax: 'return x++;') ReturnedValue: IIncrementOrDecrementOperation (Postfix) (OperationKind.Increment, Type: System.Int32) (Syntax: 'x++') Target: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'x') "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<LocalFunctionStatementSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void TestLocalFunction_ContainingMethodParameterReference_ExpressionBodied() { string source = @" class C { public void M(int x) { /*<bind>*/int Local(int p1) => x++;/*</bind>*/ Local(0); } } "; string expectedOperationTree = @" ILocalFunctionOperation (Symbol: System.Int32 Local(System.Int32 p1)) (OperationKind.LocalFunction, Type: null) (Syntax: 'int Local(i ... p1) => x++;') IBlockOperation (1 statements) (OperationKind.Block, Type: null) (Syntax: '=> x++') IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'x++') ReturnedValue: IIncrementOrDecrementOperation (Postfix) (OperationKind.Increment, Type: System.Int32) (Syntax: 'x++') Target: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'x') "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<LocalFunctionStatementSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void TestLocalFunction_LocalFunctionParameterReference() { string source = @" class C { public void M() { /*<bind>*/int Local(int x) => x++;/*</bind>*/ Local(0); } } "; string expectedOperationTree = @" ILocalFunctionOperation (Symbol: System.Int32 Local(System.Int32 x)) (OperationKind.LocalFunction, Type: null) (Syntax: 'int Local(int x) => x++;') IBlockOperation (1 statements) (OperationKind.Block, Type: null) (Syntax: '=> x++') IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'x++') ReturnedValue: IIncrementOrDecrementOperation (Postfix) (OperationKind.Increment, Type: System.Int32) (Syntax: 'x++') Target: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'x') "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<LocalFunctionStatementSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void TestLocalFunction_ContainingLocalFunctionParameterReference() { string source = @" class C { public void M() { int LocalOuter (int x) { /*<bind>*/int Local(int y) => x + y;/*</bind>*/ return Local(x); } LocalOuter(0); } } "; string expectedOperationTree = @" ILocalFunctionOperation (Symbol: System.Int32 Local(System.Int32 y)) (OperationKind.LocalFunction, Type: null) (Syntax: 'int Local(i ... ) => x + y;') IBlockOperation (1 statements) (OperationKind.Block, Type: null) (Syntax: '=> x + y') IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'x + y') ReturnedValue: IBinaryOperation (BinaryOperatorKind.Add) (OperationKind.Binary, Type: System.Int32) (Syntax: 'x + y') Left: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'x') Right: IParameterReferenceOperation: y (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'y') "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<LocalFunctionStatementSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void TestLocalFunction_LocalFunctionReference() { string source = @" class C { public void M() { int x; int Local(int p1) => x++; int Local2(int p1) => Local(p1); /*<bind>*/int Local3(int p1) => x + Local2(p1);/*</bind>*/ Local3(x = 0); } } "; string expectedOperationTree = @" ILocalFunctionOperation (Symbol: System.Int32 Local3(System.Int32 p1)) (OperationKind.LocalFunction, Type: null) (Syntax: 'int Local3( ... Local2(p1);') IBlockOperation (1 statements) (OperationKind.Block, Type: null) (Syntax: '=> x + Local2(p1)') IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'x + Local2(p1)') ReturnedValue: IBinaryOperation (BinaryOperatorKind.Add) (OperationKind.Binary, Type: System.Int32) (Syntax: 'x + Local2(p1)') Left: ILocalReferenceOperation: x (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'x') Right: IInvocationOperation (System.Int32 Local2(System.Int32 p1)) (OperationKind.Invocation, Type: System.Int32) (Syntax: 'Local2(p1)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: p1) (OperationKind.Argument, Type: null) (Syntax: 'p1') IParameterReferenceOperation: p1 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'p1') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<LocalFunctionStatementSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void TestLocalFunction_Recursion() { string source = @" class C { public void M(int x) { /*<bind>*/int Local(int p1) => Local(x + p1);/*</bind>*/ } } "; string expectedOperationTree = @" ILocalFunctionOperation (Symbol: System.Int32 Local(System.Int32 p1)) (OperationKind.LocalFunction, Type: null) (Syntax: 'int Local(i ... al(x + p1);') IBlockOperation (1 statements) (OperationKind.Block, Type: null) (Syntax: '=> Local(x + p1)') IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'Local(x + p1)') ReturnedValue: IInvocationOperation (System.Int32 Local(System.Int32 p1)) (OperationKind.Invocation, Type: System.Int32) (Syntax: 'Local(x + p1)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: p1) (OperationKind.Argument, Type: null) (Syntax: 'x + p1') IBinaryOperation (BinaryOperatorKind.Add) (OperationKind.Binary, Type: System.Int32) (Syntax: 'x + p1') Left: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'x') Right: IParameterReferenceOperation: p1 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'p1') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<LocalFunctionStatementSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void TestLocalFunction_Async() { string source = @" using System.Threading.Tasks; class C { public void M(int x) { /*<bind>*/async Task<int> LocalAsync(int p1) { await Task.Delay(0); return x + p1; }/*</bind>*/ LocalAsync(0).Wait(); } } "; string expectedOperationTree = @" ILocalFunctionOperation (Symbol: System.Threading.Tasks.Task<System.Int32> LocalAsync(System.Int32 p1)) (OperationKind.LocalFunction, Type: null) (Syntax: 'async Task< ... }') IBlockOperation (2 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'await Task.Delay(0);') Expression: IAwaitOperation (OperationKind.Await, Type: System.Void) (Syntax: 'await Task.Delay(0)') Expression: IInvocationOperation (System.Threading.Tasks.Task System.Threading.Tasks.Task.Delay(System.Int32 millisecondsDelay)) (OperationKind.Invocation, Type: System.Threading.Tasks.Task) (Syntax: 'Task.Delay(0)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: millisecondsDelay) (OperationKind.Argument, Type: null) (Syntax: '0') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IReturnOperation (OperationKind.Return, Type: null) (Syntax: 'return x + p1;') ReturnedValue: IBinaryOperation (BinaryOperatorKind.Add) (OperationKind.Binary, Type: System.Int32) (Syntax: 'x + p1') Left: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'x') Right: IParameterReferenceOperation: p1 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'p1') "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<LocalFunctionStatementSyntax>(source, expectedOperationTree, expectedDiagnostics, useLatestFrameworkReferences: true); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void TestLocalFunction_CaptureForEachVar() { string source = @" class C { public void M(int[] array) { foreach (var x in array) { /*<bind>*/int Local() => x;/*</bind>*/ Local(); } } } "; string expectedOperationTree = @" ILocalFunctionOperation (Symbol: System.Int32 Local()) (OperationKind.LocalFunction, Type: null) (Syntax: 'int Local() => x;') IBlockOperation (1 statements) (OperationKind.Block, Type: null) (Syntax: '=> x') IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'x') ReturnedValue: ILocalReferenceOperation: x (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'x') "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<LocalFunctionStatementSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void TestLocalFunction_UseOfUnusedVar() { string source = @" class C { void M() { F(); int x = 0; /*<bind>*/void F() => x++;/*</bind>*/ } } "; string expectedOperationTree = @" ILocalFunctionOperation (Symbol: void F()) (OperationKind.LocalFunction, Type: null) (Syntax: 'void F() => x++;') IBlockOperation (2 statements) (OperationKind.Block, Type: null) (Syntax: '=> x++') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsImplicit) (Syntax: 'x++') Expression: IIncrementOrDecrementOperation (Postfix) (OperationKind.Increment, Type: System.Int32) (Syntax: 'x++') Target: ILocalReferenceOperation: x (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'x') IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: '=> x++') ReturnedValue: null "; var expectedDiagnostics = new DiagnosticDescription[] { // CS0165: Use of unassigned local variable 'x' // F(); Diagnostic(ErrorCode.ERR_UseDefViolation, "F()").WithArguments("x").WithLocation(6, 9) }; VerifyOperationTreeAndDiagnosticsForTest<LocalFunctionStatementSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void TestLocalFunction_OutVar() { string source = @" class C { void M(int p) { int x; /*<bind>*/void F(out int y) => y = p;/*</bind>*/ F(out x); } } "; string expectedOperationTree = @" ILocalFunctionOperation (Symbol: void F(out System.Int32 y)) (OperationKind.LocalFunction, Type: null) (Syntax: 'void F(out ... ) => y = p;') IBlockOperation (2 statements) (OperationKind.Block, Type: null) (Syntax: '=> y = p') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsImplicit) (Syntax: 'y = p') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'y = p') Left: IParameterReferenceOperation: y (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'y') Right: IParameterReferenceOperation: p (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'p') IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: '=> y = p') ReturnedValue: null "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<LocalFunctionStatementSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void TestInvalidLocalFunction_MissingBody() { string source = @" class C { void M(int p) { /*<bind>*/void F(out int y) => ;/*</bind>*/ } } "; string expectedOperationTree = @" ILocalFunctionOperation (Symbol: void F(out System.Int32 y)) (OperationKind.LocalFunction, Type: null, IsInvalid) (Syntax: 'void F(out int y) => ;') IBlockOperation (2 statements) (OperationKind.Block, Type: null, IsInvalid) (Syntax: '=> ') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid, IsImplicit) (Syntax: '') Expression: IInvalidOperation (OperationKind.Invalid, Type: null, IsInvalid) (Syntax: '') Children(0) IReturnOperation (OperationKind.Return, Type: null, IsInvalid, IsImplicit) (Syntax: '=> ') ReturnedValue: null "; var expectedDiagnostics = new DiagnosticDescription[] { // file.cs(6,40): error CS1525: Invalid expression term ';' // /*<bind>*/void F(out int y) => ;/*</bind>*/ Diagnostic(ErrorCode.ERR_InvalidExprTerm, ";").WithArguments(";").WithLocation(6, 40), // file.cs(6,24): error CS0177: The out parameter 'y' must be assigned to before control leaves the current method // /*<bind>*/void F(out int y) => ;/*</bind>*/ Diagnostic(ErrorCode.ERR_ParamUnassigned, "F").WithArguments("y").WithLocation(6, 24), // file.cs(6,24): warning CS8321: The local function 'F' is declared but never used // /*<bind>*/void F(out int y) => ;/*</bind>*/ Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "F").WithArguments("F").WithLocation(6, 24) }; VerifyOperationTreeAndDiagnosticsForTest<LocalFunctionStatementSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void TestInvalidLocalFunction_MissingParameters() { string source = @" class C { void M(int p) { /*<bind>*/void F( { }/*</bind>*/; } } "; string expectedOperationTree = @" ILocalFunctionOperation (Symbol: void F()) (OperationKind.LocalFunction, Type: null, IsInvalid) (Syntax: 'void F( { }') IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsInvalid) (Syntax: '{ }') IReturnOperation (OperationKind.Return, Type: null, IsInvalid, IsImplicit) (Syntax: '{ }') ReturnedValue: null "; var expectedDiagnostics = new DiagnosticDescription[] { // file.cs(6,27): error CS1026: ) expected // /*<bind>*/void F( { }/*</bind>*/; Diagnostic(ErrorCode.ERR_CloseParenExpected, "{").WithLocation(6, 27), // file.cs(6,24): warning CS8321: The local function 'F' is declared but never used // /*<bind>*/void F( { }/*</bind>*/; Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "F").WithArguments("F").WithLocation(6, 24) }; VerifyOperationTreeAndDiagnosticsForTest<LocalFunctionStatementSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void TestInvalidLocalFunction_InvalidReturnType() { string source = @" class C { void M(int p) { /*<bind>*/X F() { }/*</bind>*/; } } "; string expectedOperationTree = @" ILocalFunctionOperation (Symbol: X F()) (OperationKind.LocalFunction, Type: null, IsInvalid) (Syntax: 'X F() { }') IBlockOperation (0 statements) (OperationKind.Block, Type: null) (Syntax: '{ }') "; var expectedDiagnostics = new DiagnosticDescription[] { // CS0161: 'F()': not all code paths return a value // /*<bind>*/X F() { }/*</bind>*/; Diagnostic(ErrorCode.ERR_ReturnExpected, "F").WithArguments("F()").WithLocation(6, 21), // CS0246: The type or namespace name 'X' could not be found (are you missing a using directive or an assembly reference?) // /*<bind>*/X F() { }/*</bind>*/; Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "X").WithArguments("X").WithLocation(6, 19), // CS8321: The local function 'F' is declared but never used // /*<bind>*/X F() { }/*</bind>*/; Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "F").WithArguments("F").WithLocation(6, 21) }; VerifyOperationTreeAndDiagnosticsForTest<LocalFunctionStatementSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(24650, "https://github.com/dotnet/roslyn/issues/24650")] public void TestInvalidLocalFunction_ExpressionAndBlockBody() { string source = @" class C { void M(int p) { /*<bind>*/object F() => new object(); { return null; }/*</bind>*/; } } "; string expectedOperationTree = @" ILocalFunctionOperation (Symbol: System.Object F()) (OperationKind.LocalFunction, Type: null) (Syntax: 'object F() ... w object();') IBlockOperation (1 statements) (OperationKind.Block, Type: null) (Syntax: '=> new object()') IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'new object()') ReturnedValue: IObjectCreationOperation (Constructor: System.Object..ctor()) (OperationKind.ObjectCreation, Type: System.Object) (Syntax: 'new object()') Arguments(0) Initializer: null "; var expectedDiagnostics = new DiagnosticDescription[] { // file.cs(6,49): error CS0127: Since 'C.M(int)' returns void, a return keyword must not be followed by an object expression // /*<bind>*/object F() => new object(); { return new object(); }/*</bind>*/; Diagnostic(ErrorCode.ERR_RetNoObjectRequired, "return").WithArguments("C.M(int)").WithLocation(6, 49), // file.cs(6,26): warning CS8321: The local function 'F' is declared but never used // /*<bind>*/object F() => new object(); { return new object(); }/*</bind>*/; Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "F").WithArguments("F").WithLocation(6, 26) }; VerifyOperationTreeAndDiagnosticsForTest<LocalFunctionStatementSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(24650, "https://github.com/dotnet/roslyn/issues/24650")] public void TestInvalidLocalFunction_BlockAndExpressionBody() { string source = @" class C { void M(int p) { /*<bind>*/object F() { return new object(); } => null;/*</bind>*/; } } "; string expectedOperationTree = @" ILocalFunctionOperation (Symbol: System.Object F()) (OperationKind.LocalFunction, Type: null, IsInvalid) (Syntax: 'object F() ... } => null;') Body: IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsInvalid) (Syntax: '{ return new object(); }') IReturnOperation (OperationKind.Return, Type: null, IsInvalid) (Syntax: 'return new object();') ReturnedValue: IObjectCreationOperation (Constructor: System.Object..ctor()) (OperationKind.ObjectCreation, Type: System.Object, IsInvalid) (Syntax: 'new object()') Arguments(0) Initializer: null IgnoredBody: IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsInvalid) (Syntax: '=> null') IReturnOperation (OperationKind.Return, Type: null, IsInvalid, IsImplicit) (Syntax: 'null') ReturnedValue: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, Constant: null, IsInvalid, IsImplicit) (Syntax: 'null') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: null, Constant: null, IsInvalid) (Syntax: 'null') "; var expectedDiagnostics = new DiagnosticDescription[] { // error CS8057: Block bodies and expression bodies cannot both be provided. // /*<bind>*/object F() { return new object(); } => null;/*</bind>*/; Diagnostic(ErrorCode.ERR_BlockBodyAndExpressionBody, "object F() { return new object(); } => null;").WithLocation(6, 19), // warning CS8321: The local function 'F' is declared but never used // /*<bind>*/object F() { return new object(); } => null;/*</bind>*/; Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "F").WithArguments("F").WithLocation(6, 26) }; VerifyOperationTreeAndDiagnosticsForTest<LocalFunctionStatementSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(24650, "https://github.com/dotnet/roslyn/issues/24650")] public void TestLocalFunction_ExpressionBodyInnerMember() { string source = @" class C { public void M(int x) { int Local(int p1) /*<bind>*/=> x++/*</bind>*/; Local(0); } } "; string expectedOperationTree = @" IBlockOperation (1 statements) (OperationKind.Block, Type: null) (Syntax: '=> x++') IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'x++') ReturnedValue: IIncrementOrDecrementOperation (Postfix) (OperationKind.Increment, Type: System.Int32) (Syntax: 'x++') Target: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'x') "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<ArrowExpressionClauseSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void TestLocalFunction_StaticWithShadowedVariableReference() { string source = @"#pragma warning disable 8321 class C { static void M(int x) { /*<bind>*/ static int Local(int y) { if (y > 0) { int x = (int)y; return x; } return x; } /*</bind>*/ } }"; string expectedOperationTree = @" ILocalFunctionOperation (Symbol: System.Int32 Local(System.Int32 y)) (OperationKind.LocalFunction, Type: null, IsInvalid) (Syntax: 'static int ... }') IBlockOperation (2 statements) (OperationKind.Block, Type: null, IsInvalid) (Syntax: '{ ... }') IConditionalOperation (OperationKind.Conditional, Type: null) (Syntax: 'if (y > 0) ... }') Condition: IBinaryOperation (BinaryOperatorKind.GreaterThan) (OperationKind.Binary, Type: System.Boolean) (Syntax: 'y > 0') Left: IParameterReferenceOperation: y (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'y') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0') WhenTrue: IBlockOperation (2 statements, 1 locals) (OperationKind.Block, Type: null) (Syntax: '{ ... }') Locals: Local_1: System.Int32 x IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null) (Syntax: 'int x = (int)y;') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'int x = (int)y') Declarators: IVariableDeclaratorOperation (Symbol: System.Int32 x) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'x = (int)y') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= (int)y') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32) (Syntax: '(int)y') Conversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: IParameterReferenceOperation: y (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'y') Initializer: null IReturnOperation (OperationKind.Return, Type: null) (Syntax: 'return x;') ReturnedValue: ILocalReferenceOperation: x (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'x') WhenFalse: null IReturnOperation (OperationKind.Return, Type: null, IsInvalid) (Syntax: 'return x;') ReturnedValue: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Int32, IsInvalid) (Syntax: 'x') "; var expectedDiagnostics = new[] { // (14,20): error CS8421: A static local function cannot contain a reference to 'x'. // return x; Diagnostic(ErrorCode.ERR_StaticLocalFunctionCannotCaptureVariable, "x").WithArguments("x").WithLocation(14, 20) }; VerifyOperationTreeAndDiagnosticsForTest<LocalFunctionStatementSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void TestLocalFunction_StaticWithThisReference() { string source = @"#pragma warning disable 8321 class C { void M() { /*<bind>*/ static object Local() => ToString() + this.GetHashCode() + base.GetHashCode(); /*</bind>*/ } }"; string expectedOperationTree = @" ILocalFunctionOperation (Symbol: System.Object Local()) (OperationKind.LocalFunction, Type: null, IsInvalid) (Syntax: 'static obje ... HashCode();') IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsInvalid) (Syntax: '=> ToString ... tHashCode()') IReturnOperation (OperationKind.Return, Type: null, IsInvalid, IsImplicit) (Syntax: 'ToString() ... tHashCode()') ReturnedValue: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsInvalid, IsImplicit) (Syntax: 'ToString() ... tHashCode()') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) Operand: IBinaryOperation (BinaryOperatorKind.Add) (OperationKind.Binary, Type: System.String, IsInvalid) (Syntax: 'ToString() ... tHashCode()') Left: IBinaryOperation (BinaryOperatorKind.Add) (OperationKind.Binary, Type: System.String, IsInvalid) (Syntax: 'ToString() ... tHashCode()') Left: IInvocationOperation (virtual System.String System.Object.ToString()) (OperationKind.Invocation, Type: System.String, IsInvalid) (Syntax: 'ToString()') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C, IsInvalid, IsImplicit) (Syntax: 'ToString') Arguments(0) Right: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsInvalid, IsImplicit) (Syntax: 'this.GetHashCode()') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: IInvocationOperation (virtual System.Int32 System.Object.GetHashCode()) (OperationKind.Invocation, Type: System.Int32, IsInvalid) (Syntax: 'this.GetHashCode()') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C, IsInvalid) (Syntax: 'this') Arguments(0) Right: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsInvalid, IsImplicit) (Syntax: 'base.GetHashCode()') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: IInvocationOperation ( System.Int32 System.Object.GetHashCode()) (OperationKind.Invocation, Type: System.Int32, IsInvalid) (Syntax: 'base.GetHashCode()') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: System.Object, IsInvalid) (Syntax: 'base') Arguments(0) "; var expectedDiagnostics = new[] { // (7,34): error CS8422: A static local function cannot contain a reference to 'this' or 'base'. // static object Local() => ToString() + this.GetHashCode() + base.GetHashCode(); Diagnostic(ErrorCode.ERR_StaticLocalFunctionCannotCaptureThis, "ToString").WithLocation(7, 34), // (7,47): error CS8422: A static local function cannot contain a reference to 'this' or 'base'. // static object Local() => ToString() + this.GetHashCode() + base.GetHashCode(); Diagnostic(ErrorCode.ERR_StaticLocalFunctionCannotCaptureThis, "this").WithLocation(7, 47), // (7,68): error CS8422: A static local function cannot contain a reference to 'this' or 'base'. // static object Local() => ToString() + this.GetHashCode() + base.GetHashCode(); Diagnostic(ErrorCode.ERR_StaticLocalFunctionCannotCaptureThis, "base").WithLocation(7, 68) }; VerifyOperationTreeAndDiagnosticsForTest<LocalFunctionStatementSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void LocalFunctionFlow_01() { string source = @" struct C { void M() /*<bind>*/{ void local(bool result, bool input) { result = input; } local(false, true); }/*</bind>*/ } "; string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { Methods: [void local(System.Boolean result, System.Boolean input)] Block[B1] - Block Predecessors: [B0] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'local(false, true);') Expression: IInvocationOperation (void local(System.Boolean result, System.Boolean input)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'local(false, true)') Instance Receiver: null Arguments(2): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: result) (OperationKind.Argument, Type: null) (Syntax: 'false') ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: False) (Syntax: 'false') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: input) (OperationKind.Argument, Type: null) (Syntax: 'true') ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Next (Regular) Block[B2] Leaving: {R1} { void local(System.Boolean result, System.Boolean input) Block[B0#0R1] - Entry Statements (0) Next (Regular) Block[B1#0R1] Block[B1#0R1] - Block Predecessors: [B0#0R1] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = input;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'result = input') Left: IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'result') Right: IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'input') Next (Regular) Block[B2#0R1] Block[B2#0R1] - Exit Predecessors: [B1#0R1] Statements (0) } } Block[B2] - Exit Predecessors: [B1] Statements (0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void LocalFunctionFlow_02() { string source = @" #pragma warning disable CS8321 struct C { void M() /*<bind>*/{ void local(bool result, bool input) { result = input; } }/*</bind>*/ } "; string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { Methods: [void local(System.Boolean result, System.Boolean input)] Block[B1] - Block Predecessors: [B0] Statements (0) Next (Regular) Block[B2] Leaving: {R1} { void local(System.Boolean result, System.Boolean input) Block[B0#0R1] - Entry Statements (0) Next (Regular) Block[B1#0R1] Block[B1#0R1] - Block Predecessors: [B0#0R1] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = input;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'result = input') Left: IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'result') Right: IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'input') Next (Regular) Block[B2#0R1] Block[B2#0R1] - Exit Predecessors: [B1#0R1] Statements (0) } } Block[B2] - Exit Predecessors: [B1] Statements (0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void LocalFunctionFlow_03() { string source = @" #pragma warning disable CS8321 struct C { void M() /*<bind>*/{ void local(bool result, bool input) }/*</bind>*/ } "; string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { Methods: [void local(System.Boolean result, System.Boolean input)] Block[B1] - Block Predecessors: [B0] Statements (0) Next (Regular) Block[B2] Leaving: {R1} { void local(System.Boolean result, System.Boolean input) Block[B0#0R1] - Entry Statements (0) Next (Regular) Block[B1#0R1] Block[B1#0R1] - Exit Predecessors: [B0#0R1] Statements (0) } } Block[B2] - Exit Predecessors: [B1] Statements (0) "; var expectedDiagnostics = new[] { // file.cs(7,44): error CS1002: ; expected // void local(bool result, bool input) Diagnostic(ErrorCode.ERR_SemicolonExpected, "").WithLocation(7, 44), // file.cs(7,14): error CS8112: 'local(bool, bool)' is a local function and must therefore always have a body. // void local(bool result, bool input) Diagnostic(ErrorCode.ERR_LocalFunctionMissingBody, "local").WithArguments("local(bool, bool)").WithLocation(7, 14) }; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void LocalFunctionFlow_04() { string source = @" #pragma warning disable CS8321 struct C { void M() /*<bind>*/{ void local(bool result, bool input1, bool input2) { result = input1; } => result = input2; }/*</bind>*/ } "; string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { Methods: [void local(System.Boolean result, System.Boolean input1, System.Boolean input2)] Block[B1] - Block Predecessors: [B0] Statements (0) Next (Regular) Block[B2] Leaving: {R1} { void local(System.Boolean result, System.Boolean input1, System.Boolean input2) Block[B0#0R1] - Entry Statements (0) Next (Regular) Block[B1#0R1] Block[B1#0R1] - Block Predecessors: [B0#0R1] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid) (Syntax: 'result = input1;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean, IsInvalid) (Syntax: 'result = input1') Left: IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Boolean, IsInvalid) (Syntax: 'result') Right: IParameterReferenceOperation: input1 (OperationKind.ParameterReference, Type: System.Boolean, IsInvalid) (Syntax: 'input1') Next (Regular) Block[B3#0R1] .erroneous body {R1#0R1} { Block[B2#0R1] - Block [UnReachable] Predecessors (0) Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid, IsImplicit) (Syntax: 'result = input2') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean, IsInvalid) (Syntax: 'result = input2') Left: IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Boolean, IsInvalid) (Syntax: 'result') Right: IParameterReferenceOperation: input2 (OperationKind.ParameterReference, Type: System.Boolean, IsInvalid) (Syntax: 'input2') Next (Regular) Block[B3#0R1] Leaving: {R1#0R1} } Block[B3#0R1] - Exit Predecessors: [B1#0R1] [B2#0R1] Statements (0) } } Block[B2] - Exit Predecessors: [B1] Statements (0) "; var expectedDiagnostics = new[] { // file.cs(7,9): error CS8057: Block bodies and expression bodies cannot both be provided. // void local(bool result, bool input1, bool input2) Diagnostic(ErrorCode.ERR_BlockBodyAndExpressionBody, @"void local(bool result, bool input1, bool input2) { result = input1; } => result = input2;").WithLocation(7, 9) }; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void LocalFunctionFlow_05() { string source = @" #pragma warning disable CS8321 struct C { void M() /*<bind>*/{ void local1(bool result1, bool input1) { result1 = input1; } void local2(bool result2, bool input2) => result2 = input2; }/*</bind>*/ } "; string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { Methods: [void local1(System.Boolean result1, System.Boolean input1)] [void local2(System.Boolean result2, System.Boolean input2)] Block[B1] - Block Predecessors: [B0] Statements (0) Next (Regular) Block[B2] Leaving: {R1} { void local1(System.Boolean result1, System.Boolean input1) Block[B0#0R1] - Entry Statements (0) Next (Regular) Block[B1#0R1] Block[B1#0R1] - Block Predecessors: [B0#0R1] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result1 = input1;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'result1 = input1') Left: IParameterReferenceOperation: result1 (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'result1') Right: IParameterReferenceOperation: input1 (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'input1') Next (Regular) Block[B2#0R1] Block[B2#0R1] - Exit Predecessors: [B1#0R1] Statements (0) } { void local2(System.Boolean result2, System.Boolean input2) Block[B0#1R1] - Entry Statements (0) Next (Regular) Block[B1#1R1] Block[B1#1R1] - Block Predecessors: [B0#1R1] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsImplicit) (Syntax: 'result2 = input2') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'result2 = input2') Left: IParameterReferenceOperation: result2 (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'result2') Right: IParameterReferenceOperation: input2 (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'input2') Next (Regular) Block[B2#1R1] Block[B2#1R1] - Exit Predecessors: [B1#1R1] Statements (0) } } Block[B2] - Exit Predecessors: [B1] Statements (0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void LocalFunctionFlow_06() { string source = @" struct C { void M(int input) /*<bind>*/{ int result; local1(input); int local1(int input1) { int i = local1(input1); result = local1(i); return result; } local1(result); }/*</bind>*/ } "; string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { Locals: [System.Int32 result] Methods: [System.Int32 local1(System.Int32 input1)] Block[B1] - Block Predecessors: [B0] Statements (2) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'local1(input);') Expression: IInvocationOperation (System.Int32 local1(System.Int32 input1)) (OperationKind.Invocation, Type: System.Int32) (Syntax: 'local1(input)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: input1) (OperationKind.Argument, Type: null) (Syntax: 'input') IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'input') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'local1(result);') Expression: IInvocationOperation (System.Int32 local1(System.Int32 input1)) (OperationKind.Invocation, Type: System.Int32) (Syntax: 'local1(result)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: input1) (OperationKind.Argument, Type: null) (Syntax: 'result') ILocalReferenceOperation: result (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'result') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Next (Regular) Block[B2] Leaving: {R1} { System.Int32 local1(System.Int32 input1) Block[B0#0R1] - Entry Statements (0) Next (Regular) Block[B1#0R1] Entering: {R1#0R1} .locals {R1#0R1} { Locals: [System.Int32 i] Block[B1#0R1] - Block Predecessors: [B0#0R1] Statements (2) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'i = local1(input1)') Left: ILocalReferenceOperation: i (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsImplicit) (Syntax: 'i = local1(input1)') Right: IInvocationOperation (System.Int32 local1(System.Int32 input1)) (OperationKind.Invocation, Type: System.Int32) (Syntax: 'local1(input1)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: input1) (OperationKind.Argument, Type: null) (Syntax: 'input1') IParameterReferenceOperation: input1 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'input1') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = local1(i);') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'result = local1(i)') Left: ILocalReferenceOperation: result (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'result') Right: IInvocationOperation (System.Int32 local1(System.Int32 input1)) (OperationKind.Invocation, Type: System.Int32) (Syntax: 'local1(i)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: input1) (OperationKind.Argument, Type: null) (Syntax: 'i') ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Next (Return) Block[B2#0R1] ILocalReferenceOperation: result (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'result') Leaving: {R1#0R1} } Block[B2#0R1] - Exit Predecessors: [B1#0R1] Statements (0) } } Block[B2] - Exit Predecessors: [B1] Statements (0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void LocalFunctionFlow_07() { string source = @" #pragma warning disable CS8321 struct C { void M() /*<bind>*/{ try { void local(bool result, bool input) { result = input; } } finally {} }/*</bind>*/ } "; string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { Methods: [void local(System.Boolean result, System.Boolean input)] Block[B1] - Block Predecessors: [B0] Statements (0) Next (Regular) Block[B2] Leaving: {R1} { void local(System.Boolean result, System.Boolean input) Block[B0#0R1] - Entry Statements (0) Next (Regular) Block[B1#0R1] Block[B1#0R1] - Block Predecessors: [B0#0R1] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = input;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'result = input') Left: IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'result') Right: IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'input') Next (Regular) Block[B2#0R1] Block[B2#0R1] - Exit Predecessors: [B1#0R1] Statements (0) } } Block[B2] - Exit Predecessors: [B1] Statements (0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void LocalFunctionFlow_08() { string source = @" #pragma warning disable CS8321 struct C { void M() /*<bind>*/{ int i = 0; void local1(int input1) { input1 = 1; i++; void local2(bool input2) { input2 = true; i++; } } }/*</bind>*/ } "; string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { Locals: [System.Int32 i] Methods: [void local1(System.Int32 input1)] Block[B1] - Block Predecessors: [B0] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'i = 0') Left: ILocalReferenceOperation: i (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsImplicit) (Syntax: 'i = 0') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0') Next (Regular) Block[B2] Leaving: {R1} { void local1(System.Int32 input1) Block[B0#0R1] - Entry Statements (0) Next (Regular) Block[B1#0R1] Entering: {R1#0R1} .locals {R1#0R1} { Methods: [void local2(System.Boolean input2)] Block[B1#0R1] - Block Predecessors: [B0#0R1] Statements (2) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'input1 = 1;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'input1 = 1') Left: IParameterReferenceOperation: input1 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'input1') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'i++;') Expression: IIncrementOrDecrementOperation (Postfix) (OperationKind.Increment, Type: System.Int32) (Syntax: 'i++') Target: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i') Next (Regular) Block[B2#0R1] Leaving: {R1#0R1} { void local2(System.Boolean input2) Block[B0#0R1#0R1] - Entry Statements (0) Next (Regular) Block[B1#0R1#0R1] Block[B1#0R1#0R1] - Block Predecessors: [B0#0R1#0R1] Statements (2) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'input2 = true;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'input2 = true') Left: IParameterReferenceOperation: input2 (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'input2') Right: ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'i++;') Expression: IIncrementOrDecrementOperation (Postfix) (OperationKind.Increment, Type: System.Int32) (Syntax: 'i++') Target: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i') Next (Regular) Block[B2#0R1#0R1] Block[B2#0R1#0R1] - Exit Predecessors: [B1#0R1#0R1] Statements (0) } } Block[B2#0R1] - Exit Predecessors: [B1#0R1] Statements (0) } } Block[B2] - Exit Predecessors: [B1] Statements (0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void LocalFunctionFlow_09() { string source = @" #pragma warning disable CS8321 class C { void M(C x, C y, C z) /*<bind>*/{ x = y ?? z; void local(C result, C input1, C input2) { result = input1 ?? input2; } }/*</bind>*/ } "; string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { Methods: [void local(C result, C input1, C input2)] CaptureIds: [0] [2] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'x') Value: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: C) (Syntax: 'x') 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: 'y') Value: IParameterReferenceOperation: y (OperationKind.ParameterReference, Type: C) (Syntax: 'y') Jump if True (Regular) to Block[B4] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'y') Operand: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'y') Leaving: {R2} Next (Regular) Block[B3] Block[B3] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'y') Value: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'y') Next (Regular) Block[B5] Leaving: {R2} } Block[B4] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'z') Value: IParameterReferenceOperation: z (OperationKind.ParameterReference, Type: C) (Syntax: 'z') Next (Regular) Block[B5] Block[B5] - Block Predecessors: [B3] [B4] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'x = y ?? z;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: C) (Syntax: 'x = y ?? z') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'x') Right: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'y ?? z') Next (Regular) Block[B6] Leaving: {R1} { void local(C result, C input1, C input2) Block[B0#0R1] - Entry Statements (0) Next (Regular) Block[B1#0R1] Entering: {R1#0R1} .locals {R1#0R1} { CaptureIds: [3] [5] Block[B1#0R1] - Block Predecessors: [B0#0R1] Statements (1) IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'result') Value: IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: C) (Syntax: 'result') Next (Regular) Block[B2#0R1] Entering: {R2#0R1} .locals {R2#0R1} { CaptureIds: [4] Block[B2#0R1] - Block Predecessors: [B1#0R1] Statements (1) IFlowCaptureOperation: 4 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input1') Value: IParameterReferenceOperation: input1 (OperationKind.ParameterReference, Type: C) (Syntax: 'input1') Jump if True (Regular) to Block[B4#0R1] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'input1') Operand: IFlowCaptureReferenceOperation: 4 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'input1') Leaving: {R2#0R1} Next (Regular) Block[B3#0R1] Block[B3#0R1] - Block Predecessors: [B2#0R1] Statements (1) IFlowCaptureOperation: 5 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input1') Value: IFlowCaptureReferenceOperation: 4 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'input1') Next (Regular) Block[B5#0R1] Leaving: {R2#0R1} } Block[B4#0R1] - Block Predecessors: [B2#0R1] Statements (1) IFlowCaptureOperation: 5 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input2') Value: IParameterReferenceOperation: input2 (OperationKind.ParameterReference, Type: C) (Syntax: 'input2') Next (Regular) Block[B5#0R1] Block[B5#0R1] - Block Predecessors: [B3#0R1] [B4#0R1] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = in ... ?? input2;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: C) (Syntax: 'result = in ... 1 ?? input2') Left: IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'result') Right: IFlowCaptureReferenceOperation: 5 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'input1 ?? input2') Next (Regular) Block[B6#0R1] Leaving: {R1#0R1} } Block[B6#0R1] - Exit Predecessors: [B5#0R1] Statements (0) } } Block[B6] - Exit Predecessors: [B5] Statements (0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void LocalFunctionFlow_10() { string source = @" #pragma warning disable CS8321 class C { void M() /*<bind>*/{ void local1(C result1, C input11, C input12) { result1 = input11 ?? input12; } void local2(C result2, C input21, C input22) { result2 = input21 ?? input22; } }/*</bind>*/ } "; string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { Methods: [void local1(C result1, C input11, C input12)] [void local2(C result2, C input21, C input22)] Block[B1] - Block Predecessors: [B0] Statements (0) Next (Regular) Block[B2] Leaving: {R1} { void local1(C result1, C input11, C input12) Block[B0#0R1] - Entry Statements (0) Next (Regular) Block[B1#0R1] Entering: {R1#0R1} .locals {R1#0R1} { CaptureIds: [0] [2] Block[B1#0R1] - Block Predecessors: [B0#0R1] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'result1') Value: IParameterReferenceOperation: result1 (OperationKind.ParameterReference, Type: C) (Syntax: 'result1') Next (Regular) Block[B2#0R1] Entering: {R2#0R1} .locals {R2#0R1} { CaptureIds: [1] Block[B2#0R1] - Block Predecessors: [B1#0R1] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input11') Value: IParameterReferenceOperation: input11 (OperationKind.ParameterReference, Type: C) (Syntax: 'input11') Jump if True (Regular) to Block[B4#0R1] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'input11') Operand: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'input11') Leaving: {R2#0R1} Next (Regular) Block[B3#0R1] Block[B3#0R1] - Block Predecessors: [B2#0R1] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input11') Value: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'input11') Next (Regular) Block[B5#0R1] Leaving: {R2#0R1} } Block[B4#0R1] - Block Predecessors: [B2#0R1] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input12') Value: IParameterReferenceOperation: input12 (OperationKind.ParameterReference, Type: C) (Syntax: 'input12') Next (Regular) Block[B5#0R1] Block[B5#0R1] - Block Predecessors: [B3#0R1] [B4#0R1] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result1 = i ... ?? input12;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: C) (Syntax: 'result1 = i ... ?? input12') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'result1') Right: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'input11 ?? input12') Next (Regular) Block[B6#0R1] Leaving: {R1#0R1} } Block[B6#0R1] - Exit Predecessors: [B5#0R1] Statements (0) } { void local2(C result2, C input21, C input22) Block[B0#1R1] - Entry Statements (0) Next (Regular) Block[B1#1R1] Entering: {R1#1R1} .locals {R1#1R1} { CaptureIds: [3] [5] Block[B1#1R1] - Block Predecessors: [B0#1R1] Statements (1) IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'result2') Value: IParameterReferenceOperation: result2 (OperationKind.ParameterReference, Type: C) (Syntax: 'result2') Next (Regular) Block[B2#1R1] Entering: {R2#1R1} .locals {R2#1R1} { CaptureIds: [4] Block[B2#1R1] - Block Predecessors: [B1#1R1] Statements (1) IFlowCaptureOperation: 4 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input21') Value: IParameterReferenceOperation: input21 (OperationKind.ParameterReference, Type: C) (Syntax: 'input21') Jump if True (Regular) to Block[B4#1R1] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'input21') Operand: IFlowCaptureReferenceOperation: 4 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'input21') Leaving: {R2#1R1} Next (Regular) Block[B3#1R1] Block[B3#1R1] - Block Predecessors: [B2#1R1] Statements (1) IFlowCaptureOperation: 5 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input21') Value: IFlowCaptureReferenceOperation: 4 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'input21') Next (Regular) Block[B5#1R1] Leaving: {R2#1R1} } Block[B4#1R1] - Block Predecessors: [B2#1R1] Statements (1) IFlowCaptureOperation: 5 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input22') Value: IParameterReferenceOperation: input22 (OperationKind.ParameterReference, Type: C) (Syntax: 'input22') Next (Regular) Block[B5#1R1] Block[B5#1R1] - Block Predecessors: [B3#1R1] [B4#1R1] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result2 = i ... ?? input22;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: C) (Syntax: 'result2 = i ... ?? input22') Left: IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'result2') Right: IFlowCaptureReferenceOperation: 5 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'input21 ?? input22') Next (Regular) Block[B6#1R1] Leaving: {R1#1R1} } Block[B6#1R1] - Exit Predecessors: [B5#1R1] Statements (0) } } Block[B2] - Exit Predecessors: [B1] Statements (0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void LocalFunctionFlow_11() { string source = @" struct C { void M() /*<bind>*/{ void d1() { void d2(bool result1, bool input1) { result1 = input1; } }; }/*</bind>*/ } "; var compilation = CreateCompilation(source); var tree = compilation.SyntaxTrees.Single(); var semanticModel = compilation.GetSemanticModel(tree); var graphM = ControlFlowGraph.Create((IMethodBodyOperation)semanticModel.GetOperation(tree.GetRoot().DescendantNodes().OfType<MethodDeclarationSyntax>().First())); Assert.NotNull(graphM); Assert.Null(graphM.Parent); IMethodSymbol localFunctionD1 = getLocalFunction(graphM); Assert.NotNull(localFunctionD1); Assert.Equal("d1", localFunctionD1.Name); var graphD1 = graphM.GetLocalFunctionControlFlowGraph(localFunctionD1); Assert.NotNull(graphD1); Assert.Same(graphM, graphD1.Parent); var graphD1_FromExtension = graphM.GetLocalFunctionControlFlowGraphInScope(localFunctionD1); Assert.Same(graphD1, graphD1_FromExtension); IMethodSymbol localFunctionD2 = getLocalFunction(graphD1); Assert.NotNull(localFunctionD2); Assert.Equal("d2", localFunctionD2.Name); var graphD2 = graphD1.GetLocalFunctionControlFlowGraph(localFunctionD2); Assert.NotNull(graphD2); Assert.Same(graphD1, graphD2.Parent); Assert.Throws<ArgumentNullException>(() => graphM.GetLocalFunctionControlFlowGraph(null)); Assert.Throws<ArgumentOutOfRangeException>(() => graphM.GetLocalFunctionControlFlowGraph(localFunctionD2)); Assert.Throws<ArgumentNullException>(() => graphM.GetLocalFunctionControlFlowGraphInScope(null)); Assert.Throws<ArgumentOutOfRangeException>(() => graphM.GetLocalFunctionControlFlowGraphInScope(localFunctionD2)); IMethodSymbol getLocalFunction(ControlFlowGraph graph) { return graph.LocalFunctions.Single(); } } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void LocalFunctionFlow_12() { string source = @" struct C { void M() /*<bind>*/{ void d1() { } void d2() { d1(); } }/*</bind>*/ } "; var compilation = CreateCompilation(source); var tree = compilation.SyntaxTrees.Single(); var semanticModel = compilation.GetSemanticModel(tree); var graphM = ControlFlowGraph.Create((IMethodBodyOperation)semanticModel.GetOperation(tree.GetRoot().DescendantNodes().OfType<MethodDeclarationSyntax>().First())); Assert.NotNull(graphM); Assert.Null(graphM.Parent); IMethodSymbol localFunctionD1 = getLocalFunction(graphM, "d1"); Assert.NotNull(localFunctionD1); IMethodSymbol localFunctionD2 = getLocalFunction(graphM, "d2"); Assert.NotNull(localFunctionD2); var graphD1 = graphM.GetLocalFunctionControlFlowGraph(localFunctionD1); Assert.NotNull(graphD1); Assert.Same(graphM, graphD1.Parent); var graphD2 = graphM.GetLocalFunctionControlFlowGraph(localFunctionD2); Assert.NotNull(graphD2); Assert.Same(graphM, graphD2.Parent); var graphD1_FromExtension = graphM.GetLocalFunctionControlFlowGraphInScope(localFunctionD1); Assert.Same(graphD1, graphD1_FromExtension); Assert.Throws<ArgumentOutOfRangeException>(() => graphD2.GetLocalFunctionControlFlowGraph(localFunctionD1)); graphD1_FromExtension = graphD2.GetLocalFunctionControlFlowGraphInScope(localFunctionD1); Assert.Same(graphD1, graphD1_FromExtension); IMethodSymbol getLocalFunction(ControlFlowGraph graph, string name) { return graph.LocalFunctions.Single(l => l.Name == name); } } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void LocalFunctionFlow_StaticWithShadowedVariableReference() { string source = @"#pragma warning disable 0219 #pragma warning disable 8321 class C { static void M() /*<bind>*/ { object x = null; object y = null; static object Local(string y, object z) => x ?? y ?? z; } /*</bind>*/ }"; string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { Locals: [System.Object x] [System.Object y] Methods: [System.Object Local(System.String y, System.Object z)] Block[B1] - Block Predecessors: [B0] Statements (2) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Object, IsImplicit) (Syntax: 'x = null') Left: ILocalReferenceOperation: x (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Object, IsImplicit) (Syntax: 'x = null') Right: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, Constant: null, IsImplicit) (Syntax: 'null') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) (ImplicitReference) Operand: ILiteralOperation (OperationKind.Literal, Type: null, Constant: null) (Syntax: 'null') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Object, IsImplicit) (Syntax: 'y = null') Left: ILocalReferenceOperation: y (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Object, IsImplicit) (Syntax: 'y = null') Right: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, Constant: null, IsImplicit) (Syntax: 'null') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) (ImplicitReference) Operand: ILiteralOperation (OperationKind.Literal, Type: null, Constant: null) (Syntax: 'null') Next (Regular) Block[B2] Leaving: {R1} { System.Object Local(System.String y, System.Object z) Block[B0#0R1] - Entry Statements (0) Next (Regular) Block[B1#0R1] Entering: {R1#0R1} {R2#0R1} .locals {R1#0R1} { CaptureIds: [1] .locals {R2#0R1} { CaptureIds: [0] Block[B1#0R1] - Block Predecessors: [B0#0R1] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'x') Value: ILocalReferenceOperation: x (OperationKind.LocalReference, Type: System.Object, IsInvalid) (Syntax: 'x') Jump if True (Regular) to Block[B3#0R1] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsInvalid, IsImplicit) (Syntax: 'x') Operand: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Object, IsInvalid, IsImplicit) (Syntax: 'x') Leaving: {R2#0R1} Entering: {R3#0R1} Next (Regular) Block[B2#0R1] Block[B2#0R1] - Block Predecessors: [B1#0R1] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'x') Value: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Object, IsInvalid, IsImplicit) (Syntax: 'x') Next (Regular) Block[B6#0R1] Leaving: {R2#0R1} } .locals {R3#0R1} { CaptureIds: [2] Block[B3#0R1] - Block Predecessors: [B1#0R1] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'y') Value: IParameterReferenceOperation: y (OperationKind.ParameterReference, Type: System.String) (Syntax: 'y') Jump if True (Regular) to Block[B5#0R1] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'y') Operand: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.String, IsImplicit) (Syntax: 'y') Leaving: {R3#0R1} Next (Regular) Block[B4#0R1] Block[B4#0R1] - Block Predecessors: [B3#0R1] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'y') Value: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsImplicit) (Syntax: 'y') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) (ImplicitReference) Operand: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.String, IsImplicit) (Syntax: 'y') Next (Regular) Block[B6#0R1] Leaving: {R3#0R1} } Block[B5#0R1] - Block Predecessors: [B3#0R1] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'z') Value: IParameterReferenceOperation: z (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'z') Next (Regular) Block[B6#0R1] Block[B6#0R1] - Block Predecessors: [B2#0R1] [B4#0R1] [B5#0R1] Statements (0) Next (Return) Block[B7#0R1] IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Object, IsInvalid, IsImplicit) (Syntax: 'x ?? y ?? z') Leaving: {R1#0R1} } Block[B7#0R1] - Exit Predecessors: [B6#0R1] Statements (0) } } Block[B2] - Exit Predecessors: [B1] Statements (0) "; var expectedDiagnostics = new[] { // (10,52): error CS8421: A static local function cannot contain a reference to 'x'. // static object Local(string y, object z) => x ?? y ?? z; Diagnostic(ErrorCode.ERR_StaticLocalFunctionCannotCaptureVariable, "x").WithArguments("x").WithLocation(10, 52) }; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, 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; using System.Linq; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.FlowAnalysis; using Microsoft.CodeAnalysis.Operations; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public class IOperationTests_ILocalFunctionStatement : SemanticModelTestBase { [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void TestLocalFunction_ContainingMethodParameterReference() { string source = @" class C { public void M(int x) { /*<bind>*/int Local(int p1) { return x++; }/*</bind>*/ Local(0); } } "; string expectedOperationTree = @" ILocalFunctionOperation (Symbol: System.Int32 Local(System.Int32 p1)) (OperationKind.LocalFunction, Type: null) (Syntax: 'int Local(i ... }') IBlockOperation (1 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }') IReturnOperation (OperationKind.Return, Type: null) (Syntax: 'return x++;') ReturnedValue: IIncrementOrDecrementOperation (Postfix) (OperationKind.Increment, Type: System.Int32) (Syntax: 'x++') Target: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'x') "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<LocalFunctionStatementSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void TestLocalFunction_ContainingMethodParameterReference_ExpressionBodied() { string source = @" class C { public void M(int x) { /*<bind>*/int Local(int p1) => x++;/*</bind>*/ Local(0); } } "; string expectedOperationTree = @" ILocalFunctionOperation (Symbol: System.Int32 Local(System.Int32 p1)) (OperationKind.LocalFunction, Type: null) (Syntax: 'int Local(i ... p1) => x++;') IBlockOperation (1 statements) (OperationKind.Block, Type: null) (Syntax: '=> x++') IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'x++') ReturnedValue: IIncrementOrDecrementOperation (Postfix) (OperationKind.Increment, Type: System.Int32) (Syntax: 'x++') Target: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'x') "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<LocalFunctionStatementSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void TestLocalFunction_LocalFunctionParameterReference() { string source = @" class C { public void M() { /*<bind>*/int Local(int x) => x++;/*</bind>*/ Local(0); } } "; string expectedOperationTree = @" ILocalFunctionOperation (Symbol: System.Int32 Local(System.Int32 x)) (OperationKind.LocalFunction, Type: null) (Syntax: 'int Local(int x) => x++;') IBlockOperation (1 statements) (OperationKind.Block, Type: null) (Syntax: '=> x++') IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'x++') ReturnedValue: IIncrementOrDecrementOperation (Postfix) (OperationKind.Increment, Type: System.Int32) (Syntax: 'x++') Target: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'x') "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<LocalFunctionStatementSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void TestLocalFunction_ContainingLocalFunctionParameterReference() { string source = @" class C { public void M() { int LocalOuter (int x) { /*<bind>*/int Local(int y) => x + y;/*</bind>*/ return Local(x); } LocalOuter(0); } } "; string expectedOperationTree = @" ILocalFunctionOperation (Symbol: System.Int32 Local(System.Int32 y)) (OperationKind.LocalFunction, Type: null) (Syntax: 'int Local(i ... ) => x + y;') IBlockOperation (1 statements) (OperationKind.Block, Type: null) (Syntax: '=> x + y') IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'x + y') ReturnedValue: IBinaryOperation (BinaryOperatorKind.Add) (OperationKind.Binary, Type: System.Int32) (Syntax: 'x + y') Left: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'x') Right: IParameterReferenceOperation: y (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'y') "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<LocalFunctionStatementSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void TestLocalFunction_LocalFunctionReference() { string source = @" class C { public void M() { int x; int Local(int p1) => x++; int Local2(int p1) => Local(p1); /*<bind>*/int Local3(int p1) => x + Local2(p1);/*</bind>*/ Local3(x = 0); } } "; string expectedOperationTree = @" ILocalFunctionOperation (Symbol: System.Int32 Local3(System.Int32 p1)) (OperationKind.LocalFunction, Type: null) (Syntax: 'int Local3( ... Local2(p1);') IBlockOperation (1 statements) (OperationKind.Block, Type: null) (Syntax: '=> x + Local2(p1)') IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'x + Local2(p1)') ReturnedValue: IBinaryOperation (BinaryOperatorKind.Add) (OperationKind.Binary, Type: System.Int32) (Syntax: 'x + Local2(p1)') Left: ILocalReferenceOperation: x (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'x') Right: IInvocationOperation (System.Int32 Local2(System.Int32 p1)) (OperationKind.Invocation, Type: System.Int32) (Syntax: 'Local2(p1)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: p1) (OperationKind.Argument, Type: null) (Syntax: 'p1') IParameterReferenceOperation: p1 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'p1') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<LocalFunctionStatementSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void TestLocalFunction_Recursion() { string source = @" class C { public void M(int x) { /*<bind>*/int Local(int p1) => Local(x + p1);/*</bind>*/ } } "; string expectedOperationTree = @" ILocalFunctionOperation (Symbol: System.Int32 Local(System.Int32 p1)) (OperationKind.LocalFunction, Type: null) (Syntax: 'int Local(i ... al(x + p1);') IBlockOperation (1 statements) (OperationKind.Block, Type: null) (Syntax: '=> Local(x + p1)') IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'Local(x + p1)') ReturnedValue: IInvocationOperation (System.Int32 Local(System.Int32 p1)) (OperationKind.Invocation, Type: System.Int32) (Syntax: 'Local(x + p1)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: p1) (OperationKind.Argument, Type: null) (Syntax: 'x + p1') IBinaryOperation (BinaryOperatorKind.Add) (OperationKind.Binary, Type: System.Int32) (Syntax: 'x + p1') Left: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'x') Right: IParameterReferenceOperation: p1 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'p1') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<LocalFunctionStatementSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void TestLocalFunction_Async() { string source = @" using System.Threading.Tasks; class C { public void M(int x) { /*<bind>*/async Task<int> LocalAsync(int p1) { await Task.Delay(0); return x + p1; }/*</bind>*/ LocalAsync(0).Wait(); } } "; string expectedOperationTree = @" ILocalFunctionOperation (Symbol: System.Threading.Tasks.Task<System.Int32> LocalAsync(System.Int32 p1)) (OperationKind.LocalFunction, Type: null) (Syntax: 'async Task< ... }') IBlockOperation (2 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'await Task.Delay(0);') Expression: IAwaitOperation (OperationKind.Await, Type: System.Void) (Syntax: 'await Task.Delay(0)') Expression: IInvocationOperation (System.Threading.Tasks.Task System.Threading.Tasks.Task.Delay(System.Int32 millisecondsDelay)) (OperationKind.Invocation, Type: System.Threading.Tasks.Task) (Syntax: 'Task.Delay(0)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: millisecondsDelay) (OperationKind.Argument, Type: null) (Syntax: '0') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IReturnOperation (OperationKind.Return, Type: null) (Syntax: 'return x + p1;') ReturnedValue: IBinaryOperation (BinaryOperatorKind.Add) (OperationKind.Binary, Type: System.Int32) (Syntax: 'x + p1') Left: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'x') Right: IParameterReferenceOperation: p1 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'p1') "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<LocalFunctionStatementSyntax>(source, expectedOperationTree, expectedDiagnostics, useLatestFrameworkReferences: true); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void TestLocalFunction_CaptureForEachVar() { string source = @" class C { public void M(int[] array) { foreach (var x in array) { /*<bind>*/int Local() => x;/*</bind>*/ Local(); } } } "; string expectedOperationTree = @" ILocalFunctionOperation (Symbol: System.Int32 Local()) (OperationKind.LocalFunction, Type: null) (Syntax: 'int Local() => x;') IBlockOperation (1 statements) (OperationKind.Block, Type: null) (Syntax: '=> x') IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'x') ReturnedValue: ILocalReferenceOperation: x (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'x') "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<LocalFunctionStatementSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void TestLocalFunction_UseOfUnusedVar() { string source = @" class C { void M() { F(); int x = 0; /*<bind>*/void F() => x++;/*</bind>*/ } } "; string expectedOperationTree = @" ILocalFunctionOperation (Symbol: void F()) (OperationKind.LocalFunction, Type: null) (Syntax: 'void F() => x++;') IBlockOperation (2 statements) (OperationKind.Block, Type: null) (Syntax: '=> x++') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsImplicit) (Syntax: 'x++') Expression: IIncrementOrDecrementOperation (Postfix) (OperationKind.Increment, Type: System.Int32) (Syntax: 'x++') Target: ILocalReferenceOperation: x (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'x') IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: '=> x++') ReturnedValue: null "; var expectedDiagnostics = new DiagnosticDescription[] { // CS0165: Use of unassigned local variable 'x' // F(); Diagnostic(ErrorCode.ERR_UseDefViolation, "F()").WithArguments("x").WithLocation(6, 9) }; VerifyOperationTreeAndDiagnosticsForTest<LocalFunctionStatementSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void TestLocalFunction_OutVar() { string source = @" class C { void M(int p) { int x; /*<bind>*/void F(out int y) => y = p;/*</bind>*/ F(out x); } } "; string expectedOperationTree = @" ILocalFunctionOperation (Symbol: void F(out System.Int32 y)) (OperationKind.LocalFunction, Type: null) (Syntax: 'void F(out ... ) => y = p;') IBlockOperation (2 statements) (OperationKind.Block, Type: null) (Syntax: '=> y = p') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsImplicit) (Syntax: 'y = p') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'y = p') Left: IParameterReferenceOperation: y (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'y') Right: IParameterReferenceOperation: p (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'p') IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: '=> y = p') ReturnedValue: null "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<LocalFunctionStatementSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void TestInvalidLocalFunction_MissingBody() { string source = @" class C { void M(int p) { /*<bind>*/void F(out int y) => ;/*</bind>*/ } } "; string expectedOperationTree = @" ILocalFunctionOperation (Symbol: void F(out System.Int32 y)) (OperationKind.LocalFunction, Type: null, IsInvalid) (Syntax: 'void F(out int y) => ;') IBlockOperation (2 statements) (OperationKind.Block, Type: null, IsInvalid) (Syntax: '=> ') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid, IsImplicit) (Syntax: '') Expression: IInvalidOperation (OperationKind.Invalid, Type: null, IsInvalid) (Syntax: '') Children(0) IReturnOperation (OperationKind.Return, Type: null, IsInvalid, IsImplicit) (Syntax: '=> ') ReturnedValue: null "; var expectedDiagnostics = new DiagnosticDescription[] { // file.cs(6,40): error CS1525: Invalid expression term ';' // /*<bind>*/void F(out int y) => ;/*</bind>*/ Diagnostic(ErrorCode.ERR_InvalidExprTerm, ";").WithArguments(";").WithLocation(6, 40), // file.cs(6,24): error CS0177: The out parameter 'y' must be assigned to before control leaves the current method // /*<bind>*/void F(out int y) => ;/*</bind>*/ Diagnostic(ErrorCode.ERR_ParamUnassigned, "F").WithArguments("y").WithLocation(6, 24), // file.cs(6,24): warning CS8321: The local function 'F' is declared but never used // /*<bind>*/void F(out int y) => ;/*</bind>*/ Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "F").WithArguments("F").WithLocation(6, 24) }; VerifyOperationTreeAndDiagnosticsForTest<LocalFunctionStatementSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void TestInvalidLocalFunction_MissingParameters() { string source = @" class C { void M(int p) { /*<bind>*/void F( { }/*</bind>*/; } } "; string expectedOperationTree = @" ILocalFunctionOperation (Symbol: void F()) (OperationKind.LocalFunction, Type: null, IsInvalid) (Syntax: 'void F( { }') IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsInvalid) (Syntax: '{ }') IReturnOperation (OperationKind.Return, Type: null, IsInvalid, IsImplicit) (Syntax: '{ }') ReturnedValue: null "; var expectedDiagnostics = new DiagnosticDescription[] { // file.cs(6,27): error CS1026: ) expected // /*<bind>*/void F( { }/*</bind>*/; Diagnostic(ErrorCode.ERR_CloseParenExpected, "{").WithLocation(6, 27), // file.cs(6,24): warning CS8321: The local function 'F' is declared but never used // /*<bind>*/void F( { }/*</bind>*/; Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "F").WithArguments("F").WithLocation(6, 24) }; VerifyOperationTreeAndDiagnosticsForTest<LocalFunctionStatementSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void TestInvalidLocalFunction_InvalidReturnType() { string source = @" class C { void M(int p) { /*<bind>*/X F() { }/*</bind>*/; } } "; string expectedOperationTree = @" ILocalFunctionOperation (Symbol: X F()) (OperationKind.LocalFunction, Type: null, IsInvalid) (Syntax: 'X F() { }') IBlockOperation (0 statements) (OperationKind.Block, Type: null) (Syntax: '{ }') "; var expectedDiagnostics = new DiagnosticDescription[] { // CS0161: 'F()': not all code paths return a value // /*<bind>*/X F() { }/*</bind>*/; Diagnostic(ErrorCode.ERR_ReturnExpected, "F").WithArguments("F()").WithLocation(6, 21), // CS0246: The type or namespace name 'X' could not be found (are you missing a using directive or an assembly reference?) // /*<bind>*/X F() { }/*</bind>*/; Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "X").WithArguments("X").WithLocation(6, 19), // CS8321: The local function 'F' is declared but never used // /*<bind>*/X F() { }/*</bind>*/; Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "F").WithArguments("F").WithLocation(6, 21) }; VerifyOperationTreeAndDiagnosticsForTest<LocalFunctionStatementSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(24650, "https://github.com/dotnet/roslyn/issues/24650")] public void TestInvalidLocalFunction_ExpressionAndBlockBody() { string source = @" class C { void M(int p) { /*<bind>*/object F() => new object(); { return null; }/*</bind>*/; } } "; string expectedOperationTree = @" ILocalFunctionOperation (Symbol: System.Object F()) (OperationKind.LocalFunction, Type: null) (Syntax: 'object F() ... w object();') IBlockOperation (1 statements) (OperationKind.Block, Type: null) (Syntax: '=> new object()') IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'new object()') ReturnedValue: IObjectCreationOperation (Constructor: System.Object..ctor()) (OperationKind.ObjectCreation, Type: System.Object) (Syntax: 'new object()') Arguments(0) Initializer: null "; var expectedDiagnostics = new DiagnosticDescription[] { // file.cs(6,49): error CS0127: Since 'C.M(int)' returns void, a return keyword must not be followed by an object expression // /*<bind>*/object F() => new object(); { return new object(); }/*</bind>*/; Diagnostic(ErrorCode.ERR_RetNoObjectRequired, "return").WithArguments("C.M(int)").WithLocation(6, 49), // file.cs(6,26): warning CS8321: The local function 'F' is declared but never used // /*<bind>*/object F() => new object(); { return new object(); }/*</bind>*/; Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "F").WithArguments("F").WithLocation(6, 26) }; VerifyOperationTreeAndDiagnosticsForTest<LocalFunctionStatementSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(24650, "https://github.com/dotnet/roslyn/issues/24650")] public void TestInvalidLocalFunction_BlockAndExpressionBody() { string source = @" class C { void M(int p) { /*<bind>*/object F() { return new object(); } => null;/*</bind>*/; } } "; string expectedOperationTree = @" ILocalFunctionOperation (Symbol: System.Object F()) (OperationKind.LocalFunction, Type: null, IsInvalid) (Syntax: 'object F() ... } => null;') Body: IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsInvalid) (Syntax: '{ return new object(); }') IReturnOperation (OperationKind.Return, Type: null, IsInvalid) (Syntax: 'return new object();') ReturnedValue: IObjectCreationOperation (Constructor: System.Object..ctor()) (OperationKind.ObjectCreation, Type: System.Object, IsInvalid) (Syntax: 'new object()') Arguments(0) Initializer: null IgnoredBody: IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsInvalid) (Syntax: '=> null') IReturnOperation (OperationKind.Return, Type: null, IsInvalid, IsImplicit) (Syntax: 'null') ReturnedValue: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, Constant: null, IsInvalid, IsImplicit) (Syntax: 'null') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: null, Constant: null, IsInvalid) (Syntax: 'null') "; var expectedDiagnostics = new DiagnosticDescription[] { // error CS8057: Block bodies and expression bodies cannot both be provided. // /*<bind>*/object F() { return new object(); } => null;/*</bind>*/; Diagnostic(ErrorCode.ERR_BlockBodyAndExpressionBody, "object F() { return new object(); } => null;").WithLocation(6, 19), // warning CS8321: The local function 'F' is declared but never used // /*<bind>*/object F() { return new object(); } => null;/*</bind>*/; Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "F").WithArguments("F").WithLocation(6, 26) }; VerifyOperationTreeAndDiagnosticsForTest<LocalFunctionStatementSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(24650, "https://github.com/dotnet/roslyn/issues/24650")] public void TestLocalFunction_ExpressionBodyInnerMember() { string source = @" class C { public void M(int x) { int Local(int p1) /*<bind>*/=> x++/*</bind>*/; Local(0); } } "; string expectedOperationTree = @" IBlockOperation (1 statements) (OperationKind.Block, Type: null) (Syntax: '=> x++') IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'x++') ReturnedValue: IIncrementOrDecrementOperation (Postfix) (OperationKind.Increment, Type: System.Int32) (Syntax: 'x++') Target: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'x') "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<ArrowExpressionClauseSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void TestLocalFunction_StaticWithShadowedVariableReference() { string source = @"#pragma warning disable 8321 class C { static void M(int x) { /*<bind>*/ static int Local(int y) { if (y > 0) { int x = (int)y; return x; } return x; } /*</bind>*/ } }"; string expectedOperationTree = @" ILocalFunctionOperation (Symbol: System.Int32 Local(System.Int32 y)) (OperationKind.LocalFunction, Type: null, IsInvalid) (Syntax: 'static int ... }') IBlockOperation (2 statements) (OperationKind.Block, Type: null, IsInvalid) (Syntax: '{ ... }') IConditionalOperation (OperationKind.Conditional, Type: null) (Syntax: 'if (y > 0) ... }') Condition: IBinaryOperation (BinaryOperatorKind.GreaterThan) (OperationKind.Binary, Type: System.Boolean) (Syntax: 'y > 0') Left: IParameterReferenceOperation: y (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'y') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0') WhenTrue: IBlockOperation (2 statements, 1 locals) (OperationKind.Block, Type: null) (Syntax: '{ ... }') Locals: Local_1: System.Int32 x IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null) (Syntax: 'int x = (int)y;') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'int x = (int)y') Declarators: IVariableDeclaratorOperation (Symbol: System.Int32 x) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'x = (int)y') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= (int)y') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32) (Syntax: '(int)y') Conversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: IParameterReferenceOperation: y (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'y') Initializer: null IReturnOperation (OperationKind.Return, Type: null) (Syntax: 'return x;') ReturnedValue: ILocalReferenceOperation: x (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'x') WhenFalse: null IReturnOperation (OperationKind.Return, Type: null, IsInvalid) (Syntax: 'return x;') ReturnedValue: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Int32, IsInvalid) (Syntax: 'x') "; var expectedDiagnostics = new[] { // (14,20): error CS8421: A static local function cannot contain a reference to 'x'. // return x; Diagnostic(ErrorCode.ERR_StaticLocalFunctionCannotCaptureVariable, "x").WithArguments("x").WithLocation(14, 20) }; VerifyOperationTreeAndDiagnosticsForTest<LocalFunctionStatementSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void TestLocalFunction_StaticWithThisReference() { string source = @"#pragma warning disable 8321 class C { void M() { /*<bind>*/ static object Local() => ToString() + this.GetHashCode() + base.GetHashCode(); /*</bind>*/ } }"; string expectedOperationTree = @" ILocalFunctionOperation (Symbol: System.Object Local()) (OperationKind.LocalFunction, Type: null, IsInvalid) (Syntax: 'static obje ... HashCode();') IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsInvalid) (Syntax: '=> ToString ... tHashCode()') IReturnOperation (OperationKind.Return, Type: null, IsInvalid, IsImplicit) (Syntax: 'ToString() ... tHashCode()') ReturnedValue: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsInvalid, IsImplicit) (Syntax: 'ToString() ... tHashCode()') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) Operand: IBinaryOperation (BinaryOperatorKind.Add) (OperationKind.Binary, Type: System.String, IsInvalid) (Syntax: 'ToString() ... tHashCode()') Left: IBinaryOperation (BinaryOperatorKind.Add) (OperationKind.Binary, Type: System.String, IsInvalid) (Syntax: 'ToString() ... tHashCode()') Left: IInvocationOperation (virtual System.String System.Object.ToString()) (OperationKind.Invocation, Type: System.String, IsInvalid) (Syntax: 'ToString()') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C, IsInvalid, IsImplicit) (Syntax: 'ToString') Arguments(0) Right: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsInvalid, IsImplicit) (Syntax: 'this.GetHashCode()') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: IInvocationOperation (virtual System.Int32 System.Object.GetHashCode()) (OperationKind.Invocation, Type: System.Int32, IsInvalid) (Syntax: 'this.GetHashCode()') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C, IsInvalid) (Syntax: 'this') Arguments(0) Right: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsInvalid, IsImplicit) (Syntax: 'base.GetHashCode()') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: IInvocationOperation ( System.Int32 System.Object.GetHashCode()) (OperationKind.Invocation, Type: System.Int32, IsInvalid) (Syntax: 'base.GetHashCode()') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: System.Object, IsInvalid) (Syntax: 'base') Arguments(0) "; var expectedDiagnostics = new[] { // (7,34): error CS8422: A static local function cannot contain a reference to 'this' or 'base'. // static object Local() => ToString() + this.GetHashCode() + base.GetHashCode(); Diagnostic(ErrorCode.ERR_StaticLocalFunctionCannotCaptureThis, "ToString").WithLocation(7, 34), // (7,47): error CS8422: A static local function cannot contain a reference to 'this' or 'base'. // static object Local() => ToString() + this.GetHashCode() + base.GetHashCode(); Diagnostic(ErrorCode.ERR_StaticLocalFunctionCannotCaptureThis, "this").WithLocation(7, 47), // (7,68): error CS8422: A static local function cannot contain a reference to 'this' or 'base'. // static object Local() => ToString() + this.GetHashCode() + base.GetHashCode(); Diagnostic(ErrorCode.ERR_StaticLocalFunctionCannotCaptureThis, "base").WithLocation(7, 68) }; VerifyOperationTreeAndDiagnosticsForTest<LocalFunctionStatementSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void LocalFunctionFlow_01() { string source = @" struct C { void M() /*<bind>*/{ void local(bool result, bool input) { result = input; } local(false, true); }/*</bind>*/ } "; string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { Methods: [void local(System.Boolean result, System.Boolean input)] Block[B1] - Block Predecessors: [B0] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'local(false, true);') Expression: IInvocationOperation (void local(System.Boolean result, System.Boolean input)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'local(false, true)') Instance Receiver: null Arguments(2): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: result) (OperationKind.Argument, Type: null) (Syntax: 'false') ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: False) (Syntax: 'false') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: input) (OperationKind.Argument, Type: null) (Syntax: 'true') ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Next (Regular) Block[B2] Leaving: {R1} { void local(System.Boolean result, System.Boolean input) Block[B0#0R1] - Entry Statements (0) Next (Regular) Block[B1#0R1] Block[B1#0R1] - Block Predecessors: [B0#0R1] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = input;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'result = input') Left: IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'result') Right: IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'input') Next (Regular) Block[B2#0R1] Block[B2#0R1] - Exit Predecessors: [B1#0R1] Statements (0) } } Block[B2] - Exit Predecessors: [B1] Statements (0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void LocalFunctionFlow_02() { string source = @" #pragma warning disable CS8321 struct C { void M() /*<bind>*/{ void local(bool result, bool input) { result = input; } }/*</bind>*/ } "; string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { Methods: [void local(System.Boolean result, System.Boolean input)] Block[B1] - Block Predecessors: [B0] Statements (0) Next (Regular) Block[B2] Leaving: {R1} { void local(System.Boolean result, System.Boolean input) Block[B0#0R1] - Entry Statements (0) Next (Regular) Block[B1#0R1] Block[B1#0R1] - Block Predecessors: [B0#0R1] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = input;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'result = input') Left: IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'result') Right: IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'input') Next (Regular) Block[B2#0R1] Block[B2#0R1] - Exit Predecessors: [B1#0R1] Statements (0) } } Block[B2] - Exit Predecessors: [B1] Statements (0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void LocalFunctionFlow_03() { string source = @" #pragma warning disable CS8321 struct C { void M() /*<bind>*/{ void local(bool result, bool input) }/*</bind>*/ } "; string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { Methods: [void local(System.Boolean result, System.Boolean input)] Block[B1] - Block Predecessors: [B0] Statements (0) Next (Regular) Block[B2] Leaving: {R1} { void local(System.Boolean result, System.Boolean input) Block[B0#0R1] - Entry Statements (0) Next (Regular) Block[B1#0R1] Block[B1#0R1] - Exit Predecessors: [B0#0R1] Statements (0) } } Block[B2] - Exit Predecessors: [B1] Statements (0) "; var expectedDiagnostics = new[] { // file.cs(7,44): error CS1002: ; expected // void local(bool result, bool input) Diagnostic(ErrorCode.ERR_SemicolonExpected, "").WithLocation(7, 44), // file.cs(7,14): error CS8112: 'local(bool, bool)' is a local function and must therefore always have a body. // void local(bool result, bool input) Diagnostic(ErrorCode.ERR_LocalFunctionMissingBody, "local").WithArguments("local(bool, bool)").WithLocation(7, 14) }; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void LocalFunctionFlow_04() { string source = @" #pragma warning disable CS8321 struct C { void M() /*<bind>*/{ void local(bool result, bool input1, bool input2) { result = input1; } => result = input2; }/*</bind>*/ } "; string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { Methods: [void local(System.Boolean result, System.Boolean input1, System.Boolean input2)] Block[B1] - Block Predecessors: [B0] Statements (0) Next (Regular) Block[B2] Leaving: {R1} { void local(System.Boolean result, System.Boolean input1, System.Boolean input2) Block[B0#0R1] - Entry Statements (0) Next (Regular) Block[B1#0R1] Block[B1#0R1] - Block Predecessors: [B0#0R1] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid) (Syntax: 'result = input1;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean, IsInvalid) (Syntax: 'result = input1') Left: IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Boolean, IsInvalid) (Syntax: 'result') Right: IParameterReferenceOperation: input1 (OperationKind.ParameterReference, Type: System.Boolean, IsInvalid) (Syntax: 'input1') Next (Regular) Block[B3#0R1] .erroneous body {R1#0R1} { Block[B2#0R1] - Block [UnReachable] Predecessors (0) Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid, IsImplicit) (Syntax: 'result = input2') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean, IsInvalid) (Syntax: 'result = input2') Left: IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Boolean, IsInvalid) (Syntax: 'result') Right: IParameterReferenceOperation: input2 (OperationKind.ParameterReference, Type: System.Boolean, IsInvalid) (Syntax: 'input2') Next (Regular) Block[B3#0R1] Leaving: {R1#0R1} } Block[B3#0R1] - Exit Predecessors: [B1#0R1] [B2#0R1] Statements (0) } } Block[B2] - Exit Predecessors: [B1] Statements (0) "; var expectedDiagnostics = new[] { // file.cs(7,9): error CS8057: Block bodies and expression bodies cannot both be provided. // void local(bool result, bool input1, bool input2) Diagnostic(ErrorCode.ERR_BlockBodyAndExpressionBody, @"void local(bool result, bool input1, bool input2) { result = input1; } => result = input2;").WithLocation(7, 9) }; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void LocalFunctionFlow_05() { string source = @" #pragma warning disable CS8321 struct C { void M() /*<bind>*/{ void local1(bool result1, bool input1) { result1 = input1; } void local2(bool result2, bool input2) => result2 = input2; }/*</bind>*/ } "; string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { Methods: [void local1(System.Boolean result1, System.Boolean input1)] [void local2(System.Boolean result2, System.Boolean input2)] Block[B1] - Block Predecessors: [B0] Statements (0) Next (Regular) Block[B2] Leaving: {R1} { void local1(System.Boolean result1, System.Boolean input1) Block[B0#0R1] - Entry Statements (0) Next (Regular) Block[B1#0R1] Block[B1#0R1] - Block Predecessors: [B0#0R1] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result1 = input1;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'result1 = input1') Left: IParameterReferenceOperation: result1 (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'result1') Right: IParameterReferenceOperation: input1 (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'input1') Next (Regular) Block[B2#0R1] Block[B2#0R1] - Exit Predecessors: [B1#0R1] Statements (0) } { void local2(System.Boolean result2, System.Boolean input2) Block[B0#1R1] - Entry Statements (0) Next (Regular) Block[B1#1R1] Block[B1#1R1] - Block Predecessors: [B0#1R1] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsImplicit) (Syntax: 'result2 = input2') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'result2 = input2') Left: IParameterReferenceOperation: result2 (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'result2') Right: IParameterReferenceOperation: input2 (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'input2') Next (Regular) Block[B2#1R1] Block[B2#1R1] - Exit Predecessors: [B1#1R1] Statements (0) } } Block[B2] - Exit Predecessors: [B1] Statements (0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void LocalFunctionFlow_06() { string source = @" struct C { void M(int input) /*<bind>*/{ int result; local1(input); int local1(int input1) { int i = local1(input1); result = local1(i); return result; } local1(result); }/*</bind>*/ } "; string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { Locals: [System.Int32 result] Methods: [System.Int32 local1(System.Int32 input1)] Block[B1] - Block Predecessors: [B0] Statements (2) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'local1(input);') Expression: IInvocationOperation (System.Int32 local1(System.Int32 input1)) (OperationKind.Invocation, Type: System.Int32) (Syntax: 'local1(input)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: input1) (OperationKind.Argument, Type: null) (Syntax: 'input') IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'input') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'local1(result);') Expression: IInvocationOperation (System.Int32 local1(System.Int32 input1)) (OperationKind.Invocation, Type: System.Int32) (Syntax: 'local1(result)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: input1) (OperationKind.Argument, Type: null) (Syntax: 'result') ILocalReferenceOperation: result (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'result') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Next (Regular) Block[B2] Leaving: {R1} { System.Int32 local1(System.Int32 input1) Block[B0#0R1] - Entry Statements (0) Next (Regular) Block[B1#0R1] Entering: {R1#0R1} .locals {R1#0R1} { Locals: [System.Int32 i] Block[B1#0R1] - Block Predecessors: [B0#0R1] Statements (2) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'i = local1(input1)') Left: ILocalReferenceOperation: i (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsImplicit) (Syntax: 'i = local1(input1)') Right: IInvocationOperation (System.Int32 local1(System.Int32 input1)) (OperationKind.Invocation, Type: System.Int32) (Syntax: 'local1(input1)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: input1) (OperationKind.Argument, Type: null) (Syntax: 'input1') IParameterReferenceOperation: input1 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'input1') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = local1(i);') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'result = local1(i)') Left: ILocalReferenceOperation: result (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'result') Right: IInvocationOperation (System.Int32 local1(System.Int32 input1)) (OperationKind.Invocation, Type: System.Int32) (Syntax: 'local1(i)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: input1) (OperationKind.Argument, Type: null) (Syntax: 'i') ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Next (Return) Block[B2#0R1] ILocalReferenceOperation: result (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'result') Leaving: {R1#0R1} } Block[B2#0R1] - Exit Predecessors: [B1#0R1] Statements (0) } } Block[B2] - Exit Predecessors: [B1] Statements (0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void LocalFunctionFlow_07() { string source = @" #pragma warning disable CS8321 struct C { void M() /*<bind>*/{ try { void local(bool result, bool input) { result = input; } } finally {} }/*</bind>*/ } "; string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { Methods: [void local(System.Boolean result, System.Boolean input)] Block[B1] - Block Predecessors: [B0] Statements (0) Next (Regular) Block[B2] Leaving: {R1} { void local(System.Boolean result, System.Boolean input) Block[B0#0R1] - Entry Statements (0) Next (Regular) Block[B1#0R1] Block[B1#0R1] - Block Predecessors: [B0#0R1] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = input;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'result = input') Left: IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'result') Right: IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'input') Next (Regular) Block[B2#0R1] Block[B2#0R1] - Exit Predecessors: [B1#0R1] Statements (0) } } Block[B2] - Exit Predecessors: [B1] Statements (0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void LocalFunctionFlow_08() { string source = @" #pragma warning disable CS8321 struct C { void M() /*<bind>*/{ int i = 0; void local1(int input1) { input1 = 1; i++; void local2(bool input2) { input2 = true; i++; } } }/*</bind>*/ } "; string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { Locals: [System.Int32 i] Methods: [void local1(System.Int32 input1)] Block[B1] - Block Predecessors: [B0] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'i = 0') Left: ILocalReferenceOperation: i (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsImplicit) (Syntax: 'i = 0') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0') Next (Regular) Block[B2] Leaving: {R1} { void local1(System.Int32 input1) Block[B0#0R1] - Entry Statements (0) Next (Regular) Block[B1#0R1] Entering: {R1#0R1} .locals {R1#0R1} { Methods: [void local2(System.Boolean input2)] Block[B1#0R1] - Block Predecessors: [B0#0R1] Statements (2) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'input1 = 1;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'input1 = 1') Left: IParameterReferenceOperation: input1 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'input1') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'i++;') Expression: IIncrementOrDecrementOperation (Postfix) (OperationKind.Increment, Type: System.Int32) (Syntax: 'i++') Target: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i') Next (Regular) Block[B2#0R1] Leaving: {R1#0R1} { void local2(System.Boolean input2) Block[B0#0R1#0R1] - Entry Statements (0) Next (Regular) Block[B1#0R1#0R1] Block[B1#0R1#0R1] - Block Predecessors: [B0#0R1#0R1] Statements (2) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'input2 = true;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'input2 = true') Left: IParameterReferenceOperation: input2 (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'input2') Right: ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'i++;') Expression: IIncrementOrDecrementOperation (Postfix) (OperationKind.Increment, Type: System.Int32) (Syntax: 'i++') Target: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i') Next (Regular) Block[B2#0R1#0R1] Block[B2#0R1#0R1] - Exit Predecessors: [B1#0R1#0R1] Statements (0) } } Block[B2#0R1] - Exit Predecessors: [B1#0R1] Statements (0) } } Block[B2] - Exit Predecessors: [B1] Statements (0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void LocalFunctionFlow_09() { string source = @" #pragma warning disable CS8321 class C { void M(C x, C y, C z) /*<bind>*/{ x = y ?? z; void local(C result, C input1, C input2) { result = input1 ?? input2; } }/*</bind>*/ } "; string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { Methods: [void local(C result, C input1, C input2)] CaptureIds: [0] [2] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'x') Value: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: C) (Syntax: 'x') 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: 'y') Value: IParameterReferenceOperation: y (OperationKind.ParameterReference, Type: C) (Syntax: 'y') Jump if True (Regular) to Block[B4] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'y') Operand: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'y') Leaving: {R2} Next (Regular) Block[B3] Block[B3] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'y') Value: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'y') Next (Regular) Block[B5] Leaving: {R2} } Block[B4] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'z') Value: IParameterReferenceOperation: z (OperationKind.ParameterReference, Type: C) (Syntax: 'z') Next (Regular) Block[B5] Block[B5] - Block Predecessors: [B3] [B4] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'x = y ?? z;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: C) (Syntax: 'x = y ?? z') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'x') Right: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'y ?? z') Next (Regular) Block[B6] Leaving: {R1} { void local(C result, C input1, C input2) Block[B0#0R1] - Entry Statements (0) Next (Regular) Block[B1#0R1] Entering: {R1#0R1} .locals {R1#0R1} { CaptureIds: [3] [5] Block[B1#0R1] - Block Predecessors: [B0#0R1] Statements (1) IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'result') Value: IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: C) (Syntax: 'result') Next (Regular) Block[B2#0R1] Entering: {R2#0R1} .locals {R2#0R1} { CaptureIds: [4] Block[B2#0R1] - Block Predecessors: [B1#0R1] Statements (1) IFlowCaptureOperation: 4 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input1') Value: IParameterReferenceOperation: input1 (OperationKind.ParameterReference, Type: C) (Syntax: 'input1') Jump if True (Regular) to Block[B4#0R1] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'input1') Operand: IFlowCaptureReferenceOperation: 4 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'input1') Leaving: {R2#0R1} Next (Regular) Block[B3#0R1] Block[B3#0R1] - Block Predecessors: [B2#0R1] Statements (1) IFlowCaptureOperation: 5 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input1') Value: IFlowCaptureReferenceOperation: 4 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'input1') Next (Regular) Block[B5#0R1] Leaving: {R2#0R1} } Block[B4#0R1] - Block Predecessors: [B2#0R1] Statements (1) IFlowCaptureOperation: 5 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input2') Value: IParameterReferenceOperation: input2 (OperationKind.ParameterReference, Type: C) (Syntax: 'input2') Next (Regular) Block[B5#0R1] Block[B5#0R1] - Block Predecessors: [B3#0R1] [B4#0R1] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = in ... ?? input2;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: C) (Syntax: 'result = in ... 1 ?? input2') Left: IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'result') Right: IFlowCaptureReferenceOperation: 5 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'input1 ?? input2') Next (Regular) Block[B6#0R1] Leaving: {R1#0R1} } Block[B6#0R1] - Exit Predecessors: [B5#0R1] Statements (0) } } Block[B6] - Exit Predecessors: [B5] Statements (0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void LocalFunctionFlow_10() { string source = @" #pragma warning disable CS8321 class C { void M() /*<bind>*/{ void local1(C result1, C input11, C input12) { result1 = input11 ?? input12; } void local2(C result2, C input21, C input22) { result2 = input21 ?? input22; } }/*</bind>*/ } "; string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { Methods: [void local1(C result1, C input11, C input12)] [void local2(C result2, C input21, C input22)] Block[B1] - Block Predecessors: [B0] Statements (0) Next (Regular) Block[B2] Leaving: {R1} { void local1(C result1, C input11, C input12) Block[B0#0R1] - Entry Statements (0) Next (Regular) Block[B1#0R1] Entering: {R1#0R1} .locals {R1#0R1} { CaptureIds: [0] [2] Block[B1#0R1] - Block Predecessors: [B0#0R1] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'result1') Value: IParameterReferenceOperation: result1 (OperationKind.ParameterReference, Type: C) (Syntax: 'result1') Next (Regular) Block[B2#0R1] Entering: {R2#0R1} .locals {R2#0R1} { CaptureIds: [1] Block[B2#0R1] - Block Predecessors: [B1#0R1] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input11') Value: IParameterReferenceOperation: input11 (OperationKind.ParameterReference, Type: C) (Syntax: 'input11') Jump if True (Regular) to Block[B4#0R1] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'input11') Operand: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'input11') Leaving: {R2#0R1} Next (Regular) Block[B3#0R1] Block[B3#0R1] - Block Predecessors: [B2#0R1] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input11') Value: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'input11') Next (Regular) Block[B5#0R1] Leaving: {R2#0R1} } Block[B4#0R1] - Block Predecessors: [B2#0R1] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input12') Value: IParameterReferenceOperation: input12 (OperationKind.ParameterReference, Type: C) (Syntax: 'input12') Next (Regular) Block[B5#0R1] Block[B5#0R1] - Block Predecessors: [B3#0R1] [B4#0R1] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result1 = i ... ?? input12;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: C) (Syntax: 'result1 = i ... ?? input12') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'result1') Right: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'input11 ?? input12') Next (Regular) Block[B6#0R1] Leaving: {R1#0R1} } Block[B6#0R1] - Exit Predecessors: [B5#0R1] Statements (0) } { void local2(C result2, C input21, C input22) Block[B0#1R1] - Entry Statements (0) Next (Regular) Block[B1#1R1] Entering: {R1#1R1} .locals {R1#1R1} { CaptureIds: [3] [5] Block[B1#1R1] - Block Predecessors: [B0#1R1] Statements (1) IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'result2') Value: IParameterReferenceOperation: result2 (OperationKind.ParameterReference, Type: C) (Syntax: 'result2') Next (Regular) Block[B2#1R1] Entering: {R2#1R1} .locals {R2#1R1} { CaptureIds: [4] Block[B2#1R1] - Block Predecessors: [B1#1R1] Statements (1) IFlowCaptureOperation: 4 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input21') Value: IParameterReferenceOperation: input21 (OperationKind.ParameterReference, Type: C) (Syntax: 'input21') Jump if True (Regular) to Block[B4#1R1] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'input21') Operand: IFlowCaptureReferenceOperation: 4 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'input21') Leaving: {R2#1R1} Next (Regular) Block[B3#1R1] Block[B3#1R1] - Block Predecessors: [B2#1R1] Statements (1) IFlowCaptureOperation: 5 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input21') Value: IFlowCaptureReferenceOperation: 4 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'input21') Next (Regular) Block[B5#1R1] Leaving: {R2#1R1} } Block[B4#1R1] - Block Predecessors: [B2#1R1] Statements (1) IFlowCaptureOperation: 5 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input22') Value: IParameterReferenceOperation: input22 (OperationKind.ParameterReference, Type: C) (Syntax: 'input22') Next (Regular) Block[B5#1R1] Block[B5#1R1] - Block Predecessors: [B3#1R1] [B4#1R1] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result2 = i ... ?? input22;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: C) (Syntax: 'result2 = i ... ?? input22') Left: IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'result2') Right: IFlowCaptureReferenceOperation: 5 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'input21 ?? input22') Next (Regular) Block[B6#1R1] Leaving: {R1#1R1} } Block[B6#1R1] - Exit Predecessors: [B5#1R1] Statements (0) } } Block[B2] - Exit Predecessors: [B1] Statements (0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void LocalFunctionFlow_11() { string source = @" struct C { void M() /*<bind>*/{ void d1() { void d2(bool result1, bool input1) { result1 = input1; } }; }/*</bind>*/ } "; var compilation = CreateCompilation(source); var tree = compilation.SyntaxTrees.Single(); var semanticModel = compilation.GetSemanticModel(tree); var graphM = ControlFlowGraph.Create((IMethodBodyOperation)semanticModel.GetOperation(tree.GetRoot().DescendantNodes().OfType<MethodDeclarationSyntax>().First())); Assert.NotNull(graphM); Assert.Null(graphM.Parent); IMethodSymbol localFunctionD1 = getLocalFunction(graphM); Assert.NotNull(localFunctionD1); Assert.Equal("d1", localFunctionD1.Name); var graphD1 = graphM.GetLocalFunctionControlFlowGraph(localFunctionD1); Assert.NotNull(graphD1); Assert.Same(graphM, graphD1.Parent); var graphD1_FromExtension = graphM.GetLocalFunctionControlFlowGraphInScope(localFunctionD1); Assert.Same(graphD1, graphD1_FromExtension); IMethodSymbol localFunctionD2 = getLocalFunction(graphD1); Assert.NotNull(localFunctionD2); Assert.Equal("d2", localFunctionD2.Name); var graphD2 = graphD1.GetLocalFunctionControlFlowGraph(localFunctionD2); Assert.NotNull(graphD2); Assert.Same(graphD1, graphD2.Parent); Assert.Throws<ArgumentNullException>(() => graphM.GetLocalFunctionControlFlowGraph(null)); Assert.Throws<ArgumentOutOfRangeException>(() => graphM.GetLocalFunctionControlFlowGraph(localFunctionD2)); Assert.Throws<ArgumentNullException>(() => graphM.GetLocalFunctionControlFlowGraphInScope(null)); Assert.Throws<ArgumentOutOfRangeException>(() => graphM.GetLocalFunctionControlFlowGraphInScope(localFunctionD2)); IMethodSymbol getLocalFunction(ControlFlowGraph graph) { return graph.LocalFunctions.Single(); } } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void LocalFunctionFlow_12() { string source = @" struct C { void M() /*<bind>*/{ void d1() { } void d2() { d1(); } }/*</bind>*/ } "; var compilation = CreateCompilation(source); var tree = compilation.SyntaxTrees.Single(); var semanticModel = compilation.GetSemanticModel(tree); var graphM = ControlFlowGraph.Create((IMethodBodyOperation)semanticModel.GetOperation(tree.GetRoot().DescendantNodes().OfType<MethodDeclarationSyntax>().First())); Assert.NotNull(graphM); Assert.Null(graphM.Parent); IMethodSymbol localFunctionD1 = getLocalFunction(graphM, "d1"); Assert.NotNull(localFunctionD1); IMethodSymbol localFunctionD2 = getLocalFunction(graphM, "d2"); Assert.NotNull(localFunctionD2); var graphD1 = graphM.GetLocalFunctionControlFlowGraph(localFunctionD1); Assert.NotNull(graphD1); Assert.Same(graphM, graphD1.Parent); var graphD2 = graphM.GetLocalFunctionControlFlowGraph(localFunctionD2); Assert.NotNull(graphD2); Assert.Same(graphM, graphD2.Parent); var graphD1_FromExtension = graphM.GetLocalFunctionControlFlowGraphInScope(localFunctionD1); Assert.Same(graphD1, graphD1_FromExtension); Assert.Throws<ArgumentOutOfRangeException>(() => graphD2.GetLocalFunctionControlFlowGraph(localFunctionD1)); graphD1_FromExtension = graphD2.GetLocalFunctionControlFlowGraphInScope(localFunctionD1); Assert.Same(graphD1, graphD1_FromExtension); IMethodSymbol getLocalFunction(ControlFlowGraph graph, string name) { return graph.LocalFunctions.Single(l => l.Name == name); } } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void LocalFunctionFlow_StaticWithShadowedVariableReference() { string source = @"#pragma warning disable 0219 #pragma warning disable 8321 class C { static void M() /*<bind>*/ { object x = null; object y = null; static object Local(string y, object z) => x ?? y ?? z; } /*</bind>*/ }"; string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { Locals: [System.Object x] [System.Object y] Methods: [System.Object Local(System.String y, System.Object z)] Block[B1] - Block Predecessors: [B0] Statements (2) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Object, IsImplicit) (Syntax: 'x = null') Left: ILocalReferenceOperation: x (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Object, IsImplicit) (Syntax: 'x = null') Right: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, Constant: null, IsImplicit) (Syntax: 'null') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) (ImplicitReference) Operand: ILiteralOperation (OperationKind.Literal, Type: null, Constant: null) (Syntax: 'null') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Object, IsImplicit) (Syntax: 'y = null') Left: ILocalReferenceOperation: y (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Object, IsImplicit) (Syntax: 'y = null') Right: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, Constant: null, IsImplicit) (Syntax: 'null') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) (ImplicitReference) Operand: ILiteralOperation (OperationKind.Literal, Type: null, Constant: null) (Syntax: 'null') Next (Regular) Block[B2] Leaving: {R1} { System.Object Local(System.String y, System.Object z) Block[B0#0R1] - Entry Statements (0) Next (Regular) Block[B1#0R1] Entering: {R1#0R1} {R2#0R1} .locals {R1#0R1} { CaptureIds: [1] .locals {R2#0R1} { CaptureIds: [0] Block[B1#0R1] - Block Predecessors: [B0#0R1] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'x') Value: ILocalReferenceOperation: x (OperationKind.LocalReference, Type: System.Object, IsInvalid) (Syntax: 'x') Jump if True (Regular) to Block[B3#0R1] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsInvalid, IsImplicit) (Syntax: 'x') Operand: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Object, IsInvalid, IsImplicit) (Syntax: 'x') Leaving: {R2#0R1} Entering: {R3#0R1} Next (Regular) Block[B2#0R1] Block[B2#0R1] - Block Predecessors: [B1#0R1] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'x') Value: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Object, IsInvalid, IsImplicit) (Syntax: 'x') Next (Regular) Block[B6#0R1] Leaving: {R2#0R1} } .locals {R3#0R1} { CaptureIds: [2] Block[B3#0R1] - Block Predecessors: [B1#0R1] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'y') Value: IParameterReferenceOperation: y (OperationKind.ParameterReference, Type: System.String) (Syntax: 'y') Jump if True (Regular) to Block[B5#0R1] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'y') Operand: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.String, IsImplicit) (Syntax: 'y') Leaving: {R3#0R1} Next (Regular) Block[B4#0R1] Block[B4#0R1] - Block Predecessors: [B3#0R1] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'y') Value: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsImplicit) (Syntax: 'y') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) (ImplicitReference) Operand: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.String, IsImplicit) (Syntax: 'y') Next (Regular) Block[B6#0R1] Leaving: {R3#0R1} } Block[B5#0R1] - Block Predecessors: [B3#0R1] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'z') Value: IParameterReferenceOperation: z (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'z') Next (Regular) Block[B6#0R1] Block[B6#0R1] - Block Predecessors: [B2#0R1] [B4#0R1] [B5#0R1] Statements (0) Next (Return) Block[B7#0R1] IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Object, IsInvalid, IsImplicit) (Syntax: 'x ?? y ?? z') Leaving: {R1#0R1} } Block[B7#0R1] - Exit Predecessors: [B6#0R1] Statements (0) } } Block[B2] - Exit Predecessors: [B1] Statements (0) "; var expectedDiagnostics = new[] { // (10,52): error CS8421: A static local function cannot contain a reference to 'x'. // static object Local(string y, object z) => x ?? y ?? z; Diagnostic(ErrorCode.ERR_StaticLocalFunctionCannotCaptureVariable, "x").WithArguments("x").WithLocation(10, 52) }; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedGraph, expectedDiagnostics); } } }
-1
dotnet/roslyn
55,430
Fix LSP semantic tokens algorithm
This PR primarily accomplishes two tasks: 1) Overhauls the existing LSP semantic tokens edits processing algorithm to align with [Razor's](https://github.com/dotnet/aspnetcore-tooling/blob/main/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/Semantic/Services/SemanticTokensEditsDiffer.cs) (shoutout to Ryan and the rest of the Razor team for writing the original 😄). The main change here is going from calculating edits per token (i.e. five ints) to per int. The updated algorithm is much more efficient than our previous algorithm, and returns less edits back to the LSP client. 2) The interpretation of Roslyn's LongestCommonSubstring algorithm, which we use to calculate raw edits, was missing a critical piece. Namely, for insertions, we need to keep track of _where_ we should be inserting into the original token set. We don't keep track of this in the existing implementation, resulting in bugs such as #54671. Resolves #54671
allisonchou
2021-08-05T06:06:43Z
2021-08-06T23:44:44Z
b9200d03a76c74d404040d44b9bbe12b1d0a8ef2
f300a818940ea1acef66c946cfa83756729d5e59
Fix LSP semantic tokens algorithm. This PR primarily accomplishes two tasks: 1) Overhauls the existing LSP semantic tokens edits processing algorithm to align with [Razor's](https://github.com/dotnet/aspnetcore-tooling/blob/main/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/Semantic/Services/SemanticTokensEditsDiffer.cs) (shoutout to Ryan and the rest of the Razor team for writing the original 😄). The main change here is going from calculating edits per token (i.e. five ints) to per int. The updated algorithm is much more efficient than our previous algorithm, and returns less edits back to the LSP client. 2) The interpretation of Roslyn's LongestCommonSubstring algorithm, which we use to calculate raw edits, was missing a critical piece. Namely, for insertions, we need to keep track of _where_ we should be inserting into the original token set. We don't keep track of this in the existing implementation, resulting in bugs such as #54671. Resolves #54671
./src/Compilers/Core/Portable/Collections/IdentifierCollection.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; using System.Diagnostics; namespace Microsoft.CodeAnalysis { /// <summary> /// A dictionary that maps strings to all known spellings of that string. Can be used to /// efficiently store the set of known type names for a module for both VB and C# while also /// answering questions like "do you have a type called Goo" in either a case sensitive or /// insensitive manner. /// </summary> internal partial class IdentifierCollection { // Maps an identifier to all spellings of that identifier in this module. The value type is // typed as object so that it can store either an individual element (the common case), or a // collection. // // Note: we use a case insensitive comparer so that we can quickly lookup if we know a name // regardless of its case. private readonly Dictionary<string, object> _map = new Dictionary<string, object>( StringComparer.OrdinalIgnoreCase); public IdentifierCollection() { } public IdentifierCollection(IEnumerable<string> identifiers) { this.AddIdentifiers(identifiers); } public void AddIdentifiers(IEnumerable<string> identifiers) { foreach (var identifier in identifiers) { AddIdentifier(identifier); } } public void AddIdentifier(string identifier) { RoslynDebug.Assert(identifier != null); object? value; if (!_map.TryGetValue(identifier, out value)) { AddInitialSpelling(identifier); } else { AddAdditionalSpelling(identifier, value); } } private void AddAdditionalSpelling(string identifier, object value) { // Had a mapping for it. It will either map to a single // spelling, or to a set of spellings. var strValue = value as string; if (strValue != null) { if (!string.Equals(identifier, strValue, StringComparison.Ordinal)) { // We now have two spellings. Create a collection for // that and map the name to it. _map[identifier] = new HashSet<string> { identifier, strValue }; } } else { // We have multiple spellings already. var spellings = (HashSet<string>)value; // Note: the set will prevent duplicates. spellings.Add(identifier); } } private void AddInitialSpelling(string identifier) { // We didn't have any spellings for this word already. Just // add the word as the single known spelling. _map.Add(identifier, identifier); } public bool ContainsIdentifier(string identifier, bool caseSensitive) { RoslynDebug.Assert(identifier != null); if (caseSensitive) { return CaseSensitiveContains(identifier); } else { return CaseInsensitiveContains(identifier); } } private bool CaseInsensitiveContains(string identifier) { // Simple case. Just check if we've mapped this word to // anything. The map will take care of the case insensitive // lookup for us. return _map.ContainsKey(identifier); } private bool CaseSensitiveContains(string identifier) { object? spellings; if (_map.TryGetValue(identifier, out spellings)) { var spelling = spellings as string; if (spelling != null) { return string.Equals(identifier, spelling, StringComparison.Ordinal); } var set = (HashSet<string>)spellings; return set.Contains(identifier); } return false; } public ICollection<string> AsCaseSensitiveCollection() { return new CaseSensitiveCollection(this); } public ICollection<string> AsCaseInsensitiveCollection() { return new CaseInsensitiveCollection(this); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; using System.Diagnostics; namespace Microsoft.CodeAnalysis { /// <summary> /// A dictionary that maps strings to all known spellings of that string. Can be used to /// efficiently store the set of known type names for a module for both VB and C# while also /// answering questions like "do you have a type called Goo" in either a case sensitive or /// insensitive manner. /// </summary> internal partial class IdentifierCollection { // Maps an identifier to all spellings of that identifier in this module. The value type is // typed as object so that it can store either an individual element (the common case), or a // collection. // // Note: we use a case insensitive comparer so that we can quickly lookup if we know a name // regardless of its case. private readonly Dictionary<string, object> _map = new Dictionary<string, object>( StringComparer.OrdinalIgnoreCase); public IdentifierCollection() { } public IdentifierCollection(IEnumerable<string> identifiers) { this.AddIdentifiers(identifiers); } public void AddIdentifiers(IEnumerable<string> identifiers) { foreach (var identifier in identifiers) { AddIdentifier(identifier); } } public void AddIdentifier(string identifier) { RoslynDebug.Assert(identifier != null); object? value; if (!_map.TryGetValue(identifier, out value)) { AddInitialSpelling(identifier); } else { AddAdditionalSpelling(identifier, value); } } private void AddAdditionalSpelling(string identifier, object value) { // Had a mapping for it. It will either map to a single // spelling, or to a set of spellings. var strValue = value as string; if (strValue != null) { if (!string.Equals(identifier, strValue, StringComparison.Ordinal)) { // We now have two spellings. Create a collection for // that and map the name to it. _map[identifier] = new HashSet<string> { identifier, strValue }; } } else { // We have multiple spellings already. var spellings = (HashSet<string>)value; // Note: the set will prevent duplicates. spellings.Add(identifier); } } private void AddInitialSpelling(string identifier) { // We didn't have any spellings for this word already. Just // add the word as the single known spelling. _map.Add(identifier, identifier); } public bool ContainsIdentifier(string identifier, bool caseSensitive) { RoslynDebug.Assert(identifier != null); if (caseSensitive) { return CaseSensitiveContains(identifier); } else { return CaseInsensitiveContains(identifier); } } private bool CaseInsensitiveContains(string identifier) { // Simple case. Just check if we've mapped this word to // anything. The map will take care of the case insensitive // lookup for us. return _map.ContainsKey(identifier); } private bool CaseSensitiveContains(string identifier) { object? spellings; if (_map.TryGetValue(identifier, out spellings)) { var spelling = spellings as string; if (spelling != null) { return string.Equals(identifier, spelling, StringComparison.Ordinal); } var set = (HashSet<string>)spellings; return set.Contains(identifier); } return false; } public ICollection<string> AsCaseSensitiveCollection() { return new CaseSensitiveCollection(this); } public ICollection<string> AsCaseInsensitiveCollection() { return new CaseInsensitiveCollection(this); } } }
-1
dotnet/roslyn
55,430
Fix LSP semantic tokens algorithm
This PR primarily accomplishes two tasks: 1) Overhauls the existing LSP semantic tokens edits processing algorithm to align with [Razor's](https://github.com/dotnet/aspnetcore-tooling/blob/main/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/Semantic/Services/SemanticTokensEditsDiffer.cs) (shoutout to Ryan and the rest of the Razor team for writing the original 😄). The main change here is going from calculating edits per token (i.e. five ints) to per int. The updated algorithm is much more efficient than our previous algorithm, and returns less edits back to the LSP client. 2) The interpretation of Roslyn's LongestCommonSubstring algorithm, which we use to calculate raw edits, was missing a critical piece. Namely, for insertions, we need to keep track of _where_ we should be inserting into the original token set. We don't keep track of this in the existing implementation, resulting in bugs such as #54671. Resolves #54671
allisonchou
2021-08-05T06:06:43Z
2021-08-06T23:44:44Z
b9200d03a76c74d404040d44b9bbe12b1d0a8ef2
f300a818940ea1acef66c946cfa83756729d5e59
Fix LSP semantic tokens algorithm. This PR primarily accomplishes two tasks: 1) Overhauls the existing LSP semantic tokens edits processing algorithm to align with [Razor's](https://github.com/dotnet/aspnetcore-tooling/blob/main/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/Semantic/Services/SemanticTokensEditsDiffer.cs) (shoutout to Ryan and the rest of the Razor team for writing the original 😄). The main change here is going from calculating edits per token (i.e. five ints) to per int. The updated algorithm is much more efficient than our previous algorithm, and returns less edits back to the LSP client. 2) The interpretation of Roslyn's LongestCommonSubstring algorithm, which we use to calculate raw edits, was missing a critical piece. Namely, for insertions, we need to keep track of _where_ we should be inserting into the original token set. We don't keep track of this in the existing implementation, resulting in bugs such as #54671. Resolves #54671
./src/ExpressionEvaluator/VisualBasic/Test/ExpressionCompiler/TupleTests.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.Collections.ObjectModel Imports System.IO Imports Microsoft.CodeAnalysis.CodeGen Imports Microsoft.CodeAnalysis.ExpressionEvaluator Imports Microsoft.CodeAnalysis.ExpressionEvaluator.UnitTests Imports Microsoft.CodeAnalysis.PooledObjects Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.UnitTests Imports Microsoft.VisualStudio.Debugger.Clr Imports Microsoft.VisualStudio.Debugger.Evaluation Imports Microsoft.VisualStudio.Debugger.Evaluation.ClrCompilation Imports Roslyn.Test.Utilities Imports Xunit Namespace Microsoft.CodeAnalysis.VisualBasic.ExpressionEvaluator.UnitTests Public Class TupleTests Inherits ExpressionCompilerTestBase <Fact> Public Sub Literal() Const source = "Class C Shared Sub M() Dim o As (Integer, Integer) End Sub End Class" Dim comp = CreateCompilationWithMscorlib40({source}, references:={ValueTupleRef, SystemRuntimeFacadeRef}, options:=TestOptions.DebugDll) WithRuntimeInstance(comp, {MscorlibRef, ValueTupleRef, SystemRuntimeFacadeRef}, Sub(runtime) Dim context = CreateMethodContext(runtime, "C.M") Dim errorMessage As String = Nothing Dim testData = New CompilationTestData() Dim result = context.CompileExpression( "(A:=1, B:=2)", DkmEvaluationFlags.TreatAsExpression, NoAliases, errorMessage, testData) Assert.Null(errorMessage) Dim typeInfo As ReadOnlyCollection(Of Byte) = Nothing Dim typeInfoId = result.GetCustomTypeInfo(typeInfo) Assert.NotNull(typeInfo) Dim dynamicFlags As ReadOnlyCollection(Of Byte) = Nothing Dim tupleElementNames As ReadOnlyCollection(Of String) = Nothing CustomTypeInfo.Decode(typeInfoId, typeInfo, dynamicFlags, tupleElementNames) Assert.Equal({"A", "B"}, tupleElementNames) Dim methodData = testData.GetMethodData("<>x.<>m0") Dim method = methodData.Method Assert.True(method.ReturnType.IsTupleType) CheckAttribute(result.Assembly, method, AttributeDescription.TupleElementNamesAttribute, expected:=True) methodData.VerifyIL( "{ // Code size 8 (0x8) .maxstack 2 .locals init (System.ValueTuple(Of Integer, Integer) V_0) //o IL_0000: ldc.i4.1 IL_0001: ldc.i4.2 IL_0002: newobj ""Sub System.ValueTuple(Of Integer, Integer)..ctor(Integer, Integer)"" IL_0007: ret }") End Sub) End Sub <Fact> Public Sub DuplicateValueTupleBetweenMscorlibAndLibrary() Const versionTemplate = "<Assembly: System.Reflection.AssemblyVersion(""{0}.0.0.0"")>" Const corlib_vb = " Namespace System Public Class [Object] End Class Public Structure Void End Structure Public Class ValueType End Class Public Structure IntPtr End Structure Public Structure Int32 End Structure Public Class [String] End Class Public Class Attribute End Class End Namespace Namespace System.Reflection Public Class AssemblyVersionAttribute Inherits Attribute Public Sub New(version As String) End Sub End Class End Namespace " Dim corlibWithoutVT = CreateEmptyCompilation({String.Format(versionTemplate, "1") + corlib_vb}, options:=TestOptions.DebugDll, assemblyName:="corlib") corlibWithoutVT.AssertTheseDiagnostics() Dim corlibWithoutVTRef = corlibWithoutVT.EmitToImageReference() Const valuetuple_vb As String = " Namespace System Public Structure ValueTuple(Of T1, T2) Public Dim Item1 As T1 Public Dim Item2 As T2 Public Sub New(item1 As T1, item2 As T2) End Sub End Structure End Namespace " Dim corlibWithVT = CreateEmptyCompilation({String.Format(versionTemplate, "2") + corlib_vb + valuetuple_vb}, options:=TestOptions.DebugDll, assemblyName:="corlib") corlibWithVT.AssertTheseDiagnostics() Const source As String = "Class C Shared Function M() As (Integer, Integer) Dim o = (1, 2) Return o End Function End Class" Dim app = CreateEmptyCompilation(source + valuetuple_vb, references:={corlibWithoutVTRef}, options:=TestOptions.DebugDll) app.AssertTheseDiagnostics() Dim runtime = CreateRuntimeInstance({app.ToModuleInstance(), corlibWithVT.ToModuleInstance()}) ' Create EE context with app assembly (including ValueTuple) and a more recent corlib (also including ValueTuple) Dim evalContext = CreateMethodContext(runtime, "C.M") Dim errorMessage As String = Nothing Dim testData = New CompilationTestData() Dim compileResult = evalContext.CompileExpression("(1, 2)", errorMessage, testData) Assert.Null(errorMessage) Using block As ModuleMetadata = ModuleMetadata.CreateFromStream(New MemoryStream(compileResult.Assembly)) Dim reader = block.MetadataReader Dim appRef = app.Assembly.Identity.Name AssertEx.SetEqual({"corlib 2.0", appRef + " 0.0"}, reader.DumpAssemblyReferences()) AssertEx.SetEqual({"Object, System, AssemblyReference:corlib", "ValueTuple`2, System, AssemblyReference:" + appRef}, ' ValueTuple comes from app, not corlib reader.DumpTypeReferences()) End Using End Sub <Fact> Public Sub TupleElementNamesAttribute_NotAvailable() Const source = "Namespace System Public Structure ValueTuple(Of T1, T2) Public Item1 As T1 Public Item2 As T2 Public Sub New(_1 As T1, _2 As T2) Item1 = _1 Item2 = _2 End Sub End Structure End Namespace Class C Shared Sub M() Dim o As (Integer, Integer) End Sub End Class" Dim comp = CreateCompilationWithMscorlib40({source}, options:=TestOptions.DebugDll) WithRuntimeInstance(comp, Sub(runtime) Dim context = CreateMethodContext(runtime, "C.M") Dim errorMessage As String = Nothing Dim testData = New CompilationTestData() Dim result = context.CompileExpression( "(A:=1, B:=2)", DkmEvaluationFlags.TreatAsExpression, NoAliases, errorMessage, testData) Assert.Null(errorMessage) Dim typeInfo As ReadOnlyCollection(Of Byte) = Nothing Dim typeInfoId = result.GetCustomTypeInfo(typeInfo) Assert.Null(typeInfo) Dim methodData = testData.GetMethodData("<>x.<>m0") Dim method = methodData.Method Assert.True(method.ReturnType.IsTupleType) CheckAttribute(result.Assembly, method, AttributeDescription.TupleElementNamesAttribute, expected:=False) methodData.VerifyIL( "{ // Code size 8 (0x8) .maxstack 2 .locals init (System.ValueTuple(Of Integer, Integer) V_0) //o IL_0000: ldc.i4.1 IL_0001: ldc.i4.2 IL_0002: newobj ""Sub System.ValueTuple(Of Integer, Integer)..ctor(Integer, Integer)"" IL_0007: ret }") End Sub) End Sub <WorkItem(13948, "https://github.com/dotnet/roslyn/issues/13948")> <Fact> Public Sub Local() Const source = "class C { static void M() { (int A, int B) o = (1, 2); } }" Dim comp = CreateCSharpCompilation(source, referencedAssemblies:={MscorlibRef, ValueTupleRef, SystemRuntimeFacadeRef}) WithRuntimeInstance(comp, {MscorlibRef, ValueTupleRef, SystemRuntimeFacadeRef}, Sub(runtime) Dim context = CreateMethodContext(runtime, "C.M") Dim testData = New CompilationTestData() Dim locals = ArrayBuilder(Of LocalAndMethod).GetInstance() Dim typeName As String = Nothing Dim assembly = context.CompileGetLocals(locals, argumentsOnly:=False, typeName:=typeName, testData:=testData) Assert.Equal(1, locals.Count) Dim typeInfo As ReadOnlyCollection(Of Byte) = Nothing Dim typeInfoId = locals(0).GetCustomTypeInfo(typeInfo) Dim dynamicFlags As ReadOnlyCollection(Of Byte) = Nothing Dim tupleElementNames As ReadOnlyCollection(Of String) = Nothing CustomTypeInfo.Decode(typeInfoId, typeInfo, dynamicFlags, tupleElementNames) Assert.Equal({"A", "B"}, tupleElementNames) Dim method = testData.Methods.Single().Value.Method CheckAttribute(assembly, method, AttributeDescription.TupleElementNamesAttribute, expected:=True) Assert.True(method.ReturnType.IsTupleType) VerifyLocal(testData, typeName, locals(0), "<>m0", "o", expectedILOpt:= "{ // Code size 2 (0x2) .maxstack 1 .locals init (System.ValueTuple(Of Integer, Integer) V_0) //o IL_0000: ldloc.0 IL_0001: ret }") locals.Free() End Sub) End Sub <WorkItem(13948, "https://github.com/dotnet/roslyn/issues/13948")> <Fact> Public Sub Constant() Const source = "class A<T> { internal class B<U> { } } class C { static (object, object) F; static void M() { const A<(int, int A)>.B<(object B, object)>[] c = null; } }" Dim comp = CreateCSharpCompilation(source, referencedAssemblies:={MscorlibRef, ValueTupleRef, SystemRuntimeFacadeRef}) WithRuntimeInstance(comp, {MscorlibRef, ValueTupleRef, SystemRuntimeFacadeRef}, Sub(runtime) Dim context = CreateMethodContext(runtime, "C.M") Dim testData = New CompilationTestData() Dim locals = ArrayBuilder(Of LocalAndMethod).GetInstance() Dim typeName As String = Nothing Dim assembly = context.CompileGetLocals(locals, argumentsOnly:=False, typeName:=typeName, testData:=testData) Assert.Equal(1, locals.Count) Dim typeInfo As ReadOnlyCollection(Of Byte) = Nothing Dim typeInfoId = locals(0).GetCustomTypeInfo(typeInfo) Dim dynamicFlags As ReadOnlyCollection(Of Byte) = Nothing Dim tupleElementNames As ReadOnlyCollection(Of String) = Nothing CustomTypeInfo.Decode(typeInfoId, typeInfo, dynamicFlags, tupleElementNames) Assert.Equal({Nothing, "A", "B", Nothing}, tupleElementNames) Dim method = DirectCast(testData.Methods.Single().Value.Method, MethodSymbol) CheckAttribute(assembly, method, AttributeDescription.TupleElementNamesAttribute, expected:=True) Dim returnType = method.ReturnType Assert.False(returnType.IsTupleType) Assert.True(returnType.ContainsTuple()) VerifyLocal(testData, typeName, locals(0), "<>m0", "c", expectedFlags:=DkmClrCompilationResultFlags.ReadOnlyResult, expectedILOpt:= "{ // Code size 2 (0x2) .maxstack 1 IL_0000: ldnull IL_0001: ret }") locals.Free() End Sub) End Sub <WorkItem(13803, "https://github.com/dotnet/roslyn/issues/13803")> <Fact> Public Sub LongTupleLocalElement_NoNames() Const source = "Class C Shared Sub M() Dim x = (1, 2, 3, 4, 5, 6, 7, 8) End Sub End Class" Dim comp = CreateCompilationWithMscorlib40({source}, references:={SystemRuntimeFacadeRef, ValueTupleRef}, options:=TestOptions.DebugDll) WithRuntimeInstance(comp, {MscorlibRef, SystemCoreRef, SystemRuntimeFacadeRef, ValueTupleRef}, Sub(runtime) Dim context = CreateMethodContext(runtime, "C.M") Dim errorMessage As String = Nothing Dim testData = New CompilationTestData() context.CompileExpression( "x.Item4 + x.Item8", DkmEvaluationFlags.TreatAsExpression, NoAliases, errorMessage, testData) testData.GetMethodData("<>x.<>m0").VerifyIL( "{ // Code size 19 (0x13) .maxstack 2 .locals init (System.ValueTuple(Of Integer, Integer, Integer, Integer, Integer, Integer, Integer, ValueTuple(Of Integer)) V_0) //x IL_0000: ldloc.0 IL_0001: ldfld ""System.ValueTuple(Of Integer, Integer, Integer, Integer, Integer, Integer, Integer, ValueTuple(Of Integer)).Item4 As Integer"" IL_0006: ldloc.0 IL_0007: ldfld ""System.ValueTuple(Of Integer, Integer, Integer, Integer, Integer, Integer, Integer, ValueTuple(Of Integer)).Rest As ValueTuple(Of Integer)"" IL_000c: ldfld ""System.ValueTuple(Of Integer).Item1 As Integer"" IL_0011: add.ovf IL_0012: ret }") End Sub) End Sub <Fact> Public Sub LongTupleLocalElement_Names() Const source = "Class C Shared Sub M() Dim x = (1, 2, Three:=3, Four:=4, 5, 6, 7, Eight:=8) End Sub End Class" Dim comp = CreateCompilationWithMscorlib40({source}, references:={SystemRuntimeFacadeRef, ValueTupleRef}, options:=TestOptions.DebugDll) WithRuntimeInstance(comp, {MscorlibRef, SystemCoreRef, SystemRuntimeFacadeRef, ValueTupleRef}, Sub(runtime) Dim context = CreateMethodContext(runtime, "C.M") Dim errorMessage As String = Nothing Dim testData = New CompilationTestData() context.CompileExpression( "x.Item8 + x.Eight", DkmEvaluationFlags.TreatAsExpression, NoAliases, errorMessage, testData) testData.GetMethodData("<>x.<>m0").VerifyIL( "{ // Code size 24 (0x18) .maxstack 2 .locals init (System.ValueTuple(Of Integer, Integer, Integer, Integer, Integer, Integer, Integer, ValueTuple(Of Integer)) V_0) //x IL_0000: ldloc.0 IL_0001: ldfld ""System.ValueTuple(Of Integer, Integer, Integer, Integer, Integer, Integer, Integer, ValueTuple(Of Integer)).Rest As ValueTuple(Of Integer)"" IL_0006: ldfld ""System.ValueTuple(Of Integer).Item1 As Integer"" IL_000b: ldloc.0 IL_000c: ldfld ""System.ValueTuple(Of Integer, Integer, Integer, Integer, Integer, Integer, Integer, ValueTuple(Of Integer)).Rest As ValueTuple(Of Integer)"" IL_0011: ldfld ""System.ValueTuple(Of Integer).Item1 As Integer"" IL_0016: add.ovf IL_0017: ret }") End Sub) End Sub ''' <summary> ''' Locals declared in the VB EE do not have an explicit ''' type and are statically typed to Object, so tuple ''' element names on the value are not preserved. ''' </summary> <Fact> Public Sub DeclareLocal() Const source = "Class C Shared Sub M() Dim x = (1, 2) End Sub End Class" Dim comp = CreateCompilationWithMscorlib40({source}, references:={ValueTupleRef, SystemRuntimeFacadeRef}, options:=TestOptions.DebugDll) WithRuntimeInstance(comp, references:={MscorlibRef, ValueTupleRef, SystemRuntimeFacadeRef}, validator:=Sub(runtime) Dim context = CreateMethodContext(runtime, "C.M") Dim errorMessage As String = Nothing Dim testData = New CompilationTestData() Dim result = context.CompileExpression( "y = DirectCast(x, (A As Integer, B As Integer))", DkmEvaluationFlags.None, NoAliases, errorMessage, testData) Assert.Null(errorMessage) Dim typeInfo As ReadOnlyCollection(Of Byte) = Nothing Dim typeInfoId = result.GetCustomTypeInfo(typeInfo) Assert.Null(typeInfo) Dim methodData = testData.GetMethodData("<>x.<>m0") Dim method = methodData.Method CheckAttribute(result.Assembly, method, AttributeDescription.TupleElementNamesAttribute, expected:=False) methodData.VerifyIL( "{ // Code size 48 (0x30) .maxstack 4 .locals init (System.ValueTuple(Of Integer, Integer) V_0, //x System.Guid V_1) IL_0000: ldtoken ""Object"" IL_0005: call ""Function System.Type.GetTypeFromHandle(System.RuntimeTypeHandle) As System.Type"" IL_000a: ldstr ""y"" IL_000f: ldloca.s V_1 IL_0011: initobj ""System.Guid"" IL_0017: ldloc.1 IL_0018: ldnull IL_0019: call ""Sub Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.CreateVariable(System.Type, String, System.Guid, Byte())"" IL_001e: ldstr ""y"" IL_0023: call ""Function Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetVariableAddress(Of Object)(String) As Object"" IL_0028: ldloc.0 IL_0029: box ""System.ValueTuple(Of Integer, Integer)"" IL_002e: stind.ref IL_002f: ret }") End Sub) End Sub <WorkItem(13589, "https://github.com/dotnet/roslyn/issues/13589")> <Fact> Public Sub [Alias]() Const source = "Class C Shared F As (Integer, Integer) Shared Sub M() End Sub End Class" Dim comp = CreateCompilationWithMscorlib40({source}, references:={ValueTupleRef, SystemRuntimeFacadeRef}, options:=TestOptions.DebugDll) WithRuntimeInstance(comp, {MscorlibRef, ValueTupleRef, SystemRuntimeFacadeRef}, Sub(runtime) Dim context = CreateMethodContext(runtime, "C.M") Dim locals = ArrayBuilder(Of LocalAndMethod).GetInstance() Dim typeName As String = Nothing Dim aliasElementNames = New ReadOnlyCollection(Of String)({"A", "B", Nothing, "D"}) Dim [alias] = New [Alias]( DkmClrAliasKind.Variable, "t", "t", "System.ValueTuple`2[[System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089],[System.ValueTuple`2[[System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089],[System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], System.ValueTuple, Version=4.0.1.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51]][], System.ValueTuple, Version=4.0.1.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51", CustomTypeInfo.PayloadTypeId, CustomTypeInfo.Encode(Nothing, aliasElementNames)) Dim diagnostics = DiagnosticBag.GetInstance() Dim testData = New CompilationTestData() Dim assembly = context.CompileGetLocals( locals, argumentsOnly:=False, aliases:=ImmutableArray.Create([alias]), diagnostics:=diagnostics, typeName:=typeName, testData:=testData) diagnostics.Verify() diagnostics.Free() Assert.Equal(1, locals.Count) Dim typeInfo As ReadOnlyCollection(Of Byte) = Nothing Dim typeInfoId = locals(0).GetCustomTypeInfo(typeInfo) Dim dynamicFlags As ReadOnlyCollection(Of Byte) = Nothing Dim tupleElementNames As ReadOnlyCollection(Of String) = Nothing CustomTypeInfo.Decode(typeInfoId, typeInfo, dynamicFlags, tupleElementNames) Assert.Equal(aliasElementNames, tupleElementNames) Dim method = testData.Methods.Single().Value.Method CheckAttribute(assembly, method, AttributeDescription.TupleElementNamesAttribute, expected:=True) Dim returnType = DirectCast(method.ReturnType, TypeSymbol) Assert.False(returnType.IsTupleType) Assert.True(DirectCast(returnType, ArrayTypeSymbol).ElementType.IsTupleType) VerifyLocal(testData, typeName, locals(0), "<>m0", "t", expectedILOpt:= "{ // Code size 16 (0x10) .maxstack 1 IL_0000: ldstr ""t"" IL_0005: call ""Function Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetObjectByAlias(String) As Object"" IL_000a: castclass ""(A As Integer, B As (Integer, D As Integer))()"" IL_000f: ret }") locals.Free() End Sub) End Sub <WorkItem(13803, "https://github.com/dotnet/roslyn/issues/13803")> <Fact> Public Sub AliasElement_NoNames() Const source = "Class C Shared F As (Integer, Integer) Shared Sub M() End Sub End Class" Dim comp = CreateCompilationWithMscorlib40({source}, references:={SystemRuntimeFacadeRef, ValueTupleRef}, options:=TestOptions.DebugDll) WithRuntimeInstance(comp, {MscorlibRef, SystemCoreRef, SystemRuntimeFacadeRef, ValueTupleRef}, Sub(runtime) Dim context = CreateMethodContext(runtime, "C.M") Dim [alias] = New [Alias]( DkmClrAliasKind.Variable, "x", "x", "System.ValueTuple`8[" + "[System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]," + "[System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]," + "[System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]," + "[System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]," + "[System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]," + "[System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]," + "[System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]," + "[System.ValueTuple`2[" + "[System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]," + "[System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], " + "System.ValueTuple, Version=4.0.1.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51]], " + "System.ValueTuple, Version=4.0.1.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51", Guid.Empty, Nothing) Dim errorMessage As String = Nothing Dim testData = New CompilationTestData() context.CompileExpression( "x.Item4 + x.Item8", DkmEvaluationFlags.TreatAsExpression, ImmutableArray.Create([alias]), errorMessage, testData) Assert.Null(errorMessage) testData.GetMethodData("<>x.<>m0").VerifyIL( "{ // Code size 47 (0x2f) .maxstack 2 IL_0000: ldstr ""x"" IL_0005: call ""Function Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetObjectByAlias(String) As Object"" IL_000a: unbox.any ""System.ValueTuple(Of Integer, Integer, Integer, Integer, Integer, Integer, Integer, (Integer, Integer))"" IL_000f: ldfld ""System.ValueTuple(Of Integer, Integer, Integer, Integer, Integer, Integer, Integer, (Integer, Integer)).Item4 As Integer"" IL_0014: ldstr ""x"" IL_0019: call ""Function Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetObjectByAlias(String) As Object"" IL_001e: unbox.any ""System.ValueTuple(Of Integer, Integer, Integer, Integer, Integer, Integer, Integer, (Integer, Integer))"" IL_0023: ldfld ""System.ValueTuple(Of Integer, Integer, Integer, Integer, Integer, Integer, Integer, (Integer, Integer)).Rest As (Integer, Integer)"" IL_0028: ldfld ""System.ValueTuple(Of Integer, Integer).Item1 As Integer"" IL_002d: add.ovf IL_002e: ret }") End Sub) End Sub End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable Imports System.Collections.ObjectModel Imports System.IO Imports Microsoft.CodeAnalysis.CodeGen Imports Microsoft.CodeAnalysis.ExpressionEvaluator Imports Microsoft.CodeAnalysis.ExpressionEvaluator.UnitTests Imports Microsoft.CodeAnalysis.PooledObjects Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.UnitTests Imports Microsoft.VisualStudio.Debugger.Clr Imports Microsoft.VisualStudio.Debugger.Evaluation Imports Microsoft.VisualStudio.Debugger.Evaluation.ClrCompilation Imports Roslyn.Test.Utilities Imports Xunit Namespace Microsoft.CodeAnalysis.VisualBasic.ExpressionEvaluator.UnitTests Public Class TupleTests Inherits ExpressionCompilerTestBase <Fact> Public Sub Literal() Const source = "Class C Shared Sub M() Dim o As (Integer, Integer) End Sub End Class" Dim comp = CreateCompilationWithMscorlib40({source}, references:={ValueTupleRef, SystemRuntimeFacadeRef}, options:=TestOptions.DebugDll) WithRuntimeInstance(comp, {MscorlibRef, ValueTupleRef, SystemRuntimeFacadeRef}, Sub(runtime) Dim context = CreateMethodContext(runtime, "C.M") Dim errorMessage As String = Nothing Dim testData = New CompilationTestData() Dim result = context.CompileExpression( "(A:=1, B:=2)", DkmEvaluationFlags.TreatAsExpression, NoAliases, errorMessage, testData) Assert.Null(errorMessage) Dim typeInfo As ReadOnlyCollection(Of Byte) = Nothing Dim typeInfoId = result.GetCustomTypeInfo(typeInfo) Assert.NotNull(typeInfo) Dim dynamicFlags As ReadOnlyCollection(Of Byte) = Nothing Dim tupleElementNames As ReadOnlyCollection(Of String) = Nothing CustomTypeInfo.Decode(typeInfoId, typeInfo, dynamicFlags, tupleElementNames) Assert.Equal({"A", "B"}, tupleElementNames) Dim methodData = testData.GetMethodData("<>x.<>m0") Dim method = methodData.Method Assert.True(method.ReturnType.IsTupleType) CheckAttribute(result.Assembly, method, AttributeDescription.TupleElementNamesAttribute, expected:=True) methodData.VerifyIL( "{ // Code size 8 (0x8) .maxstack 2 .locals init (System.ValueTuple(Of Integer, Integer) V_0) //o IL_0000: ldc.i4.1 IL_0001: ldc.i4.2 IL_0002: newobj ""Sub System.ValueTuple(Of Integer, Integer)..ctor(Integer, Integer)"" IL_0007: ret }") End Sub) End Sub <Fact> Public Sub DuplicateValueTupleBetweenMscorlibAndLibrary() Const versionTemplate = "<Assembly: System.Reflection.AssemblyVersion(""{0}.0.0.0"")>" Const corlib_vb = " Namespace System Public Class [Object] End Class Public Structure Void End Structure Public Class ValueType End Class Public Structure IntPtr End Structure Public Structure Int32 End Structure Public Class [String] End Class Public Class Attribute End Class End Namespace Namespace System.Reflection Public Class AssemblyVersionAttribute Inherits Attribute Public Sub New(version As String) End Sub End Class End Namespace " Dim corlibWithoutVT = CreateEmptyCompilation({String.Format(versionTemplate, "1") + corlib_vb}, options:=TestOptions.DebugDll, assemblyName:="corlib") corlibWithoutVT.AssertTheseDiagnostics() Dim corlibWithoutVTRef = corlibWithoutVT.EmitToImageReference() Const valuetuple_vb As String = " Namespace System Public Structure ValueTuple(Of T1, T2) Public Dim Item1 As T1 Public Dim Item2 As T2 Public Sub New(item1 As T1, item2 As T2) End Sub End Structure End Namespace " Dim corlibWithVT = CreateEmptyCompilation({String.Format(versionTemplate, "2") + corlib_vb + valuetuple_vb}, options:=TestOptions.DebugDll, assemblyName:="corlib") corlibWithVT.AssertTheseDiagnostics() Const source As String = "Class C Shared Function M() As (Integer, Integer) Dim o = (1, 2) Return o End Function End Class" Dim app = CreateEmptyCompilation(source + valuetuple_vb, references:={corlibWithoutVTRef}, options:=TestOptions.DebugDll) app.AssertTheseDiagnostics() Dim runtime = CreateRuntimeInstance({app.ToModuleInstance(), corlibWithVT.ToModuleInstance()}) ' Create EE context with app assembly (including ValueTuple) and a more recent corlib (also including ValueTuple) Dim evalContext = CreateMethodContext(runtime, "C.M") Dim errorMessage As String = Nothing Dim testData = New CompilationTestData() Dim compileResult = evalContext.CompileExpression("(1, 2)", errorMessage, testData) Assert.Null(errorMessage) Using block As ModuleMetadata = ModuleMetadata.CreateFromStream(New MemoryStream(compileResult.Assembly)) Dim reader = block.MetadataReader Dim appRef = app.Assembly.Identity.Name AssertEx.SetEqual({"corlib 2.0", appRef + " 0.0"}, reader.DumpAssemblyReferences()) AssertEx.SetEqual({"Object, System, AssemblyReference:corlib", "ValueTuple`2, System, AssemblyReference:" + appRef}, ' ValueTuple comes from app, not corlib reader.DumpTypeReferences()) End Using End Sub <Fact> Public Sub TupleElementNamesAttribute_NotAvailable() Const source = "Namespace System Public Structure ValueTuple(Of T1, T2) Public Item1 As T1 Public Item2 As T2 Public Sub New(_1 As T1, _2 As T2) Item1 = _1 Item2 = _2 End Sub End Structure End Namespace Class C Shared Sub M() Dim o As (Integer, Integer) End Sub End Class" Dim comp = CreateCompilationWithMscorlib40({source}, options:=TestOptions.DebugDll) WithRuntimeInstance(comp, Sub(runtime) Dim context = CreateMethodContext(runtime, "C.M") Dim errorMessage As String = Nothing Dim testData = New CompilationTestData() Dim result = context.CompileExpression( "(A:=1, B:=2)", DkmEvaluationFlags.TreatAsExpression, NoAliases, errorMessage, testData) Assert.Null(errorMessage) Dim typeInfo As ReadOnlyCollection(Of Byte) = Nothing Dim typeInfoId = result.GetCustomTypeInfo(typeInfo) Assert.Null(typeInfo) Dim methodData = testData.GetMethodData("<>x.<>m0") Dim method = methodData.Method Assert.True(method.ReturnType.IsTupleType) CheckAttribute(result.Assembly, method, AttributeDescription.TupleElementNamesAttribute, expected:=False) methodData.VerifyIL( "{ // Code size 8 (0x8) .maxstack 2 .locals init (System.ValueTuple(Of Integer, Integer) V_0) //o IL_0000: ldc.i4.1 IL_0001: ldc.i4.2 IL_0002: newobj ""Sub System.ValueTuple(Of Integer, Integer)..ctor(Integer, Integer)"" IL_0007: ret }") End Sub) End Sub <WorkItem(13948, "https://github.com/dotnet/roslyn/issues/13948")> <Fact> Public Sub Local() Const source = "class C { static void M() { (int A, int B) o = (1, 2); } }" Dim comp = CreateCSharpCompilation(source, referencedAssemblies:={MscorlibRef, ValueTupleRef, SystemRuntimeFacadeRef}) WithRuntimeInstance(comp, {MscorlibRef, ValueTupleRef, SystemRuntimeFacadeRef}, Sub(runtime) Dim context = CreateMethodContext(runtime, "C.M") Dim testData = New CompilationTestData() Dim locals = ArrayBuilder(Of LocalAndMethod).GetInstance() Dim typeName As String = Nothing Dim assembly = context.CompileGetLocals(locals, argumentsOnly:=False, typeName:=typeName, testData:=testData) Assert.Equal(1, locals.Count) Dim typeInfo As ReadOnlyCollection(Of Byte) = Nothing Dim typeInfoId = locals(0).GetCustomTypeInfo(typeInfo) Dim dynamicFlags As ReadOnlyCollection(Of Byte) = Nothing Dim tupleElementNames As ReadOnlyCollection(Of String) = Nothing CustomTypeInfo.Decode(typeInfoId, typeInfo, dynamicFlags, tupleElementNames) Assert.Equal({"A", "B"}, tupleElementNames) Dim method = testData.Methods.Single().Value.Method CheckAttribute(assembly, method, AttributeDescription.TupleElementNamesAttribute, expected:=True) Assert.True(method.ReturnType.IsTupleType) VerifyLocal(testData, typeName, locals(0), "<>m0", "o", expectedILOpt:= "{ // Code size 2 (0x2) .maxstack 1 .locals init (System.ValueTuple(Of Integer, Integer) V_0) //o IL_0000: ldloc.0 IL_0001: ret }") locals.Free() End Sub) End Sub <WorkItem(13948, "https://github.com/dotnet/roslyn/issues/13948")> <Fact> Public Sub Constant() Const source = "class A<T> { internal class B<U> { } } class C { static (object, object) F; static void M() { const A<(int, int A)>.B<(object B, object)>[] c = null; } }" Dim comp = CreateCSharpCompilation(source, referencedAssemblies:={MscorlibRef, ValueTupleRef, SystemRuntimeFacadeRef}) WithRuntimeInstance(comp, {MscorlibRef, ValueTupleRef, SystemRuntimeFacadeRef}, Sub(runtime) Dim context = CreateMethodContext(runtime, "C.M") Dim testData = New CompilationTestData() Dim locals = ArrayBuilder(Of LocalAndMethod).GetInstance() Dim typeName As String = Nothing Dim assembly = context.CompileGetLocals(locals, argumentsOnly:=False, typeName:=typeName, testData:=testData) Assert.Equal(1, locals.Count) Dim typeInfo As ReadOnlyCollection(Of Byte) = Nothing Dim typeInfoId = locals(0).GetCustomTypeInfo(typeInfo) Dim dynamicFlags As ReadOnlyCollection(Of Byte) = Nothing Dim tupleElementNames As ReadOnlyCollection(Of String) = Nothing CustomTypeInfo.Decode(typeInfoId, typeInfo, dynamicFlags, tupleElementNames) Assert.Equal({Nothing, "A", "B", Nothing}, tupleElementNames) Dim method = DirectCast(testData.Methods.Single().Value.Method, MethodSymbol) CheckAttribute(assembly, method, AttributeDescription.TupleElementNamesAttribute, expected:=True) Dim returnType = method.ReturnType Assert.False(returnType.IsTupleType) Assert.True(returnType.ContainsTuple()) VerifyLocal(testData, typeName, locals(0), "<>m0", "c", expectedFlags:=DkmClrCompilationResultFlags.ReadOnlyResult, expectedILOpt:= "{ // Code size 2 (0x2) .maxstack 1 IL_0000: ldnull IL_0001: ret }") locals.Free() End Sub) End Sub <WorkItem(13803, "https://github.com/dotnet/roslyn/issues/13803")> <Fact> Public Sub LongTupleLocalElement_NoNames() Const source = "Class C Shared Sub M() Dim x = (1, 2, 3, 4, 5, 6, 7, 8) End Sub End Class" Dim comp = CreateCompilationWithMscorlib40({source}, references:={SystemRuntimeFacadeRef, ValueTupleRef}, options:=TestOptions.DebugDll) WithRuntimeInstance(comp, {MscorlibRef, SystemCoreRef, SystemRuntimeFacadeRef, ValueTupleRef}, Sub(runtime) Dim context = CreateMethodContext(runtime, "C.M") Dim errorMessage As String = Nothing Dim testData = New CompilationTestData() context.CompileExpression( "x.Item4 + x.Item8", DkmEvaluationFlags.TreatAsExpression, NoAliases, errorMessage, testData) testData.GetMethodData("<>x.<>m0").VerifyIL( "{ // Code size 19 (0x13) .maxstack 2 .locals init (System.ValueTuple(Of Integer, Integer, Integer, Integer, Integer, Integer, Integer, ValueTuple(Of Integer)) V_0) //x IL_0000: ldloc.0 IL_0001: ldfld ""System.ValueTuple(Of Integer, Integer, Integer, Integer, Integer, Integer, Integer, ValueTuple(Of Integer)).Item4 As Integer"" IL_0006: ldloc.0 IL_0007: ldfld ""System.ValueTuple(Of Integer, Integer, Integer, Integer, Integer, Integer, Integer, ValueTuple(Of Integer)).Rest As ValueTuple(Of Integer)"" IL_000c: ldfld ""System.ValueTuple(Of Integer).Item1 As Integer"" IL_0011: add.ovf IL_0012: ret }") End Sub) End Sub <Fact> Public Sub LongTupleLocalElement_Names() Const source = "Class C Shared Sub M() Dim x = (1, 2, Three:=3, Four:=4, 5, 6, 7, Eight:=8) End Sub End Class" Dim comp = CreateCompilationWithMscorlib40({source}, references:={SystemRuntimeFacadeRef, ValueTupleRef}, options:=TestOptions.DebugDll) WithRuntimeInstance(comp, {MscorlibRef, SystemCoreRef, SystemRuntimeFacadeRef, ValueTupleRef}, Sub(runtime) Dim context = CreateMethodContext(runtime, "C.M") Dim errorMessage As String = Nothing Dim testData = New CompilationTestData() context.CompileExpression( "x.Item8 + x.Eight", DkmEvaluationFlags.TreatAsExpression, NoAliases, errorMessage, testData) testData.GetMethodData("<>x.<>m0").VerifyIL( "{ // Code size 24 (0x18) .maxstack 2 .locals init (System.ValueTuple(Of Integer, Integer, Integer, Integer, Integer, Integer, Integer, ValueTuple(Of Integer)) V_0) //x IL_0000: ldloc.0 IL_0001: ldfld ""System.ValueTuple(Of Integer, Integer, Integer, Integer, Integer, Integer, Integer, ValueTuple(Of Integer)).Rest As ValueTuple(Of Integer)"" IL_0006: ldfld ""System.ValueTuple(Of Integer).Item1 As Integer"" IL_000b: ldloc.0 IL_000c: ldfld ""System.ValueTuple(Of Integer, Integer, Integer, Integer, Integer, Integer, Integer, ValueTuple(Of Integer)).Rest As ValueTuple(Of Integer)"" IL_0011: ldfld ""System.ValueTuple(Of Integer).Item1 As Integer"" IL_0016: add.ovf IL_0017: ret }") End Sub) End Sub ''' <summary> ''' Locals declared in the VB EE do not have an explicit ''' type and are statically typed to Object, so tuple ''' element names on the value are not preserved. ''' </summary> <Fact> Public Sub DeclareLocal() Const source = "Class C Shared Sub M() Dim x = (1, 2) End Sub End Class" Dim comp = CreateCompilationWithMscorlib40({source}, references:={ValueTupleRef, SystemRuntimeFacadeRef}, options:=TestOptions.DebugDll) WithRuntimeInstance(comp, references:={MscorlibRef, ValueTupleRef, SystemRuntimeFacadeRef}, validator:=Sub(runtime) Dim context = CreateMethodContext(runtime, "C.M") Dim errorMessage As String = Nothing Dim testData = New CompilationTestData() Dim result = context.CompileExpression( "y = DirectCast(x, (A As Integer, B As Integer))", DkmEvaluationFlags.None, NoAliases, errorMessage, testData) Assert.Null(errorMessage) Dim typeInfo As ReadOnlyCollection(Of Byte) = Nothing Dim typeInfoId = result.GetCustomTypeInfo(typeInfo) Assert.Null(typeInfo) Dim methodData = testData.GetMethodData("<>x.<>m0") Dim method = methodData.Method CheckAttribute(result.Assembly, method, AttributeDescription.TupleElementNamesAttribute, expected:=False) methodData.VerifyIL( "{ // Code size 48 (0x30) .maxstack 4 .locals init (System.ValueTuple(Of Integer, Integer) V_0, //x System.Guid V_1) IL_0000: ldtoken ""Object"" IL_0005: call ""Function System.Type.GetTypeFromHandle(System.RuntimeTypeHandle) As System.Type"" IL_000a: ldstr ""y"" IL_000f: ldloca.s V_1 IL_0011: initobj ""System.Guid"" IL_0017: ldloc.1 IL_0018: ldnull IL_0019: call ""Sub Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.CreateVariable(System.Type, String, System.Guid, Byte())"" IL_001e: ldstr ""y"" IL_0023: call ""Function Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetVariableAddress(Of Object)(String) As Object"" IL_0028: ldloc.0 IL_0029: box ""System.ValueTuple(Of Integer, Integer)"" IL_002e: stind.ref IL_002f: ret }") End Sub) End Sub <WorkItem(13589, "https://github.com/dotnet/roslyn/issues/13589")> <Fact> Public Sub [Alias]() Const source = "Class C Shared F As (Integer, Integer) Shared Sub M() End Sub End Class" Dim comp = CreateCompilationWithMscorlib40({source}, references:={ValueTupleRef, SystemRuntimeFacadeRef}, options:=TestOptions.DebugDll) WithRuntimeInstance(comp, {MscorlibRef, ValueTupleRef, SystemRuntimeFacadeRef}, Sub(runtime) Dim context = CreateMethodContext(runtime, "C.M") Dim locals = ArrayBuilder(Of LocalAndMethod).GetInstance() Dim typeName As String = Nothing Dim aliasElementNames = New ReadOnlyCollection(Of String)({"A", "B", Nothing, "D"}) Dim [alias] = New [Alias]( DkmClrAliasKind.Variable, "t", "t", "System.ValueTuple`2[[System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089],[System.ValueTuple`2[[System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089],[System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], System.ValueTuple, Version=4.0.1.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51]][], System.ValueTuple, Version=4.0.1.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51", CustomTypeInfo.PayloadTypeId, CustomTypeInfo.Encode(Nothing, aliasElementNames)) Dim diagnostics = DiagnosticBag.GetInstance() Dim testData = New CompilationTestData() Dim assembly = context.CompileGetLocals( locals, argumentsOnly:=False, aliases:=ImmutableArray.Create([alias]), diagnostics:=diagnostics, typeName:=typeName, testData:=testData) diagnostics.Verify() diagnostics.Free() Assert.Equal(1, locals.Count) Dim typeInfo As ReadOnlyCollection(Of Byte) = Nothing Dim typeInfoId = locals(0).GetCustomTypeInfo(typeInfo) Dim dynamicFlags As ReadOnlyCollection(Of Byte) = Nothing Dim tupleElementNames As ReadOnlyCollection(Of String) = Nothing CustomTypeInfo.Decode(typeInfoId, typeInfo, dynamicFlags, tupleElementNames) Assert.Equal(aliasElementNames, tupleElementNames) Dim method = testData.Methods.Single().Value.Method CheckAttribute(assembly, method, AttributeDescription.TupleElementNamesAttribute, expected:=True) Dim returnType = DirectCast(method.ReturnType, TypeSymbol) Assert.False(returnType.IsTupleType) Assert.True(DirectCast(returnType, ArrayTypeSymbol).ElementType.IsTupleType) VerifyLocal(testData, typeName, locals(0), "<>m0", "t", expectedILOpt:= "{ // Code size 16 (0x10) .maxstack 1 IL_0000: ldstr ""t"" IL_0005: call ""Function Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetObjectByAlias(String) As Object"" IL_000a: castclass ""(A As Integer, B As (Integer, D As Integer))()"" IL_000f: ret }") locals.Free() End Sub) End Sub <WorkItem(13803, "https://github.com/dotnet/roslyn/issues/13803")> <Fact> Public Sub AliasElement_NoNames() Const source = "Class C Shared F As (Integer, Integer) Shared Sub M() End Sub End Class" Dim comp = CreateCompilationWithMscorlib40({source}, references:={SystemRuntimeFacadeRef, ValueTupleRef}, options:=TestOptions.DebugDll) WithRuntimeInstance(comp, {MscorlibRef, SystemCoreRef, SystemRuntimeFacadeRef, ValueTupleRef}, Sub(runtime) Dim context = CreateMethodContext(runtime, "C.M") Dim [alias] = New [Alias]( DkmClrAliasKind.Variable, "x", "x", "System.ValueTuple`8[" + "[System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]," + "[System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]," + "[System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]," + "[System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]," + "[System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]," + "[System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]," + "[System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]," + "[System.ValueTuple`2[" + "[System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]," + "[System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], " + "System.ValueTuple, Version=4.0.1.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51]], " + "System.ValueTuple, Version=4.0.1.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51", Guid.Empty, Nothing) Dim errorMessage As String = Nothing Dim testData = New CompilationTestData() context.CompileExpression( "x.Item4 + x.Item8", DkmEvaluationFlags.TreatAsExpression, ImmutableArray.Create([alias]), errorMessage, testData) Assert.Null(errorMessage) testData.GetMethodData("<>x.<>m0").VerifyIL( "{ // Code size 47 (0x2f) .maxstack 2 IL_0000: ldstr ""x"" IL_0005: call ""Function Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetObjectByAlias(String) As Object"" IL_000a: unbox.any ""System.ValueTuple(Of Integer, Integer, Integer, Integer, Integer, Integer, Integer, (Integer, Integer))"" IL_000f: ldfld ""System.ValueTuple(Of Integer, Integer, Integer, Integer, Integer, Integer, Integer, (Integer, Integer)).Item4 As Integer"" IL_0014: ldstr ""x"" IL_0019: call ""Function Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetObjectByAlias(String) As Object"" IL_001e: unbox.any ""System.ValueTuple(Of Integer, Integer, Integer, Integer, Integer, Integer, Integer, (Integer, Integer))"" IL_0023: ldfld ""System.ValueTuple(Of Integer, Integer, Integer, Integer, Integer, Integer, Integer, (Integer, Integer)).Rest As (Integer, Integer)"" IL_0028: ldfld ""System.ValueTuple(Of Integer, Integer).Item1 As Integer"" IL_002d: add.ovf IL_002e: ret }") End Sub) End Sub End Class End Namespace
-1
dotnet/roslyn
55,430
Fix LSP semantic tokens algorithm
This PR primarily accomplishes two tasks: 1) Overhauls the existing LSP semantic tokens edits processing algorithm to align with [Razor's](https://github.com/dotnet/aspnetcore-tooling/blob/main/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/Semantic/Services/SemanticTokensEditsDiffer.cs) (shoutout to Ryan and the rest of the Razor team for writing the original 😄). The main change here is going from calculating edits per token (i.e. five ints) to per int. The updated algorithm is much more efficient than our previous algorithm, and returns less edits back to the LSP client. 2) The interpretation of Roslyn's LongestCommonSubstring algorithm, which we use to calculate raw edits, was missing a critical piece. Namely, for insertions, we need to keep track of _where_ we should be inserting into the original token set. We don't keep track of this in the existing implementation, resulting in bugs such as #54671. Resolves #54671
allisonchou
2021-08-05T06:06:43Z
2021-08-06T23:44:44Z
b9200d03a76c74d404040d44b9bbe12b1d0a8ef2
f300a818940ea1acef66c946cfa83756729d5e59
Fix LSP semantic tokens algorithm. This PR primarily accomplishes two tasks: 1) Overhauls the existing LSP semantic tokens edits processing algorithm to align with [Razor's](https://github.com/dotnet/aspnetcore-tooling/blob/main/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/Semantic/Services/SemanticTokensEditsDiffer.cs) (shoutout to Ryan and the rest of the Razor team for writing the original 😄). The main change here is going from calculating edits per token (i.e. five ints) to per int. The updated algorithm is much more efficient than our previous algorithm, and returns less edits back to the LSP client. 2) The interpretation of Roslyn's LongestCommonSubstring algorithm, which we use to calculate raw edits, was missing a critical piece. Namely, for insertions, we need to keep track of _where_ we should be inserting into the original token set. We don't keep track of this in the existing implementation, resulting in bugs such as #54671. Resolves #54671
./src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/Utilities/TextReaderWithLength.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.IO; namespace Microsoft.CodeAnalysis.Shared.Utilities { internal abstract class TextReaderWithLength : TextReader { public TextReaderWithLength(int length) => Length = length; public int Length { get; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.IO; namespace Microsoft.CodeAnalysis.Shared.Utilities { internal abstract class TextReaderWithLength : TextReader { public TextReaderWithLength(int length) => Length = length; public int Length { get; } } }
-1
dotnet/roslyn
55,430
Fix LSP semantic tokens algorithm
This PR primarily accomplishes two tasks: 1) Overhauls the existing LSP semantic tokens edits processing algorithm to align with [Razor's](https://github.com/dotnet/aspnetcore-tooling/blob/main/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/Semantic/Services/SemanticTokensEditsDiffer.cs) (shoutout to Ryan and the rest of the Razor team for writing the original 😄). The main change here is going from calculating edits per token (i.e. five ints) to per int. The updated algorithm is much more efficient than our previous algorithm, and returns less edits back to the LSP client. 2) The interpretation of Roslyn's LongestCommonSubstring algorithm, which we use to calculate raw edits, was missing a critical piece. Namely, for insertions, we need to keep track of _where_ we should be inserting into the original token set. We don't keep track of this in the existing implementation, resulting in bugs such as #54671. Resolves #54671
allisonchou
2021-08-05T06:06:43Z
2021-08-06T23:44:44Z
b9200d03a76c74d404040d44b9bbe12b1d0a8ef2
f300a818940ea1acef66c946cfa83756729d5e59
Fix LSP semantic tokens algorithm. This PR primarily accomplishes two tasks: 1) Overhauls the existing LSP semantic tokens edits processing algorithm to align with [Razor's](https://github.com/dotnet/aspnetcore-tooling/blob/main/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/Semantic/Services/SemanticTokensEditsDiffer.cs) (shoutout to Ryan and the rest of the Razor team for writing the original 😄). The main change here is going from calculating edits per token (i.e. five ints) to per int. The updated algorithm is much more efficient than our previous algorithm, and returns less edits back to the LSP client. 2) The interpretation of Roslyn's LongestCommonSubstring algorithm, which we use to calculate raw edits, was missing a critical piece. Namely, for insertions, we need to keep track of _where_ we should be inserting into the original token set. We don't keep track of this in the existing implementation, resulting in bugs such as #54671. Resolves #54671
./src/VisualStudio/CSharp/Impl/Options/Formatting/FormattingNewLinesPage.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Runtime.InteropServices; using Microsoft.VisualStudio.LanguageServices.Implementation.Options; namespace Microsoft.VisualStudio.LanguageServices.CSharp.Options.Formatting { [Guid(Guids.CSharpOptionPageFormattingNewLinesIdString)] internal class FormattingNewLinesPage : AbstractOptionPage { public FormattingNewLinesPage() { } protected override AbstractOptionPageControl CreateOptionPage(IServiceProvider serviceProvider, OptionStore optionStore) => new OptionPreviewControl(serviceProvider, optionStore, (o, s) => new NewLinesViewModel(o, s)); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Runtime.InteropServices; using Microsoft.VisualStudio.LanguageServices.Implementation.Options; namespace Microsoft.VisualStudio.LanguageServices.CSharp.Options.Formatting { [Guid(Guids.CSharpOptionPageFormattingNewLinesIdString)] internal class FormattingNewLinesPage : AbstractOptionPage { public FormattingNewLinesPage() { } protected override AbstractOptionPageControl CreateOptionPage(IServiceProvider serviceProvider, OptionStore optionStore) => new OptionPreviewControl(serviceProvider, optionStore, (o, s) => new NewLinesViewModel(o, s)); } }
-1
dotnet/roslyn
55,430
Fix LSP semantic tokens algorithm
This PR primarily accomplishes two tasks: 1) Overhauls the existing LSP semantic tokens edits processing algorithm to align with [Razor's](https://github.com/dotnet/aspnetcore-tooling/blob/main/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/Semantic/Services/SemanticTokensEditsDiffer.cs) (shoutout to Ryan and the rest of the Razor team for writing the original 😄). The main change here is going from calculating edits per token (i.e. five ints) to per int. The updated algorithm is much more efficient than our previous algorithm, and returns less edits back to the LSP client. 2) The interpretation of Roslyn's LongestCommonSubstring algorithm, which we use to calculate raw edits, was missing a critical piece. Namely, for insertions, we need to keep track of _where_ we should be inserting into the original token set. We don't keep track of this in the existing implementation, resulting in bugs such as #54671. Resolves #54671
allisonchou
2021-08-05T06:06:43Z
2021-08-06T23:44:44Z
b9200d03a76c74d404040d44b9bbe12b1d0a8ef2
f300a818940ea1acef66c946cfa83756729d5e59
Fix LSP semantic tokens algorithm. This PR primarily accomplishes two tasks: 1) Overhauls the existing LSP semantic tokens edits processing algorithm to align with [Razor's](https://github.com/dotnet/aspnetcore-tooling/blob/main/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/Semantic/Services/SemanticTokensEditsDiffer.cs) (shoutout to Ryan and the rest of the Razor team for writing the original 😄). The main change here is going from calculating edits per token (i.e. five ints) to per int. The updated algorithm is much more efficient than our previous algorithm, and returns less edits back to the LSP client. 2) The interpretation of Roslyn's LongestCommonSubstring algorithm, which we use to calculate raw edits, was missing a critical piece. Namely, for insertions, we need to keep track of _where_ we should be inserting into the original token set. We don't keep track of this in the existing implementation, resulting in bugs such as #54671. Resolves #54671
./src/EditorFeatures/Test2/IntelliSense/CSharpCompletionCommandHandlerTests_InternalsVisibleTo.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces Namespace Microsoft.CodeAnalysis.Editor.UnitTests.IntelliSense <[UseExportProvider]> Public Class CSharpCompletionCommandHandlerTests_InternalsVisibleTo <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function CodeCompletionContainsOtherAssembliesOfSolution(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateTestStateFromWorkspace( <Workspace> <Project Language="C#" CommonReferences="true" AssemblyName="ClassLibrary1"/> <Project Language="C#" CommonReferences="true" AssemblyName="ClassLibrary2"/> <Project Language="C#" CommonReferences="true" AssemblyName="ClassLibrary3"/> <Project Language="C#" CommonReferences="true" AssemblyName="TestAssembly"> <Document FilePath="C.cs"> [assembly: System.Runtime.CompilerServices.InternalsVisibleTo("$$ </Document> </Project> </Workspace>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendInvokeCompletionList() Await state.AssertCompletionItemsContainAll("ClassLibrary1", "ClassLibrary2", "ClassLibrary3") End Using End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function CodeCompletionContainsOtherAssemblyIfAttributeSuffixIsPresent(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateTestStateFromWorkspace( <Workspace> <Project Language="C#" CommonReferences="true" AssemblyName="ClassLibrary1"/> <Project Language="C#" CommonReferences="true" AssemblyName="TestAssembly"> <Document FilePath="C.cs"> [assembly: System.Runtime.CompilerServices.InternalsVisibleToAttribute("$$ </Document> </Project> </Workspace>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendInvokeCompletionList() Await state.AssertCompletionItemsContainAll("ClassLibrary1") End Using End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function CodeCompletionIsTriggeredWhenDoubleQuoteIsEntered(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateTestStateFromWorkspace( <Workspace> <Project Language="C#" CommonReferences="true" AssemblyName="ClassLibrary1"/> <Project Language="C#" CommonReferences="true" AssemblyName="TestAssembly"> <Document FilePath="C.cs"> [assembly: System.Runtime.CompilerServices.InternalsVisibleTo($$ </Document> </Project> </Workspace>, showCompletionInArgumentLists:=showCompletionInArgumentLists) Await state.AssertNoCompletionSession() state.SendTypeChars(""""c) Await state.AssertCompletionItemsContainAll("ClassLibrary1") End Using End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function CodeCompletionIsEmptyUntilDoubleQuotesAreEntered(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateTestStateFromWorkspace( <Workspace> <Project Language="C#" CommonReferences="true" AssemblyName="ClassLibrary1"/> <Project Language="C#" CommonReferences="true" AssemblyName="TestAssembly"> <Document FilePath="C.cs"> [assembly: System.Runtime.CompilerServices.InternalsVisibleTo$$ </Document> </Project> </Workspace>, showCompletionInArgumentLists:=showCompletionInArgumentLists) Await state.AssertNoCompletionSession() state.SendInvokeCompletionList() Await state.AssertCompletionItemsDoNotContainAny("ClassLibrary1") state.SendTypeChars("("c) If Not showCompletionInArgumentLists Then Await state.AssertNoCompletionSession() state.SendInvokeCompletionList() End If Await state.AssertCompletionItemsDoNotContainAny("ClassLibrary1") state.SendTypeChars(""""c) Await state.AssertCompletionItemsContainAll("ClassLibrary1") End Using End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function CodeCompletionIsTriggeredWhenCharacterIsEnteredAfterOpeningDoubleQuote(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateTestStateFromWorkspace( <Workspace> <Project Language="C#" CommonReferences="true" AssemblyName="ClassLibrary1"/> <Project Language="C#" CommonReferences="true" AssemblyName="TestAssembly"> <Document FilePath="C.cs"> [assembly: System.Runtime.CompilerServices.InternalsVisibleTo("$$")] </Document> </Project> </Workspace>, showCompletionInArgumentLists:=showCompletionInArgumentLists) Await state.AssertNoCompletionSession() state.SendTypeChars("a"c) Await state.AssertCompletionItemsContainAll("ClassLibrary1") End Using End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function CodeCompletionIsNotTriggeredWhenCharacterIsEnteredThatIsNotRightBesideTheOpeniningDoubleQuote(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateTestStateFromWorkspace( <Workspace> <Project Language="C#" CommonReferences="true" AssemblyName="ClassLibrary1"/> <Project Language="C#" CommonReferences="true" AssemblyName="TestAssembly"> <Document FilePath="C.cs"> [assembly: System.Runtime.CompilerServices.InternalsVisibleTo("a$$")] </Document> </Project> </Workspace>, showCompletionInArgumentLists:=showCompletionInArgumentLists) Await state.AssertNoCompletionSession() state.SendTypeChars("b"c) Await state.AssertNoCompletionSession() End Using End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function CodeCompletionIsNotTriggeredWhenDoubleQuoteIsEnteredAtStartOfFile(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateTestStateFromWorkspace( <Workspace> <Project Language="C#" CommonReferences="true" AssemblyName="ClassLibrary1"/> <Project Language="C#" CommonReferences="true" AssemblyName="TestAssembly"> <Document FilePath="C.cs">$$ </Document> </Project> </Workspace>, showCompletionInArgumentLists:=showCompletionInArgumentLists) Await state.AssertNoCompletionSession() state.SendTypeChars("a"c) Await state.AssertCompletionItemsDoNotContainAny("ClassLibrary1") End Using End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function CodeCompletionIsNotTriggeredByArrayElementAccess(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateTestStateFromWorkspace( <Workspace> <Project Language="C#" CommonReferences="true" AssemblyName="ClassLibrary1"/> <Project Language="C#" CommonReferences="true" AssemblyName="TestAssembly"> <Document FilePath="C.cs"><![CDATA[ namespace A { public class C { public void M() { var d = new System.Collections.Generic.Dictionary<string, string>(); var v = d$$; } } } ]]> </Document> </Project> </Workspace>, showCompletionInArgumentLists:=showCompletionInArgumentLists) Dim AssertNoCompletionAndCompletionDoesNotContainClassLibrary1 As Func(Of Task) = Async Function() Await state.AssertNoCompletionSession() state.SendInvokeCompletionList() Await state.AssertSessionIsNothingOrNoCompletionItemLike("ClassLibrary1") End Function Await AssertNoCompletionAndCompletionDoesNotContainClassLibrary1() state.SendTypeChars("["c) If Not showCompletionInArgumentLists Then Await AssertNoCompletionAndCompletionDoesNotContainClassLibrary1() Else Await state.AssertCompletionSession() Await state.AssertSessionIsNothingOrNoCompletionItemLike("ClassLibrary1") End If state.SendTypeChars(""""c) Await AssertNoCompletionAndCompletionDoesNotContainClassLibrary1() End Using End Function Private Shared Async Function AssertCompletionListHasItems(code As String, hasItems As Boolean, showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateTestStateFromWorkspace( <Workspace> <Project Language="C#" CommonReferences="true" AssemblyName="ClassLibrary1"/> <Project Language="C#" CommonReferences="true" AssemblyName="TestAssembly"> <Document FilePath="C.cs"> using System.Runtime.CompilerServices; using System.Reflection; <%= code %> </Document> </Project> </Workspace>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendInvokeCompletionList() If hasItems Then Await state.AssertCompletionItemsContainAll("ClassLibrary1") Else Await state.AssertNoCompletionSession End If End Using End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function AssertCompletionListHasItems_AfterSingleDoubleQuoteAndClosing(showCompletionInArgumentLists As Boolean) As Task Await AssertCompletionListHasItems("[assembly: InternalsVisibleTo(""$$)]", True, showCompletionInArgumentLists) End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function AssertCompletionListHasItems_AfterText(showCompletionInArgumentLists As Boolean) As Task Await AssertCompletionListHasItems("[assembly: InternalsVisibleTo(""Test$$)]", True, showCompletionInArgumentLists) End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function AssertCompletionListHasItems_IfCursorIsInSecondParameter(showCompletionInArgumentLists As Boolean) As Task Await AssertCompletionListHasItems("[assembly: InternalsVisibleTo(""Test"", ""$$", True, showCompletionInArgumentLists) End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function AssertCompletionListHasNoItems_IfCursorIsClosingDoubleQuote1(showCompletionInArgumentLists As Boolean) As Task Await AssertCompletionListHasItems("[assembly: InternalsVisibleTo(""Test""$$", False, showCompletionInArgumentLists) End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function AssertCompletionListHasNoItems_IfCursorIsClosingDoubleQuote2(showCompletionInArgumentLists As Boolean) As Task Await AssertCompletionListHasItems("[assembly: InternalsVisibleTo(""""$$", False, showCompletionInArgumentLists) End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function AssertCompletionListHasItems_IfNamedParameterIsPresent(showCompletionInArgumentLists As Boolean) As Task Await AssertCompletionListHasItems("[assembly: InternalsVisibleTo(""$$, AllInternalsVisible = true)]", True, showCompletionInArgumentLists) End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function AssertCompletionListHasItems_IfNamedParameterAndNamedPositionalParametersArePresent(showCompletionInArgumentLists As Boolean) As Task Await AssertCompletionListHasItems("[assembly: InternalsVisibleTo(assemblyName: ""$$, AllInternalsVisible = true)]", True, showCompletionInArgumentLists) End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function AssertCompletionListHasNoItems_IfNumberIsEntered(showCompletionInArgumentLists As Boolean) As Task Await AssertCompletionListHasItems("[assembly: InternalsVisibleTo(1$$2)]", False, showCompletionInArgumentLists) End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function AssertCompletionListHasNoItems_IfNotInternalsVisibleToAttribute(showCompletionInArgumentLists As Boolean) As Task Await AssertCompletionListHasItems("[assembly: AssemblyVersion(""$$"")]", False, showCompletionInArgumentLists) End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function AssertCompletionListHasItems_IfOtherAttributeIsPresent1(showCompletionInArgumentLists As Boolean) As Task Await AssertCompletionListHasItems("[assembly: AssemblyVersion(""1.0.0.0""), InternalsVisibleTo(""$$", True, showCompletionInArgumentLists) End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function AssertCompletionListHasItems_IfOtherAttributeIsPresent2(showCompletionInArgumentLists As Boolean) As Task Await AssertCompletionListHasItems("[assembly: InternalsVisibleTo(""$$""), AssemblyVersion(""1.0.0.0"")]", True, showCompletionInArgumentLists) End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function AssertCompletionListHasItems_IfOtherAttributesAreAhead(showCompletionInArgumentLists As Boolean) As Task Await AssertCompletionListHasItems(" [assembly: AssemblyVersion(""1.0.0.0"")] [assembly: InternalsVisibleTo(""$$", True, showCompletionInArgumentLists) End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function AssertCompletionListHasItems_IfOtherAttributesAreFollowing(showCompletionInArgumentLists As Boolean) As Task Await AssertCompletionListHasItems(" [assembly: InternalsVisibleTo(""$$ [assembly: AssemblyVersion(""1.0.0.0"")] [assembly: AssemblyCompany(""Test"")]", True, showCompletionInArgumentLists) End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function AssertCompletionListHasItems_IfNamespaceIsFollowing(showCompletionInArgumentLists As Boolean) As Task Await AssertCompletionListHasItems(" [assembly: InternalsVisibleTo(""$$ namespace A { public class A { } }", True, showCompletionInArgumentLists) End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function CodeCompletionHasItemsIfInteralVisibleToIsReferencedByTypeAlias(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateTestStateFromWorkspace( <Workspace> <Project Language="C#" CommonReferences="true" AssemblyName="ClassLibrary1"/> <Project Language="C#" CommonReferences="true" AssemblyName="TestAssembly"> <Document FilePath="C.cs"> using IVT = System.Runtime.CompilerServices.InternalsVisibleToAttribute; [assembly: IVT("$$ </Document> </Project> </Workspace>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendInvokeCompletionList() Await state.AssertCompletionItemsContainAll("ClassLibrary1") End Using End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function CodeCompletionDoesNotContainCurrentAssembly(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateTestStateFromWorkspace( <Workspace> <Project Language="C#" CommonReferences="true" AssemblyName="ClassLibrary1"/> <Project Language="C#" CommonReferences="true" AssemblyName="TestAssembly"> <Document FilePath="C.cs"> [assembly: System.Runtime.CompilerServices.InternalsVisibleTo("$$")] </Document> </Project> </Workspace>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendInvokeCompletionList() Await state.AssertCompletionItemsDoNotContainAny("TestAssembly") End Using End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function CodeCompletionInsertsAssemblyNameOnCommit(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateTestStateFromWorkspace( <Workspace> <Project Language="C#" CommonReferences="true" AssemblyName="ClassLibrary1"> </Project> <Project Language="C#" CommonReferences="true" AssemblyName="TestAssembly"> <Document> [assembly: System.Runtime.CompilerServices.InternalsVisibleTo("$$")] </Document> </Project> </Workspace>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendInvokeCompletionList() Await state.AssertSelectedCompletionItem("ClassLibrary1") state.SendTab() state.AssertMatchesTextStartingAtLine(1, "[assembly: System.Runtime.CompilerServices.InternalsVisibleTo(""ClassLibrary1"")]") End Using End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function CodeCompletionInsertsPublicKeyOnCommit(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateTestStateFromWorkspace( <Workspace> <Project Language="C#" CommonReferences="true" AssemblyName="ClassLibrary1"> <CompilationOptions CryptoKeyFile=<%= SigningTestHelpers.PublicKeyFile %> StrongNameProvider=<%= SigningTestHelpers.DefaultDesktopStrongNameProvider.GetType().AssemblyQualifiedName %>/> </Project> <Project Language="C#" CommonReferences="true" AssemblyName="TestAssembly"> <Document> [assembly: System.Runtime.CompilerServices.InternalsVisibleTo("$$")] </Document> </Project> </Workspace>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendInvokeCompletionList() Await state.AssertSelectedCompletionItem("ClassLibrary1") state.SendTab() state.AssertMatchesTextStartingAtLine(1, "[assembly: System.Runtime.CompilerServices.InternalsVisibleTo(""ClassLibrary1, PublicKey=00240000048000009400000006020000002400005253413100040000010001002b986f6b5ea5717d35c72d38561f413e267029efa9b5f107b9331d83df657381325b3a67b75812f63a9436ceccb49494de8f574f8e639d4d26c0fcf8b0e9a1a196b80b6f6ed053628d10d027e032df2ed1d60835e5f47d32c9ef6da10d0366a319573362c821b5f8fa5abc5bb22241de6f666a85d82d6ba8c3090d01636bd2bb"")]") End Using End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function CodeCompletionContainsPublicKeyIfKeyIsSpecifiedByAttribute(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateTestStateFromWorkspace( <Workspace> <Project Language="C#" CommonReferences="true" AssemblyName="ClassLibrary1"> <CompilationOptions StrongNameProvider=<%= SigningTestHelpers.DefaultDesktopStrongNameProvider.GetType().AssemblyQualifiedName %>/> <Document> [assembly: System.Reflection.AssemblyKeyFile("<%= SigningTestHelpers.PublicKeyFile.Replace("\", "\\") %>")] </Document> </Project> <Project Language="C#" CommonReferences="true" AssemblyName="TestAssembly"> <Document> [assembly: System.Runtime.CompilerServices.InternalsVisibleTo("$$")] </Document> </Project> </Workspace>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendInvokeCompletionList() Await state.AssertSelectedCompletionItem("ClassLibrary1") state.SendTab() state.AssertMatchesTextStartingAtLine(1, "[assembly: System.Runtime.CompilerServices.InternalsVisibleTo(""ClassLibrary1, PublicKey=00240000048000009400000006020000002400005253413100040000010001002b986f6b5ea5717d35c72d38561f413e267029efa9b5f107b9331d83df657381325b3a67b75812f63a9436ceccb49494de8f574f8e639d4d26c0fcf8b0e9a1a196b80b6f6ed053628d10d027e032df2ed1d60835e5f47d32c9ef6da10d0366a319573362c821b5f8fa5abc5bb22241de6f666a85d82d6ba8c3090d01636bd2bb"")]") End Using End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function CodeCompletionContainsPublicKeyIfDelayedSigningIsEnabled(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateTestStateFromWorkspace( <Workspace> <Project Language="C#" CommonReferences="true" AssemblyName="ClassLibrary1"> <CompilationOptions CryptoKeyFile=<%= SigningTestHelpers.PublicKeyFile %> StrongNameProvider=<%= SigningTestHelpers.DefaultDesktopStrongNameProvider.GetType().AssemblyQualifiedName %> DelaySign="True"/> </Project> <Project Language="C#" CommonReferences="true" AssemblyName="TestAssembly"> <Document> [assembly: System.Runtime.CompilerServices.InternalsVisibleTo("$$")] </Document> </Project> </Workspace>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendInvokeCompletionList() Await state.AssertSelectedCompletionItem("ClassLibrary1") state.SendTab() state.AssertMatchesTextStartingAtLine(1, "[assembly: System.Runtime.CompilerServices.InternalsVisibleTo(""ClassLibrary1, PublicKey=00240000048000009400000006020000002400005253413100040000010001002b986f6b5ea5717d35c72d38561f413e267029efa9b5f107b9331d83df657381325b3a67b75812f63a9436ceccb49494de8f574f8e639d4d26c0fcf8b0e9a1a196b80b6f6ed053628d10d027e032df2ed1d60835e5f47d32c9ef6da10d0366a319573362c821b5f8fa5abc5bb22241de6f666a85d82d6ba8c3090d01636bd2bb"")]") End Using End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function CodeCompletionListIsEmptyIfAttributeIsNotTheBCLAttribute(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateTestStateFromWorkspace( <Workspace> <Project Language="C#" CommonReferences="true" AssemblyName="ClassLibrary1"/> <Project Language="C#" CommonReferences="true" AssemblyName="TestAssembly"> <Document FilePath="C.cs"> [assembly: Test.InternalsVisibleTo("$$")] namespace Test { [System.AttributeUsage(System.AttributeTargets.Assembly)] public sealed class InternalsVisibleToAttribute: System.Attribute { public InternalsVisibleToAttribute(string ignore) { } } } </Document> </Project> </Workspace>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendInvokeCompletionList() Await state.AssertNoCompletionSession() End Using End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function CodeCompletionContainsOnlyAssembliesThatAreNotAlreadyIVT(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateTestStateFromWorkspace( <Workspace> <Project Language="C#" CommonReferences="true" AssemblyName="ClassLibrary1"/> <Project Language="C#" CommonReferences="true" AssemblyName="ClassLibrary2"/> <Project Language="C#" CommonReferences="true" AssemblyName="ClassLibrary3"/> <Project Language="C#" CommonReferences="true" AssemblyName="TestAssembly"> <Document FilePath="C.cs"> [assembly: System.Runtime.CompilerServices.InternalsVisibleTo("ClassLibrary1")] [assembly: System.Runtime.CompilerServices.InternalsVisibleTo("ClassLibrary2")] [assembly: System.Runtime.CompilerServices.InternalsVisibleTo("$$ </Document> </Project> </Workspace>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendInvokeCompletionList() Await state.AssertCompletionItemsDoNotContainAny("ClassLibrary1", "ClassLibrary2") Await state.AssertCompletionItemsContainAll("ClassLibrary3") End Using End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function CodeCompletionContainsOnlyAssembliesThatAreNotAlreadyIVTIfAssemblyNameIsAConstant(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateTestStateFromWorkspace( <Workspace> <Project Language="C#" CommonReferences="true" AssemblyName="ClassLibrary1"/> <Project Language="C#" CommonReferences="true" AssemblyName="ClassLibrary2"/> <Project Language="C#" CommonReferences="true" AssemblyName="ClassLibrary3"/> <Project Language="C#" CommonReferences="true" AssemblyName="TestAssembly"> <MetadataReferenceFromSource Language="C#" CommonReferences="true"> <Document FilePath="ReferencedDocument.cs"> namespace A { public static class Constants { public const string AssemblyName1 = "ClassLibrary1"; } } </Document> </MetadataReferenceFromSource> <Document FilePath="C.cs"> [assembly: System.Runtime.CompilerServices.InternalsVisibleTo(A.Constants.AssemblyName1)] [assembly: System.Runtime.CompilerServices.InternalsVisibleTo("ClassLibrary2")] [assembly: System.Runtime.CompilerServices.InternalsVisibleTo("$$ </Document> </Project> </Workspace>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendInvokeCompletionList() Await state.AssertCompletionItemsDoNotContainAny("ClassLibrary1", "ClassLibrary2") Await state.AssertCompletionItemsContainAll("ClassLibrary3") End Using End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function CodeCompletionContainsOnlyAssembliesThatAreNotAlreadyIVTForDifferentSyntax(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateTestStateFromWorkspace( <Workspace> <Project Language="C#" CommonReferences="true" AssemblyName="ClassLibrary1"/> <Project Language="C#" CommonReferences="true" AssemblyName="ClassLibrary2"/> <Project Language="C#" CommonReferences="true" AssemblyName="ClassLibrary3"/> <Project Language="C#" CommonReferences="true" AssemblyName="ClassLibrary4"/> <Project Language="C#" CommonReferences="true" AssemblyName="ClassLibrary5"/> <Project Language="C#" CommonReferences="true" AssemblyName="ClassLibrary6"/> <Project Language="C#" CommonReferences="true" AssemblyName="ClassLibrary7"/> <Project Language="C#" CommonReferences="true" AssemblyName="ClassLibrary8"/> <Project Language="C#" CommonReferences="true" AssemblyName="ClassLibrary9"/> <Project Language="C#" CommonReferences="true" AssemblyName="TestAssembly"> <Document FilePath="C.cs"> // Code comment using System.Runtime.CompilerServices; using System.Reflection; using IVT = System.Runtime.CompilerServices.InternalsVisibleToAttribute; // Code comment [assembly: InternalsVisibleTo("ClassLibrary1", AllInternalsVisible = true)] [assembly: InternalsVisibleTo(assemblyName: "ClassLibrary2", AllInternalsVisible = true)] [assembly: AssemblyVersion("1.0.0.0"), InternalsVisibleTo("ClassLibrary3")] [assembly: InternalsVisibleTo("ClassLibrary4"), AssemblyCopyright("Copyright")] [assembly: AssemblyDescription("Description")] [assembly: InternalsVisibleTo("ClassLibrary5")] [assembly: InternalsVisibleTo("ClassLibrary6, PublicKey=00240000048000009400000006020000002400005253413100040000010001002b986f6b5ea5717d35c72d38561f413e267029efa9b5f107b9331d83df657381325b3a67b75812f63a9436ceccb49494de8f574f8e639d4d26c0fcf8b0e9a1a196b80b6f6ed053628d10d027e032df2ed1d60835e5f47d32c9ef6da10d0366a319573362c821b5f8fa5abc5bb22241de6f666a85d82d6ba8c3090d01636bd2bb")] [assembly: InternalsVisibleTo("ClassLibrary" + "7")] [assembly: IVT("ClassLibrary8")] [assembly: InternalsVisibleTo("$$ namespace A { public class A { } } </Document> </Project> </Workspace>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendInvokeCompletionList() Await state.AssertCompletionItemsDoNotContainAny("ClassLibrary1", "ClassLibrary2", "ClassLibrary3", "ClassLibrary4", "ClassLibrary5", "ClassLibrary6", "ClassLibrary7", "ClassLibrary8") Await state.AssertCompletionItemsContainAll("ClassLibrary9") End Using End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function CodeCompletionContainsOnlyAssembliesThatAreNotAlreadyIVTWithSyntaxError(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateTestStateFromWorkspace( <Workspace> <Project Language="C#" CommonReferences="true" AssemblyName="ClassLibrary1"/> <Project Language="C#" CommonReferences="true" AssemblyName="TestAssembly"> <Document FilePath="C.cs"> using System.Runtime.CompilerServices; using System.Reflection; [assembly: InternalsVisibleTo("ClassLibrary" + 1)] // Not a constant [assembly: InternalsVisibleTo("$$ </Document> </Project> </Workspace>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendInvokeCompletionList() ' ClassLibrary1 must be listed because the existing attribute argument can't be resolved to a constant. Await state.AssertCompletionItemsContainAll("ClassLibrary1") End Using End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function CodeCompletionContainsOnlyAssembliesThatAreNotAlreadyIVTWithMoreThanOneDocument(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateTestStateFromWorkspace( <Workspace> <Project Language="C#" CommonReferences="true" AssemblyName="ClassLibrary1"/> <Project Language="C#" CommonReferences="true" AssemblyName="ClassLibrary2"/> <Project Language="C#" CommonReferences="true" AssemblyName="TestAssembly"> <Document FilePath="OtherDocument.cs"> using System.Runtime.CompilerServices; using System.Reflection; [assembly: InternalsVisibleTo("ClassLibrary1")] [assembly: AssemblyDescription("Description")] </Document> <Document FilePath="C.cs"> using System.Runtime.CompilerServices; using System.Reflection; [assembly: InternalsVisibleTo("$$ </Document> </Project> </Workspace>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendInvokeCompletionList() Await state.AssertCompletionItemsDoNotContainAny("ClassLibrary1") Await state.AssertCompletionItemsContainAll("ClassLibrary2") End Using End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function CodeCompletionIgnoresUnsupportedProjectTypes(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateTestStateFromWorkspace( <Workspace> <Project Language="NoCompilation" AssemblyName="ClassLibrary1"/> <Project Language="C#" CommonReferences="true" AssemblyName="TestAssembly"> <Document FilePath="C.cs"> using System.Runtime.CompilerServices; using System.Reflection; [assembly: InternalsVisibleTo("$$ </Document> </Project> </Workspace>, extraExportedTypes:={GetType(NoCompilationContentTypeDefinitions), GetType(NoCompilationContentTypeLanguageService)}, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendInvokeCompletionList() Await state.AssertNoCompletionSession() End Using End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Completion)> <WorkItem(29447, "https://github.com/dotnet/roslyn/pull/29447")> Public Async Function CodeCompletionReplacesExisitingAssemblyNameWithDots_1(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateTestStateFromWorkspace( <Workspace> <Project Language="C#" AssemblyName="Dotted.Assembly.Name"/> <Project Language="C#" CommonReferences="true" AssemblyName="TestAssembly"> <Document FilePath="C.cs"> [assembly: System.Runtime.CompilerServices.InternalsVisibleTo("Dotted.Assem$$bly")] </Document> </Project> </Workspace>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendInvokeCompletionList() Await state.AssertSelectedCompletionItem("Dotted.Assembly.Name") state.SendTab() state.AssertMatchesTextStartingAtLine(1, "[assembly: System.Runtime.CompilerServices.InternalsVisibleTo(""Dotted.Assembly.Name"")]") End Using End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Completion)> <WorkItem(29447, "https://github.com/dotnet/roslyn/pull/29447")> Public Async Function CodeCompletionReplacesExisitingAssemblyNameWithDots_2(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateTestStateFromWorkspace( <Workspace> <Project Language="C#" AssemblyName="Dotted.Assembly.Name"/> <Project Language="C#" CommonReferences="true" AssemblyName="TestAssembly"> <Document FilePath="C.cs"> [assembly: System.Runtime.CompilerServices.InternalsVisibleTo("Dotted.Assem$$bly </Document> </Project> </Workspace>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendInvokeCompletionList() Await state.AssertSelectedCompletionItem("Dotted.Assembly.Name") state.SendTab() state.AssertMatchesTextStartingAtLine(1, "[assembly: System.Runtime.CompilerServices.InternalsVisibleTo(""Dotted.Assembly.Name") End Using End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Completion)> <WorkItem(29447, "https://github.com/dotnet/roslyn/pull/29447")> Public Async Function CodeCompletionReplacesExisitingAssemblyNameWithDots_3(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateTestStateFromWorkspace( <Workspace> <Project Language="C#" AssemblyName="Dotted.Assembly.Name"/> <Project Language="C#" CommonReferences="true" AssemblyName="TestAssembly"> <Document FilePath="C.cs"> [assembly: System.Runtime.CompilerServices.InternalsVisibleTo(" Dotted.Assem$$bly ")] </Document> </Project> </Workspace>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendInvokeCompletionList() Await state.AssertSelectedCompletionItem("Dotted.Assembly.Name") state.SendTab() state.AssertMatchesTextStartingAtLine(1, "[assembly: System.Runtime.CompilerServices.InternalsVisibleTo(""Dotted.Assembly.Name"")]") End Using End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Completion)> <WorkItem(29447, "https://github.com/dotnet/roslyn/pull/29447")> Public Async Function CodeCompletionReplacesExisitingAssemblyNameWithDots_4(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateTestStateFromWorkspace( <Workspace> <Project Language="C#" AssemblyName="Dotted1.Dotted2.Assembly.Dotted3"/> <Project Language="C#" CommonReferences="true" AssemblyName="TestAssembly"> <Document FilePath="C.cs"> [assembly: System.Runtime.CompilerServices.InternalsVisibleTo("Dotted1.Dotted2.Assem$$bly.Dotted")] </Document> </Project> </Workspace>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendInvokeCompletionList() Await state.AssertSelectedCompletionItem("Dotted1.Dotted2.Assembly.Dotted3") state.SendTab() state.AssertMatchesTextStartingAtLine(1, "[assembly: System.Runtime.CompilerServices.InternalsVisibleTo(""Dotted1.Dotted2.Assembly.Dotted3"")]") End Using End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Completion)> <WorkItem(29447, "https://github.com/dotnet/roslyn/pull/29447")> Public Async Function CodeCompletionReplacesExisitingAssemblyNameWithDots_Verbatim_1(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateTestStateFromWorkspace( <Workspace> <Project Language="C#" AssemblyName="Dotted1.Dotted2.Assembly.Dotted3"/> <Project Language="C#" CommonReferences="true" AssemblyName="TestAssembly"> <Document FilePath="C.cs"> [assembly: System.Runtime.CompilerServices.InternalsVisibleTo(@"Dotted1.Dotted2.Assem$$bly.Dotted")] </Document> </Project> </Workspace>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendInvokeCompletionList() Await state.AssertSelectedCompletionItem("Dotted1.Dotted2.Assembly.Dotted3") state.SendTab() state.AssertMatchesTextStartingAtLine(1, "[assembly: System.Runtime.CompilerServices.InternalsVisibleTo(@""Dotted1.Dotted2.Assembly.Dotted3"")]") End Using End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Completion)> <WorkItem(29447, "https://github.com/dotnet/roslyn/pull/29447")> Public Async Function CodeCompletionReplacesExisitingAssemblyNameWithDots_Verbatim_2(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateTestStateFromWorkspace( <Workspace> <Project Language="C#" AssemblyName="Dotted1.Dotted2.Assembly.Dotted3"/> <Project Language="C#" CommonReferences="true" AssemblyName="TestAssembly"> <Document FilePath="C.cs"> [assembly: System.Runtime.CompilerServices.InternalsVisibleTo(@"Dotted1.Dotted2.Assem$$bly </Document> </Project> </Workspace>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendInvokeCompletionList() Await state.AssertSelectedCompletionItem("Dotted1.Dotted2.Assembly.Dotted3") state.SendTab() state.AssertMatchesTextStartingAtLine(1, "[assembly: System.Runtime.CompilerServices.InternalsVisibleTo(@""Dotted1.Dotted2.Assembly.Dotted3") End Using End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Completion)> <WorkItem(29447, "https://github.com/dotnet/roslyn/pull/29447")> Public Async Function CodeCompletionReplacesExisitingAssemblyNameWithDots_EscapeSequence_1(showCompletionInArgumentLists As Boolean) As Task ' Escaped double quotes are not handled properly: The selection is expanded from the cursor position until ' a double quote or new line is reached. But because double quotes are not allowed in this context this ' case is rare enough to ignore. Supporting it would require more complicated code that was reverted in ' https://github.com/dotnet/roslyn/pull/29447/commits/e7a852a7e83fffe1f25a8dee0aaec68f67fcc1d8 Using state = TestStateFactory.CreateTestStateFromWorkspace( <Workspace> <Project Language="C#" AssemblyName="Dotted1.Dotted2.Assembly.Dotted3"/> <Project Language="C#" CommonReferences="true" AssemblyName="TestAssembly"> <Document FilePath="C.cs"> [assembly: System.Runtime.CompilerServices.InternalsVisibleTo("\"Dotted1.Dotted2.Assem$$bly\"")] </Document> </Project> </Workspace>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendInvokeCompletionList() Await state.AssertSelectedCompletionItem("Dotted1.Dotted2.Assembly.Dotted3") state.SendTab() state.AssertMatchesTextStartingAtLine(1, "[assembly: System.Runtime.CompilerServices.InternalsVisibleTo(""\""Dotted1.Dotted2.Assembly.Dotted3"""")]") End Using End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Completion)> <WorkItem(29447, "https://github.com/dotnet/roslyn/pull/29447")> Public Async Function CodeCompletionReplacesExisitingAssemblyNameWithDots_OpenEnded(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateTestStateFromWorkspace( <Workspace> <Project Language="C#" AssemblyName="Dotted1.Dotted2.Assembly.Dotted3"/> <Project Language="C#" CommonReferences="true" AssemblyName="TestAssembly"> <Document FilePath="C.cs"> [assembly: System.Runtime.CompilerServices.InternalsVisibleTo("Dotted1.Dotted2.Assem$$bly.Dotted4 </Document> </Project> </Workspace>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendInvokeCompletionList() Await state.AssertSelectedCompletionItem("Dotted1.Dotted2.Assembly.Dotted3") state.SendTab() state.AssertMatchesTextStartingAtLine(1, "[assembly: System.Runtime.CompilerServices.InternalsVisibleTo(""Dotted1.Dotted2.Assembly.Dotted3") End Using End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Completion)> <WorkItem(29447, "https://github.com/dotnet/roslyn/pull/29447")> Public Async Function CodeCompletionReplacesExisitingAssemblyNameWithDots_AndPublicKey_OpenEnded(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateTestStateFromWorkspace( <Workspace> <Project Language="C#" AssemblyName="Dotted1.Dotted2.Assembly.Dotted3"/> <Project Language="C#" CommonReferences="true" AssemblyName="TestAssembly"> <Document FilePath="C.cs"> [assembly: System.Runtime.CompilerServices.InternalsVisibleTo("Company.Asse$$mbly, PublicKey=123 </Document> </Project> </Workspace>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendInvokeCompletionList() Await state.AssertSelectedCompletionItem("Dotted1.Dotted2.Assembly.Dotted3") state.SendTab() state.AssertMatchesTextStartingAtLine(1, "[assembly: System.Runtime.CompilerServices.InternalsVisibleTo(""Dotted1.Dotted2.Assembly.Dotted3") End Using End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Completion)> <WorkItem(29447, "https://github.com/dotnet/roslyn/pull/29447")> Public Async Function CodeCompletionReplacesExisitingAssemblyNameWithDots_AndPublicKey_LineBreakExampleFromMSDN(showCompletionInArgumentLists As Boolean) As Task ' Source https://msdn.microsoft.com/de-de/library/system.runtime.compilerservices.internalsvisibletoattribute(v=vs.110).aspx Using state = TestStateFactory.CreateTestStateFromWorkspace( <Workspace> <Project Language="C#" AssemblyName="Dotted1.Dotted2.Assembly.Dotted3"/> <Project Language="C#" CommonReferences="true" AssemblyName="TestAssembly"> <Document FilePath="C.cs"> [assembly: System.Runtime.CompilerServices.InternalsVisibleTo("$$Friend1, PublicKey=002400000480000094" + "0000000602000000240000525341310004000" + "001000100bf8c25fcd44838d87e245ab35bf7" + "3ba2615707feea295709559b3de903fb95a93" + "3d2729967c3184a97d7b84c7547cd87e435b5" + "6bdf8621bcb62b59c00c88bd83aa62c4fcdd4" + "712da72eec2533dc00f8529c3a0bbb4103282" + "f0d894d5f34e9f0103c473dce9f4b457a5dee" + "fd8f920d8681ed6dfcb0a81e96bd9b176525a" + "26e0b3")] </Document> </Project> </Workspace>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendInvokeCompletionList() Await state.AssertSelectedCompletionItem("Dotted1.Dotted2.Assembly.Dotted3") state.SendTab() state.AssertMatchesTextStartingAtLine(1, "[assembly: System.Runtime.CompilerServices.InternalsVisibleTo(""Dotted1.Dotted2.Assembly.Dotted3"" +") state.AssertMatchesTextStartingAtLine(2, " ""0000000602000000240000525341310004000"" +") End Using End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Completion)> <WorkItem(29447, "https://github.com/dotnet/roslyn/pull/29447")> Public Async Function CodeCompletionReplacesExisitingAssemblyNameWithDots_OpenEndedStringFollowedByEOF(showCompletionInArgumentLists As Boolean) As Task ' Source https://msdn.microsoft.com/de-de/library/system.runtime.compilerservices.internalsvisibletoattribute(v=vs.110).aspx Using state = TestStateFactory.CreateTestStateFromWorkspace( <Workspace> <Project Language="C#" AssemblyName="Dotted1.Dotted2.Assembly.Dotted3"/> <Project Language="C#" CommonReferences="true" AssemblyName="TestAssembly"> <Document FilePath="C.cs"> [assembly: System.Runtime.CompilerServices.InternalsVisibleTo("Friend1$$</Document> </Project> </Workspace>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendInvokeCompletionList() Await state.AssertSelectedCompletionItem("Dotted1.Dotted2.Assembly.Dotted3") state.SendTab() state.AssertMatchesTextStartingAtLine(1, "[assembly: System.Runtime.CompilerServices.InternalsVisibleTo(""Dotted1.Dotted2.Assembly.Dotted3") End Using End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Completion)> <WorkItem(29447, "https://github.com/dotnet/roslyn/pull/29447")> Public Async Function CodeCompletionReplacesExisitingAssemblyNameWithDots_OpenEndedStringFollowedByNewLines(showCompletionInArgumentLists As Boolean) As Task ' Source https://msdn.microsoft.com/de-de/library/system.runtime.compilerservices.internalsvisibletoattribute(v=vs.110).aspx Using state = TestStateFactory.CreateTestStateFromWorkspace( <Workspace> <Project Language="C#" AssemblyName="Dotted1.Dotted2.Assembly.Dotted3"/> <Project Language="C#" CommonReferences="true" AssemblyName="TestAssembly"> <Document FilePath="C.cs"><![CDATA[ [assembly: System.Runtime.CompilerServices.InternalsVisibleTo("Friend1$$ ]]> </Document> </Project> </Workspace>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendInvokeCompletionList() Await state.AssertSelectedCompletionItem("Dotted1.Dotted2.Assembly.Dotted3") state.SendTab() state.AssertMatchesTextStartingAtLine(1, "[assembly: System.Runtime.CompilerServices.InternalsVisibleTo(""Dotted1.Dotted2.Assembly.Dotted3") state.AssertMatchesTextStartingAtLine(2, "") End Using End Function End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces Namespace Microsoft.CodeAnalysis.Editor.UnitTests.IntelliSense <[UseExportProvider]> Public Class CSharpCompletionCommandHandlerTests_InternalsVisibleTo <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function CodeCompletionContainsOtherAssembliesOfSolution(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateTestStateFromWorkspace( <Workspace> <Project Language="C#" CommonReferences="true" AssemblyName="ClassLibrary1"/> <Project Language="C#" CommonReferences="true" AssemblyName="ClassLibrary2"/> <Project Language="C#" CommonReferences="true" AssemblyName="ClassLibrary3"/> <Project Language="C#" CommonReferences="true" AssemblyName="TestAssembly"> <Document FilePath="C.cs"> [assembly: System.Runtime.CompilerServices.InternalsVisibleTo("$$ </Document> </Project> </Workspace>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendInvokeCompletionList() Await state.AssertCompletionItemsContainAll("ClassLibrary1", "ClassLibrary2", "ClassLibrary3") End Using End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function CodeCompletionContainsOtherAssemblyIfAttributeSuffixIsPresent(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateTestStateFromWorkspace( <Workspace> <Project Language="C#" CommonReferences="true" AssemblyName="ClassLibrary1"/> <Project Language="C#" CommonReferences="true" AssemblyName="TestAssembly"> <Document FilePath="C.cs"> [assembly: System.Runtime.CompilerServices.InternalsVisibleToAttribute("$$ </Document> </Project> </Workspace>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendInvokeCompletionList() Await state.AssertCompletionItemsContainAll("ClassLibrary1") End Using End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function CodeCompletionIsTriggeredWhenDoubleQuoteIsEntered(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateTestStateFromWorkspace( <Workspace> <Project Language="C#" CommonReferences="true" AssemblyName="ClassLibrary1"/> <Project Language="C#" CommonReferences="true" AssemblyName="TestAssembly"> <Document FilePath="C.cs"> [assembly: System.Runtime.CompilerServices.InternalsVisibleTo($$ </Document> </Project> </Workspace>, showCompletionInArgumentLists:=showCompletionInArgumentLists) Await state.AssertNoCompletionSession() state.SendTypeChars(""""c) Await state.AssertCompletionItemsContainAll("ClassLibrary1") End Using End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function CodeCompletionIsEmptyUntilDoubleQuotesAreEntered(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateTestStateFromWorkspace( <Workspace> <Project Language="C#" CommonReferences="true" AssemblyName="ClassLibrary1"/> <Project Language="C#" CommonReferences="true" AssemblyName="TestAssembly"> <Document FilePath="C.cs"> [assembly: System.Runtime.CompilerServices.InternalsVisibleTo$$ </Document> </Project> </Workspace>, showCompletionInArgumentLists:=showCompletionInArgumentLists) Await state.AssertNoCompletionSession() state.SendInvokeCompletionList() Await state.AssertCompletionItemsDoNotContainAny("ClassLibrary1") state.SendTypeChars("("c) If Not showCompletionInArgumentLists Then Await state.AssertNoCompletionSession() state.SendInvokeCompletionList() End If Await state.AssertCompletionItemsDoNotContainAny("ClassLibrary1") state.SendTypeChars(""""c) Await state.AssertCompletionItemsContainAll("ClassLibrary1") End Using End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function CodeCompletionIsTriggeredWhenCharacterIsEnteredAfterOpeningDoubleQuote(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateTestStateFromWorkspace( <Workspace> <Project Language="C#" CommonReferences="true" AssemblyName="ClassLibrary1"/> <Project Language="C#" CommonReferences="true" AssemblyName="TestAssembly"> <Document FilePath="C.cs"> [assembly: System.Runtime.CompilerServices.InternalsVisibleTo("$$")] </Document> </Project> </Workspace>, showCompletionInArgumentLists:=showCompletionInArgumentLists) Await state.AssertNoCompletionSession() state.SendTypeChars("a"c) Await state.AssertCompletionItemsContainAll("ClassLibrary1") End Using End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function CodeCompletionIsNotTriggeredWhenCharacterIsEnteredThatIsNotRightBesideTheOpeniningDoubleQuote(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateTestStateFromWorkspace( <Workspace> <Project Language="C#" CommonReferences="true" AssemblyName="ClassLibrary1"/> <Project Language="C#" CommonReferences="true" AssemblyName="TestAssembly"> <Document FilePath="C.cs"> [assembly: System.Runtime.CompilerServices.InternalsVisibleTo("a$$")] </Document> </Project> </Workspace>, showCompletionInArgumentLists:=showCompletionInArgumentLists) Await state.AssertNoCompletionSession() state.SendTypeChars("b"c) Await state.AssertNoCompletionSession() End Using End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function CodeCompletionIsNotTriggeredWhenDoubleQuoteIsEnteredAtStartOfFile(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateTestStateFromWorkspace( <Workspace> <Project Language="C#" CommonReferences="true" AssemblyName="ClassLibrary1"/> <Project Language="C#" CommonReferences="true" AssemblyName="TestAssembly"> <Document FilePath="C.cs">$$ </Document> </Project> </Workspace>, showCompletionInArgumentLists:=showCompletionInArgumentLists) Await state.AssertNoCompletionSession() state.SendTypeChars("a"c) Await state.AssertCompletionItemsDoNotContainAny("ClassLibrary1") End Using End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function CodeCompletionIsNotTriggeredByArrayElementAccess(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateTestStateFromWorkspace( <Workspace> <Project Language="C#" CommonReferences="true" AssemblyName="ClassLibrary1"/> <Project Language="C#" CommonReferences="true" AssemblyName="TestAssembly"> <Document FilePath="C.cs"><![CDATA[ namespace A { public class C { public void M() { var d = new System.Collections.Generic.Dictionary<string, string>(); var v = d$$; } } } ]]> </Document> </Project> </Workspace>, showCompletionInArgumentLists:=showCompletionInArgumentLists) Dim AssertNoCompletionAndCompletionDoesNotContainClassLibrary1 As Func(Of Task) = Async Function() Await state.AssertNoCompletionSession() state.SendInvokeCompletionList() Await state.AssertSessionIsNothingOrNoCompletionItemLike("ClassLibrary1") End Function Await AssertNoCompletionAndCompletionDoesNotContainClassLibrary1() state.SendTypeChars("["c) If Not showCompletionInArgumentLists Then Await AssertNoCompletionAndCompletionDoesNotContainClassLibrary1() Else Await state.AssertCompletionSession() Await state.AssertSessionIsNothingOrNoCompletionItemLike("ClassLibrary1") End If state.SendTypeChars(""""c) Await AssertNoCompletionAndCompletionDoesNotContainClassLibrary1() End Using End Function Private Shared Async Function AssertCompletionListHasItems(code As String, hasItems As Boolean, showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateTestStateFromWorkspace( <Workspace> <Project Language="C#" CommonReferences="true" AssemblyName="ClassLibrary1"/> <Project Language="C#" CommonReferences="true" AssemblyName="TestAssembly"> <Document FilePath="C.cs"> using System.Runtime.CompilerServices; using System.Reflection; <%= code %> </Document> </Project> </Workspace>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendInvokeCompletionList() If hasItems Then Await state.AssertCompletionItemsContainAll("ClassLibrary1") Else Await state.AssertNoCompletionSession End If End Using End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function AssertCompletionListHasItems_AfterSingleDoubleQuoteAndClosing(showCompletionInArgumentLists As Boolean) As Task Await AssertCompletionListHasItems("[assembly: InternalsVisibleTo(""$$)]", True, showCompletionInArgumentLists) End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function AssertCompletionListHasItems_AfterText(showCompletionInArgumentLists As Boolean) As Task Await AssertCompletionListHasItems("[assembly: InternalsVisibleTo(""Test$$)]", True, showCompletionInArgumentLists) End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function AssertCompletionListHasItems_IfCursorIsInSecondParameter(showCompletionInArgumentLists As Boolean) As Task Await AssertCompletionListHasItems("[assembly: InternalsVisibleTo(""Test"", ""$$", True, showCompletionInArgumentLists) End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function AssertCompletionListHasNoItems_IfCursorIsClosingDoubleQuote1(showCompletionInArgumentLists As Boolean) As Task Await AssertCompletionListHasItems("[assembly: InternalsVisibleTo(""Test""$$", False, showCompletionInArgumentLists) End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function AssertCompletionListHasNoItems_IfCursorIsClosingDoubleQuote2(showCompletionInArgumentLists As Boolean) As Task Await AssertCompletionListHasItems("[assembly: InternalsVisibleTo(""""$$", False, showCompletionInArgumentLists) End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function AssertCompletionListHasItems_IfNamedParameterIsPresent(showCompletionInArgumentLists As Boolean) As Task Await AssertCompletionListHasItems("[assembly: InternalsVisibleTo(""$$, AllInternalsVisible = true)]", True, showCompletionInArgumentLists) End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function AssertCompletionListHasItems_IfNamedParameterAndNamedPositionalParametersArePresent(showCompletionInArgumentLists As Boolean) As Task Await AssertCompletionListHasItems("[assembly: InternalsVisibleTo(assemblyName: ""$$, AllInternalsVisible = true)]", True, showCompletionInArgumentLists) End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function AssertCompletionListHasNoItems_IfNumberIsEntered(showCompletionInArgumentLists As Boolean) As Task Await AssertCompletionListHasItems("[assembly: InternalsVisibleTo(1$$2)]", False, showCompletionInArgumentLists) End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function AssertCompletionListHasNoItems_IfNotInternalsVisibleToAttribute(showCompletionInArgumentLists As Boolean) As Task Await AssertCompletionListHasItems("[assembly: AssemblyVersion(""$$"")]", False, showCompletionInArgumentLists) End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function AssertCompletionListHasItems_IfOtherAttributeIsPresent1(showCompletionInArgumentLists As Boolean) As Task Await AssertCompletionListHasItems("[assembly: AssemblyVersion(""1.0.0.0""), InternalsVisibleTo(""$$", True, showCompletionInArgumentLists) End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function AssertCompletionListHasItems_IfOtherAttributeIsPresent2(showCompletionInArgumentLists As Boolean) As Task Await AssertCompletionListHasItems("[assembly: InternalsVisibleTo(""$$""), AssemblyVersion(""1.0.0.0"")]", True, showCompletionInArgumentLists) End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function AssertCompletionListHasItems_IfOtherAttributesAreAhead(showCompletionInArgumentLists As Boolean) As Task Await AssertCompletionListHasItems(" [assembly: AssemblyVersion(""1.0.0.0"")] [assembly: InternalsVisibleTo(""$$", True, showCompletionInArgumentLists) End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function AssertCompletionListHasItems_IfOtherAttributesAreFollowing(showCompletionInArgumentLists As Boolean) As Task Await AssertCompletionListHasItems(" [assembly: InternalsVisibleTo(""$$ [assembly: AssemblyVersion(""1.0.0.0"")] [assembly: AssemblyCompany(""Test"")]", True, showCompletionInArgumentLists) End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function AssertCompletionListHasItems_IfNamespaceIsFollowing(showCompletionInArgumentLists As Boolean) As Task Await AssertCompletionListHasItems(" [assembly: InternalsVisibleTo(""$$ namespace A { public class A { } }", True, showCompletionInArgumentLists) End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function CodeCompletionHasItemsIfInteralVisibleToIsReferencedByTypeAlias(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateTestStateFromWorkspace( <Workspace> <Project Language="C#" CommonReferences="true" AssemblyName="ClassLibrary1"/> <Project Language="C#" CommonReferences="true" AssemblyName="TestAssembly"> <Document FilePath="C.cs"> using IVT = System.Runtime.CompilerServices.InternalsVisibleToAttribute; [assembly: IVT("$$ </Document> </Project> </Workspace>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendInvokeCompletionList() Await state.AssertCompletionItemsContainAll("ClassLibrary1") End Using End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function CodeCompletionDoesNotContainCurrentAssembly(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateTestStateFromWorkspace( <Workspace> <Project Language="C#" CommonReferences="true" AssemblyName="ClassLibrary1"/> <Project Language="C#" CommonReferences="true" AssemblyName="TestAssembly"> <Document FilePath="C.cs"> [assembly: System.Runtime.CompilerServices.InternalsVisibleTo("$$")] </Document> </Project> </Workspace>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendInvokeCompletionList() Await state.AssertCompletionItemsDoNotContainAny("TestAssembly") End Using End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function CodeCompletionInsertsAssemblyNameOnCommit(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateTestStateFromWorkspace( <Workspace> <Project Language="C#" CommonReferences="true" AssemblyName="ClassLibrary1"> </Project> <Project Language="C#" CommonReferences="true" AssemblyName="TestAssembly"> <Document> [assembly: System.Runtime.CompilerServices.InternalsVisibleTo("$$")] </Document> </Project> </Workspace>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendInvokeCompletionList() Await state.AssertSelectedCompletionItem("ClassLibrary1") state.SendTab() state.AssertMatchesTextStartingAtLine(1, "[assembly: System.Runtime.CompilerServices.InternalsVisibleTo(""ClassLibrary1"")]") End Using End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function CodeCompletionInsertsPublicKeyOnCommit(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateTestStateFromWorkspace( <Workspace> <Project Language="C#" CommonReferences="true" AssemblyName="ClassLibrary1"> <CompilationOptions CryptoKeyFile=<%= SigningTestHelpers.PublicKeyFile %> StrongNameProvider=<%= SigningTestHelpers.DefaultDesktopStrongNameProvider.GetType().AssemblyQualifiedName %>/> </Project> <Project Language="C#" CommonReferences="true" AssemblyName="TestAssembly"> <Document> [assembly: System.Runtime.CompilerServices.InternalsVisibleTo("$$")] </Document> </Project> </Workspace>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendInvokeCompletionList() Await state.AssertSelectedCompletionItem("ClassLibrary1") state.SendTab() state.AssertMatchesTextStartingAtLine(1, "[assembly: System.Runtime.CompilerServices.InternalsVisibleTo(""ClassLibrary1, PublicKey=00240000048000009400000006020000002400005253413100040000010001002b986f6b5ea5717d35c72d38561f413e267029efa9b5f107b9331d83df657381325b3a67b75812f63a9436ceccb49494de8f574f8e639d4d26c0fcf8b0e9a1a196b80b6f6ed053628d10d027e032df2ed1d60835e5f47d32c9ef6da10d0366a319573362c821b5f8fa5abc5bb22241de6f666a85d82d6ba8c3090d01636bd2bb"")]") End Using End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function CodeCompletionContainsPublicKeyIfKeyIsSpecifiedByAttribute(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateTestStateFromWorkspace( <Workspace> <Project Language="C#" CommonReferences="true" AssemblyName="ClassLibrary1"> <CompilationOptions StrongNameProvider=<%= SigningTestHelpers.DefaultDesktopStrongNameProvider.GetType().AssemblyQualifiedName %>/> <Document> [assembly: System.Reflection.AssemblyKeyFile("<%= SigningTestHelpers.PublicKeyFile.Replace("\", "\\") %>")] </Document> </Project> <Project Language="C#" CommonReferences="true" AssemblyName="TestAssembly"> <Document> [assembly: System.Runtime.CompilerServices.InternalsVisibleTo("$$")] </Document> </Project> </Workspace>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendInvokeCompletionList() Await state.AssertSelectedCompletionItem("ClassLibrary1") state.SendTab() state.AssertMatchesTextStartingAtLine(1, "[assembly: System.Runtime.CompilerServices.InternalsVisibleTo(""ClassLibrary1, PublicKey=00240000048000009400000006020000002400005253413100040000010001002b986f6b5ea5717d35c72d38561f413e267029efa9b5f107b9331d83df657381325b3a67b75812f63a9436ceccb49494de8f574f8e639d4d26c0fcf8b0e9a1a196b80b6f6ed053628d10d027e032df2ed1d60835e5f47d32c9ef6da10d0366a319573362c821b5f8fa5abc5bb22241de6f666a85d82d6ba8c3090d01636bd2bb"")]") End Using End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function CodeCompletionContainsPublicKeyIfDelayedSigningIsEnabled(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateTestStateFromWorkspace( <Workspace> <Project Language="C#" CommonReferences="true" AssemblyName="ClassLibrary1"> <CompilationOptions CryptoKeyFile=<%= SigningTestHelpers.PublicKeyFile %> StrongNameProvider=<%= SigningTestHelpers.DefaultDesktopStrongNameProvider.GetType().AssemblyQualifiedName %> DelaySign="True"/> </Project> <Project Language="C#" CommonReferences="true" AssemblyName="TestAssembly"> <Document> [assembly: System.Runtime.CompilerServices.InternalsVisibleTo("$$")] </Document> </Project> </Workspace>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendInvokeCompletionList() Await state.AssertSelectedCompletionItem("ClassLibrary1") state.SendTab() state.AssertMatchesTextStartingAtLine(1, "[assembly: System.Runtime.CompilerServices.InternalsVisibleTo(""ClassLibrary1, PublicKey=00240000048000009400000006020000002400005253413100040000010001002b986f6b5ea5717d35c72d38561f413e267029efa9b5f107b9331d83df657381325b3a67b75812f63a9436ceccb49494de8f574f8e639d4d26c0fcf8b0e9a1a196b80b6f6ed053628d10d027e032df2ed1d60835e5f47d32c9ef6da10d0366a319573362c821b5f8fa5abc5bb22241de6f666a85d82d6ba8c3090d01636bd2bb"")]") End Using End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function CodeCompletionListIsEmptyIfAttributeIsNotTheBCLAttribute(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateTestStateFromWorkspace( <Workspace> <Project Language="C#" CommonReferences="true" AssemblyName="ClassLibrary1"/> <Project Language="C#" CommonReferences="true" AssemblyName="TestAssembly"> <Document FilePath="C.cs"> [assembly: Test.InternalsVisibleTo("$$")] namespace Test { [System.AttributeUsage(System.AttributeTargets.Assembly)] public sealed class InternalsVisibleToAttribute: System.Attribute { public InternalsVisibleToAttribute(string ignore) { } } } </Document> </Project> </Workspace>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendInvokeCompletionList() Await state.AssertNoCompletionSession() End Using End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function CodeCompletionContainsOnlyAssembliesThatAreNotAlreadyIVT(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateTestStateFromWorkspace( <Workspace> <Project Language="C#" CommonReferences="true" AssemblyName="ClassLibrary1"/> <Project Language="C#" CommonReferences="true" AssemblyName="ClassLibrary2"/> <Project Language="C#" CommonReferences="true" AssemblyName="ClassLibrary3"/> <Project Language="C#" CommonReferences="true" AssemblyName="TestAssembly"> <Document FilePath="C.cs"> [assembly: System.Runtime.CompilerServices.InternalsVisibleTo("ClassLibrary1")] [assembly: System.Runtime.CompilerServices.InternalsVisibleTo("ClassLibrary2")] [assembly: System.Runtime.CompilerServices.InternalsVisibleTo("$$ </Document> </Project> </Workspace>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendInvokeCompletionList() Await state.AssertCompletionItemsDoNotContainAny("ClassLibrary1", "ClassLibrary2") Await state.AssertCompletionItemsContainAll("ClassLibrary3") End Using End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function CodeCompletionContainsOnlyAssembliesThatAreNotAlreadyIVTIfAssemblyNameIsAConstant(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateTestStateFromWorkspace( <Workspace> <Project Language="C#" CommonReferences="true" AssemblyName="ClassLibrary1"/> <Project Language="C#" CommonReferences="true" AssemblyName="ClassLibrary2"/> <Project Language="C#" CommonReferences="true" AssemblyName="ClassLibrary3"/> <Project Language="C#" CommonReferences="true" AssemblyName="TestAssembly"> <MetadataReferenceFromSource Language="C#" CommonReferences="true"> <Document FilePath="ReferencedDocument.cs"> namespace A { public static class Constants { public const string AssemblyName1 = "ClassLibrary1"; } } </Document> </MetadataReferenceFromSource> <Document FilePath="C.cs"> [assembly: System.Runtime.CompilerServices.InternalsVisibleTo(A.Constants.AssemblyName1)] [assembly: System.Runtime.CompilerServices.InternalsVisibleTo("ClassLibrary2")] [assembly: System.Runtime.CompilerServices.InternalsVisibleTo("$$ </Document> </Project> </Workspace>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendInvokeCompletionList() Await state.AssertCompletionItemsDoNotContainAny("ClassLibrary1", "ClassLibrary2") Await state.AssertCompletionItemsContainAll("ClassLibrary3") End Using End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function CodeCompletionContainsOnlyAssembliesThatAreNotAlreadyIVTForDifferentSyntax(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateTestStateFromWorkspace( <Workspace> <Project Language="C#" CommonReferences="true" AssemblyName="ClassLibrary1"/> <Project Language="C#" CommonReferences="true" AssemblyName="ClassLibrary2"/> <Project Language="C#" CommonReferences="true" AssemblyName="ClassLibrary3"/> <Project Language="C#" CommonReferences="true" AssemblyName="ClassLibrary4"/> <Project Language="C#" CommonReferences="true" AssemblyName="ClassLibrary5"/> <Project Language="C#" CommonReferences="true" AssemblyName="ClassLibrary6"/> <Project Language="C#" CommonReferences="true" AssemblyName="ClassLibrary7"/> <Project Language="C#" CommonReferences="true" AssemblyName="ClassLibrary8"/> <Project Language="C#" CommonReferences="true" AssemblyName="ClassLibrary9"/> <Project Language="C#" CommonReferences="true" AssemblyName="TestAssembly"> <Document FilePath="C.cs"> // Code comment using System.Runtime.CompilerServices; using System.Reflection; using IVT = System.Runtime.CompilerServices.InternalsVisibleToAttribute; // Code comment [assembly: InternalsVisibleTo("ClassLibrary1", AllInternalsVisible = true)] [assembly: InternalsVisibleTo(assemblyName: "ClassLibrary2", AllInternalsVisible = true)] [assembly: AssemblyVersion("1.0.0.0"), InternalsVisibleTo("ClassLibrary3")] [assembly: InternalsVisibleTo("ClassLibrary4"), AssemblyCopyright("Copyright")] [assembly: AssemblyDescription("Description")] [assembly: InternalsVisibleTo("ClassLibrary5")] [assembly: InternalsVisibleTo("ClassLibrary6, PublicKey=00240000048000009400000006020000002400005253413100040000010001002b986f6b5ea5717d35c72d38561f413e267029efa9b5f107b9331d83df657381325b3a67b75812f63a9436ceccb49494de8f574f8e639d4d26c0fcf8b0e9a1a196b80b6f6ed053628d10d027e032df2ed1d60835e5f47d32c9ef6da10d0366a319573362c821b5f8fa5abc5bb22241de6f666a85d82d6ba8c3090d01636bd2bb")] [assembly: InternalsVisibleTo("ClassLibrary" + "7")] [assembly: IVT("ClassLibrary8")] [assembly: InternalsVisibleTo("$$ namespace A { public class A { } } </Document> </Project> </Workspace>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendInvokeCompletionList() Await state.AssertCompletionItemsDoNotContainAny("ClassLibrary1", "ClassLibrary2", "ClassLibrary3", "ClassLibrary4", "ClassLibrary5", "ClassLibrary6", "ClassLibrary7", "ClassLibrary8") Await state.AssertCompletionItemsContainAll("ClassLibrary9") End Using End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function CodeCompletionContainsOnlyAssembliesThatAreNotAlreadyIVTWithSyntaxError(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateTestStateFromWorkspace( <Workspace> <Project Language="C#" CommonReferences="true" AssemblyName="ClassLibrary1"/> <Project Language="C#" CommonReferences="true" AssemblyName="TestAssembly"> <Document FilePath="C.cs"> using System.Runtime.CompilerServices; using System.Reflection; [assembly: InternalsVisibleTo("ClassLibrary" + 1)] // Not a constant [assembly: InternalsVisibleTo("$$ </Document> </Project> </Workspace>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendInvokeCompletionList() ' ClassLibrary1 must be listed because the existing attribute argument can't be resolved to a constant. Await state.AssertCompletionItemsContainAll("ClassLibrary1") End Using End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function CodeCompletionContainsOnlyAssembliesThatAreNotAlreadyIVTWithMoreThanOneDocument(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateTestStateFromWorkspace( <Workspace> <Project Language="C#" CommonReferences="true" AssemblyName="ClassLibrary1"/> <Project Language="C#" CommonReferences="true" AssemblyName="ClassLibrary2"/> <Project Language="C#" CommonReferences="true" AssemblyName="TestAssembly"> <Document FilePath="OtherDocument.cs"> using System.Runtime.CompilerServices; using System.Reflection; [assembly: InternalsVisibleTo("ClassLibrary1")] [assembly: AssemblyDescription("Description")] </Document> <Document FilePath="C.cs"> using System.Runtime.CompilerServices; using System.Reflection; [assembly: InternalsVisibleTo("$$ </Document> </Project> </Workspace>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendInvokeCompletionList() Await state.AssertCompletionItemsDoNotContainAny("ClassLibrary1") Await state.AssertCompletionItemsContainAll("ClassLibrary2") End Using End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function CodeCompletionIgnoresUnsupportedProjectTypes(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateTestStateFromWorkspace( <Workspace> <Project Language="NoCompilation" AssemblyName="ClassLibrary1"/> <Project Language="C#" CommonReferences="true" AssemblyName="TestAssembly"> <Document FilePath="C.cs"> using System.Runtime.CompilerServices; using System.Reflection; [assembly: InternalsVisibleTo("$$ </Document> </Project> </Workspace>, extraExportedTypes:={GetType(NoCompilationContentTypeDefinitions), GetType(NoCompilationContentTypeLanguageService)}, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendInvokeCompletionList() Await state.AssertNoCompletionSession() End Using End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Completion)> <WorkItem(29447, "https://github.com/dotnet/roslyn/pull/29447")> Public Async Function CodeCompletionReplacesExisitingAssemblyNameWithDots_1(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateTestStateFromWorkspace( <Workspace> <Project Language="C#" AssemblyName="Dotted.Assembly.Name"/> <Project Language="C#" CommonReferences="true" AssemblyName="TestAssembly"> <Document FilePath="C.cs"> [assembly: System.Runtime.CompilerServices.InternalsVisibleTo("Dotted.Assem$$bly")] </Document> </Project> </Workspace>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendInvokeCompletionList() Await state.AssertSelectedCompletionItem("Dotted.Assembly.Name") state.SendTab() state.AssertMatchesTextStartingAtLine(1, "[assembly: System.Runtime.CompilerServices.InternalsVisibleTo(""Dotted.Assembly.Name"")]") End Using End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Completion)> <WorkItem(29447, "https://github.com/dotnet/roslyn/pull/29447")> Public Async Function CodeCompletionReplacesExisitingAssemblyNameWithDots_2(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateTestStateFromWorkspace( <Workspace> <Project Language="C#" AssemblyName="Dotted.Assembly.Name"/> <Project Language="C#" CommonReferences="true" AssemblyName="TestAssembly"> <Document FilePath="C.cs"> [assembly: System.Runtime.CompilerServices.InternalsVisibleTo("Dotted.Assem$$bly </Document> </Project> </Workspace>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendInvokeCompletionList() Await state.AssertSelectedCompletionItem("Dotted.Assembly.Name") state.SendTab() state.AssertMatchesTextStartingAtLine(1, "[assembly: System.Runtime.CompilerServices.InternalsVisibleTo(""Dotted.Assembly.Name") End Using End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Completion)> <WorkItem(29447, "https://github.com/dotnet/roslyn/pull/29447")> Public Async Function CodeCompletionReplacesExisitingAssemblyNameWithDots_3(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateTestStateFromWorkspace( <Workspace> <Project Language="C#" AssemblyName="Dotted.Assembly.Name"/> <Project Language="C#" CommonReferences="true" AssemblyName="TestAssembly"> <Document FilePath="C.cs"> [assembly: System.Runtime.CompilerServices.InternalsVisibleTo(" Dotted.Assem$$bly ")] </Document> </Project> </Workspace>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendInvokeCompletionList() Await state.AssertSelectedCompletionItem("Dotted.Assembly.Name") state.SendTab() state.AssertMatchesTextStartingAtLine(1, "[assembly: System.Runtime.CompilerServices.InternalsVisibleTo(""Dotted.Assembly.Name"")]") End Using End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Completion)> <WorkItem(29447, "https://github.com/dotnet/roslyn/pull/29447")> Public Async Function CodeCompletionReplacesExisitingAssemblyNameWithDots_4(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateTestStateFromWorkspace( <Workspace> <Project Language="C#" AssemblyName="Dotted1.Dotted2.Assembly.Dotted3"/> <Project Language="C#" CommonReferences="true" AssemblyName="TestAssembly"> <Document FilePath="C.cs"> [assembly: System.Runtime.CompilerServices.InternalsVisibleTo("Dotted1.Dotted2.Assem$$bly.Dotted")] </Document> </Project> </Workspace>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendInvokeCompletionList() Await state.AssertSelectedCompletionItem("Dotted1.Dotted2.Assembly.Dotted3") state.SendTab() state.AssertMatchesTextStartingAtLine(1, "[assembly: System.Runtime.CompilerServices.InternalsVisibleTo(""Dotted1.Dotted2.Assembly.Dotted3"")]") End Using End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Completion)> <WorkItem(29447, "https://github.com/dotnet/roslyn/pull/29447")> Public Async Function CodeCompletionReplacesExisitingAssemblyNameWithDots_Verbatim_1(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateTestStateFromWorkspace( <Workspace> <Project Language="C#" AssemblyName="Dotted1.Dotted2.Assembly.Dotted3"/> <Project Language="C#" CommonReferences="true" AssemblyName="TestAssembly"> <Document FilePath="C.cs"> [assembly: System.Runtime.CompilerServices.InternalsVisibleTo(@"Dotted1.Dotted2.Assem$$bly.Dotted")] </Document> </Project> </Workspace>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendInvokeCompletionList() Await state.AssertSelectedCompletionItem("Dotted1.Dotted2.Assembly.Dotted3") state.SendTab() state.AssertMatchesTextStartingAtLine(1, "[assembly: System.Runtime.CompilerServices.InternalsVisibleTo(@""Dotted1.Dotted2.Assembly.Dotted3"")]") End Using End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Completion)> <WorkItem(29447, "https://github.com/dotnet/roslyn/pull/29447")> Public Async Function CodeCompletionReplacesExisitingAssemblyNameWithDots_Verbatim_2(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateTestStateFromWorkspace( <Workspace> <Project Language="C#" AssemblyName="Dotted1.Dotted2.Assembly.Dotted3"/> <Project Language="C#" CommonReferences="true" AssemblyName="TestAssembly"> <Document FilePath="C.cs"> [assembly: System.Runtime.CompilerServices.InternalsVisibleTo(@"Dotted1.Dotted2.Assem$$bly </Document> </Project> </Workspace>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendInvokeCompletionList() Await state.AssertSelectedCompletionItem("Dotted1.Dotted2.Assembly.Dotted3") state.SendTab() state.AssertMatchesTextStartingAtLine(1, "[assembly: System.Runtime.CompilerServices.InternalsVisibleTo(@""Dotted1.Dotted2.Assembly.Dotted3") End Using End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Completion)> <WorkItem(29447, "https://github.com/dotnet/roslyn/pull/29447")> Public Async Function CodeCompletionReplacesExisitingAssemblyNameWithDots_EscapeSequence_1(showCompletionInArgumentLists As Boolean) As Task ' Escaped double quotes are not handled properly: The selection is expanded from the cursor position until ' a double quote or new line is reached. But because double quotes are not allowed in this context this ' case is rare enough to ignore. Supporting it would require more complicated code that was reverted in ' https://github.com/dotnet/roslyn/pull/29447/commits/e7a852a7e83fffe1f25a8dee0aaec68f67fcc1d8 Using state = TestStateFactory.CreateTestStateFromWorkspace( <Workspace> <Project Language="C#" AssemblyName="Dotted1.Dotted2.Assembly.Dotted3"/> <Project Language="C#" CommonReferences="true" AssemblyName="TestAssembly"> <Document FilePath="C.cs"> [assembly: System.Runtime.CompilerServices.InternalsVisibleTo("\"Dotted1.Dotted2.Assem$$bly\"")] </Document> </Project> </Workspace>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendInvokeCompletionList() Await state.AssertSelectedCompletionItem("Dotted1.Dotted2.Assembly.Dotted3") state.SendTab() state.AssertMatchesTextStartingAtLine(1, "[assembly: System.Runtime.CompilerServices.InternalsVisibleTo(""\""Dotted1.Dotted2.Assembly.Dotted3"""")]") End Using End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Completion)> <WorkItem(29447, "https://github.com/dotnet/roslyn/pull/29447")> Public Async Function CodeCompletionReplacesExisitingAssemblyNameWithDots_OpenEnded(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateTestStateFromWorkspace( <Workspace> <Project Language="C#" AssemblyName="Dotted1.Dotted2.Assembly.Dotted3"/> <Project Language="C#" CommonReferences="true" AssemblyName="TestAssembly"> <Document FilePath="C.cs"> [assembly: System.Runtime.CompilerServices.InternalsVisibleTo("Dotted1.Dotted2.Assem$$bly.Dotted4 </Document> </Project> </Workspace>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendInvokeCompletionList() Await state.AssertSelectedCompletionItem("Dotted1.Dotted2.Assembly.Dotted3") state.SendTab() state.AssertMatchesTextStartingAtLine(1, "[assembly: System.Runtime.CompilerServices.InternalsVisibleTo(""Dotted1.Dotted2.Assembly.Dotted3") End Using End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Completion)> <WorkItem(29447, "https://github.com/dotnet/roslyn/pull/29447")> Public Async Function CodeCompletionReplacesExisitingAssemblyNameWithDots_AndPublicKey_OpenEnded(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateTestStateFromWorkspace( <Workspace> <Project Language="C#" AssemblyName="Dotted1.Dotted2.Assembly.Dotted3"/> <Project Language="C#" CommonReferences="true" AssemblyName="TestAssembly"> <Document FilePath="C.cs"> [assembly: System.Runtime.CompilerServices.InternalsVisibleTo("Company.Asse$$mbly, PublicKey=123 </Document> </Project> </Workspace>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendInvokeCompletionList() Await state.AssertSelectedCompletionItem("Dotted1.Dotted2.Assembly.Dotted3") state.SendTab() state.AssertMatchesTextStartingAtLine(1, "[assembly: System.Runtime.CompilerServices.InternalsVisibleTo(""Dotted1.Dotted2.Assembly.Dotted3") End Using End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Completion)> <WorkItem(29447, "https://github.com/dotnet/roslyn/pull/29447")> Public Async Function CodeCompletionReplacesExisitingAssemblyNameWithDots_AndPublicKey_LineBreakExampleFromMSDN(showCompletionInArgumentLists As Boolean) As Task ' Source https://msdn.microsoft.com/de-de/library/system.runtime.compilerservices.internalsvisibletoattribute(v=vs.110).aspx Using state = TestStateFactory.CreateTestStateFromWorkspace( <Workspace> <Project Language="C#" AssemblyName="Dotted1.Dotted2.Assembly.Dotted3"/> <Project Language="C#" CommonReferences="true" AssemblyName="TestAssembly"> <Document FilePath="C.cs"> [assembly: System.Runtime.CompilerServices.InternalsVisibleTo("$$Friend1, PublicKey=002400000480000094" + "0000000602000000240000525341310004000" + "001000100bf8c25fcd44838d87e245ab35bf7" + "3ba2615707feea295709559b3de903fb95a93" + "3d2729967c3184a97d7b84c7547cd87e435b5" + "6bdf8621bcb62b59c00c88bd83aa62c4fcdd4" + "712da72eec2533dc00f8529c3a0bbb4103282" + "f0d894d5f34e9f0103c473dce9f4b457a5dee" + "fd8f920d8681ed6dfcb0a81e96bd9b176525a" + "26e0b3")] </Document> </Project> </Workspace>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendInvokeCompletionList() Await state.AssertSelectedCompletionItem("Dotted1.Dotted2.Assembly.Dotted3") state.SendTab() state.AssertMatchesTextStartingAtLine(1, "[assembly: System.Runtime.CompilerServices.InternalsVisibleTo(""Dotted1.Dotted2.Assembly.Dotted3"" +") state.AssertMatchesTextStartingAtLine(2, " ""0000000602000000240000525341310004000"" +") End Using End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Completion)> <WorkItem(29447, "https://github.com/dotnet/roslyn/pull/29447")> Public Async Function CodeCompletionReplacesExisitingAssemblyNameWithDots_OpenEndedStringFollowedByEOF(showCompletionInArgumentLists As Boolean) As Task ' Source https://msdn.microsoft.com/de-de/library/system.runtime.compilerservices.internalsvisibletoattribute(v=vs.110).aspx Using state = TestStateFactory.CreateTestStateFromWorkspace( <Workspace> <Project Language="C#" AssemblyName="Dotted1.Dotted2.Assembly.Dotted3"/> <Project Language="C#" CommonReferences="true" AssemblyName="TestAssembly"> <Document FilePath="C.cs"> [assembly: System.Runtime.CompilerServices.InternalsVisibleTo("Friend1$$</Document> </Project> </Workspace>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendInvokeCompletionList() Await state.AssertSelectedCompletionItem("Dotted1.Dotted2.Assembly.Dotted3") state.SendTab() state.AssertMatchesTextStartingAtLine(1, "[assembly: System.Runtime.CompilerServices.InternalsVisibleTo(""Dotted1.Dotted2.Assembly.Dotted3") End Using End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Completion)> <WorkItem(29447, "https://github.com/dotnet/roslyn/pull/29447")> Public Async Function CodeCompletionReplacesExisitingAssemblyNameWithDots_OpenEndedStringFollowedByNewLines(showCompletionInArgumentLists As Boolean) As Task ' Source https://msdn.microsoft.com/de-de/library/system.runtime.compilerservices.internalsvisibletoattribute(v=vs.110).aspx Using state = TestStateFactory.CreateTestStateFromWorkspace( <Workspace> <Project Language="C#" AssemblyName="Dotted1.Dotted2.Assembly.Dotted3"/> <Project Language="C#" CommonReferences="true" AssemblyName="TestAssembly"> <Document FilePath="C.cs"><![CDATA[ [assembly: System.Runtime.CompilerServices.InternalsVisibleTo("Friend1$$ ]]> </Document> </Project> </Workspace>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendInvokeCompletionList() Await state.AssertSelectedCompletionItem("Dotted1.Dotted2.Assembly.Dotted3") state.SendTab() state.AssertMatchesTextStartingAtLine(1, "[assembly: System.Runtime.CompilerServices.InternalsVisibleTo(""Dotted1.Dotted2.Assembly.Dotted3") state.AssertMatchesTextStartingAtLine(2, "") End Using End Function End Class End Namespace
-1
dotnet/roslyn
55,430
Fix LSP semantic tokens algorithm
This PR primarily accomplishes two tasks: 1) Overhauls the existing LSP semantic tokens edits processing algorithm to align with [Razor's](https://github.com/dotnet/aspnetcore-tooling/blob/main/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/Semantic/Services/SemanticTokensEditsDiffer.cs) (shoutout to Ryan and the rest of the Razor team for writing the original 😄). The main change here is going from calculating edits per token (i.e. five ints) to per int. The updated algorithm is much more efficient than our previous algorithm, and returns less edits back to the LSP client. 2) The interpretation of Roslyn's LongestCommonSubstring algorithm, which we use to calculate raw edits, was missing a critical piece. Namely, for insertions, we need to keep track of _where_ we should be inserting into the original token set. We don't keep track of this in the existing implementation, resulting in bugs such as #54671. Resolves #54671
allisonchou
2021-08-05T06:06:43Z
2021-08-06T23:44:44Z
b9200d03a76c74d404040d44b9bbe12b1d0a8ef2
f300a818940ea1acef66c946cfa83756729d5e59
Fix LSP semantic tokens algorithm. This PR primarily accomplishes two tasks: 1) Overhauls the existing LSP semantic tokens edits processing algorithm to align with [Razor's](https://github.com/dotnet/aspnetcore-tooling/blob/main/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/Semantic/Services/SemanticTokensEditsDiffer.cs) (shoutout to Ryan and the rest of the Razor team for writing the original 😄). The main change here is going from calculating edits per token (i.e. five ints) to per int. The updated algorithm is much more efficient than our previous algorithm, and returns less edits back to the LSP client. 2) The interpretation of Roslyn's LongestCommonSubstring algorithm, which we use to calculate raw edits, was missing a critical piece. Namely, for insertions, we need to keep track of _where_ we should be inserting into the original token set. We don't keep track of this in the existing implementation, resulting in bugs such as #54671. Resolves #54671
./src/VisualStudio/Core/Def/Implementation/CallHierarchy/CallHierarchyProvider.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.ComponentModel.Composition; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Editor.Implementation.CallHierarchy.Finders; using Microsoft.CodeAnalysis.Editor.Shared.Extensions; using Microsoft.CodeAnalysis.FindSymbols; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Navigation; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Shared.TestHooks; using Microsoft.VisualStudio.Language.CallHierarchy; using Microsoft.VisualStudio.Language.Intellisense; using Microsoft.VisualStudio.LanguageServices.Implementation.Utilities; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Editor.Implementation.CallHierarchy { [Export(typeof(CallHierarchyProvider))] internal partial class CallHierarchyProvider { private readonly IAsynchronousOperationListener _asyncListener; public IGlyphService GlyphService { get; } [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public CallHierarchyProvider( IAsynchronousOperationListenerProvider listenerProvider, IGlyphService glyphService) { _asyncListener = listenerProvider.GetListener(FeatureAttribute.CallHierarchy); this.GlyphService = glyphService; } public async Task<ICallHierarchyMemberItem> CreateItemAsync(ISymbol symbol, Project project, IEnumerable<Location> callsites, CancellationToken cancellationToken) { if (symbol.Kind == SymbolKind.Method || symbol.Kind == SymbolKind.Property || symbol.Kind == SymbolKind.Event || symbol.Kind == SymbolKind.Field) { symbol = GetTargetSymbol(symbol); var finders = await CreateFindersAsync(symbol, project, cancellationToken).ConfigureAwait(false); ICallHierarchyMemberItem item = new CallHierarchyItem(symbol, project.Id, finders, () => symbol.GetGlyph().GetImageSource(GlyphService), this, callsites, project.Solution.Workspace); return item; } return null; } private ISymbol GetTargetSymbol(ISymbol symbol) { if (symbol is IMethodSymbol methodSymbol) { methodSymbol = methodSymbol.ReducedFrom ?? methodSymbol; methodSymbol = methodSymbol.ConstructedFrom ?? methodSymbol; return methodSymbol; } return symbol; } public FieldInitializerItem CreateInitializerItem(IEnumerable<CallHierarchyDetail> details) { return new FieldInitializerItem(EditorFeaturesResources.Initializers, "__" + EditorFeaturesResources.Initializers, Glyph.FieldPublic.GetImageSource(GlyphService), details); } public async Task<IEnumerable<AbstractCallFinder>> CreateFindersAsync(ISymbol symbol, Project project, CancellationToken cancellationToken) { if (symbol.Kind == SymbolKind.Property || symbol.Kind == SymbolKind.Event || symbol.Kind == SymbolKind.Method) { var finders = new List<AbstractCallFinder>(); finders.Add(new MethodCallFinder(symbol, project.Id, _asyncListener, this)); if (symbol.IsVirtual || symbol.IsAbstract) { finders.Add(new OverridingMemberFinder(symbol, project.Id, _asyncListener, this)); } var @overrides = await SymbolFinder.FindOverridesAsync(symbol, project.Solution, cancellationToken: cancellationToken).ConfigureAwait(false); if (overrides.Any()) { finders.Add(new CallToOverrideFinder(symbol, project.Id, _asyncListener, this)); } if (symbol.GetOverriddenMember() != null) { finders.Add(new BaseMemberFinder(symbol.GetOverriddenMember(), project.Id, _asyncListener, this)); } var implementedInterfaceMembers = await SymbolFinder.FindImplementedInterfaceMembersAsync(symbol, project.Solution, cancellationToken: cancellationToken).ConfigureAwait(false); foreach (var implementedInterfaceMember in implementedInterfaceMembers) { finders.Add(new InterfaceImplementationCallFinder(implementedInterfaceMember, project.Id, _asyncListener, this)); } if (symbol.IsImplementableMember()) { finders.Add(new ImplementerFinder(symbol, project.Id, _asyncListener, this)); } return finders; } if (symbol.Kind == SymbolKind.Field) { return SpecializedCollections.SingletonEnumerable(new FieldReferenceFinder(symbol, project.Id, _asyncListener, this)); } return null; } public void NavigateTo(SymbolKey id, Project project, CancellationToken cancellationToken) { var compilation = project.GetCompilationAsync(cancellationToken).WaitAndGetResult(cancellationToken); var resolution = id.Resolve(compilation, cancellationToken: cancellationToken); var workspace = project.Solution.Workspace; var options = workspace.Options.WithChangedOption(NavigationOptions.PreferProvisionalTab, true); var symbolNavigationService = workspace.Services.GetService<ISymbolNavigationService>(); symbolNavigationService.TryNavigateToSymbol(resolution.Symbol, project, options, cancellationToken); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.ComponentModel.Composition; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Editor.Implementation.CallHierarchy.Finders; using Microsoft.CodeAnalysis.Editor.Shared.Extensions; using Microsoft.CodeAnalysis.FindSymbols; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Navigation; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Shared.TestHooks; using Microsoft.VisualStudio.Language.CallHierarchy; using Microsoft.VisualStudio.Language.Intellisense; using Microsoft.VisualStudio.LanguageServices.Implementation.Utilities; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Editor.Implementation.CallHierarchy { [Export(typeof(CallHierarchyProvider))] internal partial class CallHierarchyProvider { private readonly IAsynchronousOperationListener _asyncListener; public IGlyphService GlyphService { get; } [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public CallHierarchyProvider( IAsynchronousOperationListenerProvider listenerProvider, IGlyphService glyphService) { _asyncListener = listenerProvider.GetListener(FeatureAttribute.CallHierarchy); this.GlyphService = glyphService; } public async Task<ICallHierarchyMemberItem> CreateItemAsync(ISymbol symbol, Project project, IEnumerable<Location> callsites, CancellationToken cancellationToken) { if (symbol.Kind == SymbolKind.Method || symbol.Kind == SymbolKind.Property || symbol.Kind == SymbolKind.Event || symbol.Kind == SymbolKind.Field) { symbol = GetTargetSymbol(symbol); var finders = await CreateFindersAsync(symbol, project, cancellationToken).ConfigureAwait(false); ICallHierarchyMemberItem item = new CallHierarchyItem(symbol, project.Id, finders, () => symbol.GetGlyph().GetImageSource(GlyphService), this, callsites, project.Solution.Workspace); return item; } return null; } private ISymbol GetTargetSymbol(ISymbol symbol) { if (symbol is IMethodSymbol methodSymbol) { methodSymbol = methodSymbol.ReducedFrom ?? methodSymbol; methodSymbol = methodSymbol.ConstructedFrom ?? methodSymbol; return methodSymbol; } return symbol; } public FieldInitializerItem CreateInitializerItem(IEnumerable<CallHierarchyDetail> details) { return new FieldInitializerItem(EditorFeaturesResources.Initializers, "__" + EditorFeaturesResources.Initializers, Glyph.FieldPublic.GetImageSource(GlyphService), details); } public async Task<IEnumerable<AbstractCallFinder>> CreateFindersAsync(ISymbol symbol, Project project, CancellationToken cancellationToken) { if (symbol.Kind == SymbolKind.Property || symbol.Kind == SymbolKind.Event || symbol.Kind == SymbolKind.Method) { var finders = new List<AbstractCallFinder>(); finders.Add(new MethodCallFinder(symbol, project.Id, _asyncListener, this)); if (symbol.IsVirtual || symbol.IsAbstract) { finders.Add(new OverridingMemberFinder(symbol, project.Id, _asyncListener, this)); } var @overrides = await SymbolFinder.FindOverridesAsync(symbol, project.Solution, cancellationToken: cancellationToken).ConfigureAwait(false); if (overrides.Any()) { finders.Add(new CallToOverrideFinder(symbol, project.Id, _asyncListener, this)); } if (symbol.GetOverriddenMember() != null) { finders.Add(new BaseMemberFinder(symbol.GetOverriddenMember(), project.Id, _asyncListener, this)); } var implementedInterfaceMembers = await SymbolFinder.FindImplementedInterfaceMembersAsync(symbol, project.Solution, cancellationToken: cancellationToken).ConfigureAwait(false); foreach (var implementedInterfaceMember in implementedInterfaceMembers) { finders.Add(new InterfaceImplementationCallFinder(implementedInterfaceMember, project.Id, _asyncListener, this)); } if (symbol.IsImplementableMember()) { finders.Add(new ImplementerFinder(symbol, project.Id, _asyncListener, this)); } return finders; } if (symbol.Kind == SymbolKind.Field) { return SpecializedCollections.SingletonEnumerable(new FieldReferenceFinder(symbol, project.Id, _asyncListener, this)); } return null; } public void NavigateTo(SymbolKey id, Project project, CancellationToken cancellationToken) { var compilation = project.GetCompilationAsync(cancellationToken).WaitAndGetResult(cancellationToken); var resolution = id.Resolve(compilation, cancellationToken: cancellationToken); var workspace = project.Solution.Workspace; var options = workspace.Options.WithChangedOption(NavigationOptions.PreferProvisionalTab, true); var symbolNavigationService = workspace.Services.GetService<ISymbolNavigationService>(); symbolNavigationService.TryNavigateToSymbol(resolution.Symbol, project, options, cancellationToken); } } }
-1
dotnet/roslyn
55,430
Fix LSP semantic tokens algorithm
This PR primarily accomplishes two tasks: 1) Overhauls the existing LSP semantic tokens edits processing algorithm to align with [Razor's](https://github.com/dotnet/aspnetcore-tooling/blob/main/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/Semantic/Services/SemanticTokensEditsDiffer.cs) (shoutout to Ryan and the rest of the Razor team for writing the original 😄). The main change here is going from calculating edits per token (i.e. five ints) to per int. The updated algorithm is much more efficient than our previous algorithm, and returns less edits back to the LSP client. 2) The interpretation of Roslyn's LongestCommonSubstring algorithm, which we use to calculate raw edits, was missing a critical piece. Namely, for insertions, we need to keep track of _where_ we should be inserting into the original token set. We don't keep track of this in the existing implementation, resulting in bugs such as #54671. Resolves #54671
allisonchou
2021-08-05T06:06:43Z
2021-08-06T23:44:44Z
b9200d03a76c74d404040d44b9bbe12b1d0a8ef2
f300a818940ea1acef66c946cfa83756729d5e59
Fix LSP semantic tokens algorithm. This PR primarily accomplishes two tasks: 1) Overhauls the existing LSP semantic tokens edits processing algorithm to align with [Razor's](https://github.com/dotnet/aspnetcore-tooling/blob/main/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/Semantic/Services/SemanticTokensEditsDiffer.cs) (shoutout to Ryan and the rest of the Razor team for writing the original 😄). The main change here is going from calculating edits per token (i.e. five ints) to per int. The updated algorithm is much more efficient than our previous algorithm, and returns less edits back to the LSP client. 2) The interpretation of Roslyn's LongestCommonSubstring algorithm, which we use to calculate raw edits, was missing a critical piece. Namely, for insertions, we need to keep track of _where_ we should be inserting into the original token set. We don't keep track of this in the existing implementation, resulting in bugs such as #54671. Resolves #54671
./src/Compilers/VisualBasic/Portable/Parser/BlockContexts/DoLoopBlockContext.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax '----------------------------------------------------------------------------- ' Contains the definition of the BlockContext '----------------------------------------------------------------------------- Namespace Microsoft.CodeAnalysis.VisualBasic.Syntax.InternalSyntax Friend NotInheritable Class DoLoopBlockContext Inherits ExecutableStatementContext Friend Sub New(statement As StatementSyntax, prevContext As BlockContext) MyBase.New(If(DirectCast(statement, DoStatementSyntax).WhileOrUntilClause Is Nothing, SyntaxKind.SimpleDoLoopBlock, SyntaxKind.DoWhileLoopBlock), statement, prevContext) End Sub Friend Overrides Function CreateBlockSyntax(statement As StatementSyntax) As VisualBasicSyntaxNode Dim doStmt As DoStatementSyntax = Nothing Dim loopStmt As LoopStatementSyntax = DirectCast(statement, LoopStatementSyntax) GetBeginEndStatements(doStmt, loopStmt) Dim kind As SyntaxKind = BlockKind If kind = SyntaxKind.DoWhileLoopBlock AndAlso loopStmt.WhileOrUntilClause IsNot Nothing Then Dim whileUntilClause = loopStmt.WhileOrUntilClause ' Error: the loop has a condition in both header and trailer. Dim keyword = Parser.ReportSyntaxError(whileUntilClause.WhileOrUntilKeyword, ERRID.ERR_LoopDoubleCondition) Dim errors = whileUntilClause.GetDiagnostics whileUntilClause = SyntaxFactory.WhileOrUntilClause(whileUntilClause.Kind, DirectCast(keyword, KeywordSyntax), whileUntilClause.Condition) If errors IsNot Nothing Then whileUntilClause = DirectCast(whileUntilClause.SetDiagnostics(errors), WhileOrUntilClauseSyntax) End If loopStmt = SyntaxFactory.LoopStatement(loopStmt.Kind, loopStmt.LoopKeyword, whileUntilClause) End If If kind = SyntaxKind.SimpleDoLoopBlock AndAlso loopStmt.WhileOrUntilClause IsNot Nothing Then ' Set the Do Loop kind now that the bottom is known. kind = If(loopStmt.Kind = SyntaxKind.LoopWhileStatement, SyntaxKind.DoLoopWhileBlock, SyntaxKind.DoLoopUntilBlock) ElseIf doStmt.WhileOrUntilClause IsNot Nothing Then kind = If(doStmt.Kind = SyntaxKind.DoWhileStatement, SyntaxKind.DoWhileLoopBlock, SyntaxKind.DoUntilLoopBlock) End If Dim result = SyntaxFactory.DoLoopBlock(kind, doStmt, Body(), loopStmt) FreeStatements() Return result End Function Friend Overrides Function KindEndsBlock(kind As SyntaxKind) As Boolean Select Case kind Case SyntaxKind.SimpleLoopStatement, SyntaxKind.LoopWhileStatement, SyntaxKind.LoopUntilStatement Return True Case Else Return False End Select 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.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax '----------------------------------------------------------------------------- ' Contains the definition of the BlockContext '----------------------------------------------------------------------------- Namespace Microsoft.CodeAnalysis.VisualBasic.Syntax.InternalSyntax Friend NotInheritable Class DoLoopBlockContext Inherits ExecutableStatementContext Friend Sub New(statement As StatementSyntax, prevContext As BlockContext) MyBase.New(If(DirectCast(statement, DoStatementSyntax).WhileOrUntilClause Is Nothing, SyntaxKind.SimpleDoLoopBlock, SyntaxKind.DoWhileLoopBlock), statement, prevContext) End Sub Friend Overrides Function CreateBlockSyntax(statement As StatementSyntax) As VisualBasicSyntaxNode Dim doStmt As DoStatementSyntax = Nothing Dim loopStmt As LoopStatementSyntax = DirectCast(statement, LoopStatementSyntax) GetBeginEndStatements(doStmt, loopStmt) Dim kind As SyntaxKind = BlockKind If kind = SyntaxKind.DoWhileLoopBlock AndAlso loopStmt.WhileOrUntilClause IsNot Nothing Then Dim whileUntilClause = loopStmt.WhileOrUntilClause ' Error: the loop has a condition in both header and trailer. Dim keyword = Parser.ReportSyntaxError(whileUntilClause.WhileOrUntilKeyword, ERRID.ERR_LoopDoubleCondition) Dim errors = whileUntilClause.GetDiagnostics whileUntilClause = SyntaxFactory.WhileOrUntilClause(whileUntilClause.Kind, DirectCast(keyword, KeywordSyntax), whileUntilClause.Condition) If errors IsNot Nothing Then whileUntilClause = DirectCast(whileUntilClause.SetDiagnostics(errors), WhileOrUntilClauseSyntax) End If loopStmt = SyntaxFactory.LoopStatement(loopStmt.Kind, loopStmt.LoopKeyword, whileUntilClause) End If If kind = SyntaxKind.SimpleDoLoopBlock AndAlso loopStmt.WhileOrUntilClause IsNot Nothing Then ' Set the Do Loop kind now that the bottom is known. kind = If(loopStmt.Kind = SyntaxKind.LoopWhileStatement, SyntaxKind.DoLoopWhileBlock, SyntaxKind.DoLoopUntilBlock) ElseIf doStmt.WhileOrUntilClause IsNot Nothing Then kind = If(doStmt.Kind = SyntaxKind.DoWhileStatement, SyntaxKind.DoWhileLoopBlock, SyntaxKind.DoUntilLoopBlock) End If Dim result = SyntaxFactory.DoLoopBlock(kind, doStmt, Body(), loopStmt) FreeStatements() Return result End Function Friend Overrides Function KindEndsBlock(kind As SyntaxKind) As Boolean Select Case kind Case SyntaxKind.SimpleLoopStatement, SyntaxKind.LoopWhileStatement, SyntaxKind.LoopUntilStatement Return True Case Else Return False End Select End Function End Class End Namespace
-1
dotnet/roslyn
55,430
Fix LSP semantic tokens algorithm
This PR primarily accomplishes two tasks: 1) Overhauls the existing LSP semantic tokens edits processing algorithm to align with [Razor's](https://github.com/dotnet/aspnetcore-tooling/blob/main/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/Semantic/Services/SemanticTokensEditsDiffer.cs) (shoutout to Ryan and the rest of the Razor team for writing the original 😄). The main change here is going from calculating edits per token (i.e. five ints) to per int. The updated algorithm is much more efficient than our previous algorithm, and returns less edits back to the LSP client. 2) The interpretation of Roslyn's LongestCommonSubstring algorithm, which we use to calculate raw edits, was missing a critical piece. Namely, for insertions, we need to keep track of _where_ we should be inserting into the original token set. We don't keep track of this in the existing implementation, resulting in bugs such as #54671. Resolves #54671
allisonchou
2021-08-05T06:06:43Z
2021-08-06T23:44:44Z
b9200d03a76c74d404040d44b9bbe12b1d0a8ef2
f300a818940ea1acef66c946cfa83756729d5e59
Fix LSP semantic tokens algorithm. This PR primarily accomplishes two tasks: 1) Overhauls the existing LSP semantic tokens edits processing algorithm to align with [Razor's](https://github.com/dotnet/aspnetcore-tooling/blob/main/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/Semantic/Services/SemanticTokensEditsDiffer.cs) (shoutout to Ryan and the rest of the Razor team for writing the original 😄). The main change here is going from calculating edits per token (i.e. five ints) to per int. The updated algorithm is much more efficient than our previous algorithm, and returns less edits back to the LSP client. 2) The interpretation of Roslyn's LongestCommonSubstring algorithm, which we use to calculate raw edits, was missing a critical piece. Namely, for insertions, we need to keep track of _where_ we should be inserting into the original token set. We don't keep track of this in the existing implementation, resulting in bugs such as #54671. Resolves #54671
./src/Compilers/VisualBasic/Portable/Symbols/Symbol_Attributes.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Generic Imports System.Collections.Immutable Imports System.Runtime.InteropServices Imports System.Threading Imports Microsoft.CodeAnalysis.PooledObjects Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports TypeKind = Microsoft.CodeAnalysis.TypeKind Namespace Microsoft.CodeAnalysis.VisualBasic Partial Friend Class Symbol ' !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! ' Changes to the public interface of this class should remain synchronized with the C# version of Symbol. ' Do not make any changes to the public interface without making the corresponding change ' to the C# version. ' !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! ''' <summary> ''' Gets the attributes on this symbol. Returns an empty ImmutableArray if there are ''' no attributes. ''' </summary> Public Overridable Function GetAttributes() As ImmutableArray(Of VisualBasicAttributeData) Return ImmutableArray(Of VisualBasicAttributeData).Empty End Function ''' <summary> ''' Build and add synthesized attributes for this symbol. ''' </summary> Friend Overridable Sub AddSynthesizedAttributes(compilationState As ModuleCompilationState, ByRef attributes As ArrayBuilder(Of SynthesizedAttributeData)) End Sub ''' <summary> ''' Convenience helper called by subclasses to add a synthesized attribute to a collection of attributes. ''' </summary> Friend Shared Sub AddSynthesizedAttribute(ByRef attributes As ArrayBuilder(Of SynthesizedAttributeData), attribute As SynthesizedAttributeData) If attribute IsNot Nothing Then If attributes Is Nothing Then attributes = ArrayBuilder(Of SynthesizedAttributeData).GetInstance(4) End If attributes.Add(attribute) End If End Sub ''' <summary> ''' Returns the appropriate AttributeTarget for a symbol. This is used to validate attribute usage when ''' applying an attribute to a symbol. For any symbol that does not support the application of custom ''' attributes 0 is returned. ''' </summary> ''' <returns>The attribute target flag for this symbol or 0 if none apply.</returns> ''' <remarks></remarks> Friend Function GetAttributeTarget() As AttributeTargets Select Case Kind Case SymbolKind.Assembly Return AttributeTargets.Assembly Case SymbolKind.Event Return AttributeTargets.Event Case SymbolKind.Field Return AttributeTargets.Field Case SymbolKind.Method Dim method = DirectCast(Me, MethodSymbol) Select Case method.MethodKind Case MethodKind.Constructor, MethodKind.SharedConstructor Return AttributeTargets.Constructor Case MethodKind.Ordinary, MethodKind.DeclareMethod, MethodKind.UserDefinedOperator, MethodKind.Conversion, MethodKind.PropertyGet, MethodKind.PropertySet, MethodKind.EventAdd, MethodKind.EventRaise, MethodKind.EventRemove, MethodKind.DelegateInvoke Return AttributeTargets.Method End Select Case SymbolKind.Property Return AttributeTargets.Property Case SymbolKind.NamedType Dim namedType = DirectCast(Me, NamedTypeSymbol) Select Case namedType.TypeKind Case TypeKind.Class, TypeKind.Module Return AttributeTargets.Class Case TypeKind.Structure Return AttributeTargets.Struct Case TypeKind.Interface Return AttributeTargets.Interface Case TypeKind.Enum Return AttributeTargets.Enum Or AttributeTargets.Struct Case TypeKind.Delegate Return AttributeTargets.Delegate Case TypeKind.Submission ' attributes can't be applied on a submission type Throw ExceptionUtilities.UnexpectedValue(namedType.TypeKind) End Select Case SymbolKind.NetModule Return AttributeTargets.Module Case SymbolKind.Parameter Return AttributeTargets.Parameter Case SymbolKind.TypeParameter Return AttributeTargets.GenericParameter End Select Return 0 End Function ''' <summary> ''' Method to early decode applied well-known attribute which can be queried by the binder. ''' This method is called during attribute binding after we have bound the attribute types for all attributes, ''' but haven't yet bound the attribute arguments/attribute constructor. ''' Early decoding certain well-known attributes enables the binder to use this decoded information on this symbol ''' when binding the attribute arguments/attribute constructor without causing attribute binding cycle. ''' </summary> Friend Overridable Function EarlyDecodeWellKnownAttribute(ByRef arguments As EarlyDecodeWellKnownAttributeArguments(Of EarlyWellKnownAttributeBinder, NamedTypeSymbol, AttributeSyntax, AttributeLocation)) As VisualBasicAttributeData Return Nothing End Function Friend Function EarlyDecodeDeprecatedOrExperimentalOrObsoleteAttribute( ByRef arguments As EarlyDecodeWellKnownAttributeArguments(Of EarlyWellKnownAttributeBinder, NamedTypeSymbol, AttributeSyntax, AttributeLocation), <Out> ByRef boundAttribute As VisualBasicAttributeData, <Out> ByRef obsoleteData As ObsoleteAttributeData ) As Boolean Dim type = arguments.AttributeType Dim syntax = arguments.AttributeSyntax Dim kind As ObsoleteAttributeKind If VisualBasicAttributeData.IsTargetEarlyAttribute(type, syntax, AttributeDescription.ObsoleteAttribute) Then kind = ObsoleteAttributeKind.Obsolete ElseIf VisualBasicAttributeData.IsTargetEarlyAttribute(type, syntax, AttributeDescription.DeprecatedAttribute) Then kind = ObsoleteAttributeKind.Deprecated ElseIf VisualBasicAttributeData.IsTargetEarlyAttribute(type, syntax, AttributeDescription.ExperimentalAttribute) Then kind = ObsoleteAttributeKind.Experimental Else boundAttribute = Nothing obsoleteData = Nothing Return False End If Dim hasAnyDiagnostics As Boolean = False boundAttribute = arguments.Binder.GetAttribute(syntax, type, hasAnyDiagnostics) If Not boundAttribute.HasErrors Then obsoleteData = boundAttribute.DecodeObsoleteAttribute(kind) If hasAnyDiagnostics Then boundAttribute = Nothing End If Else obsoleteData = Nothing boundAttribute = Nothing End If Return True End Function ''' <summary> ''' This method is called by the binder when it is finished binding a set of attributes on the symbol so that ''' the symbol can extract data from the attribute arguments and potentially perform validation specific to ''' some well known attributes. ''' </summary> ''' <remarks> ''' <para> ''' Symbol types should override this if they want to handle a specific well-known attribute. ''' If the attribute is of a type that the symbol does not wish to handle, it should delegate back to ''' this (base) method. ''' </para> ''' </remarks> Friend Overridable Sub DecodeWellKnownAttribute(ByRef arguments As DecodeWellKnownAttributeArguments(Of AttributeSyntax, VisualBasicAttributeData, AttributeLocation)) Dim compilation = Me.DeclaringCompilation MarkEmbeddedAttributeTypeReference(arguments.Attribute, arguments.AttributeSyntaxOpt, compilation) ReportExtensionAttributeUseSiteInfo(arguments.Attribute, arguments.AttributeSyntaxOpt, compilation, DirectCast(arguments.Diagnostics, BindingDiagnosticBag)) If arguments.Attribute.IsTargetAttribute(Me, AttributeDescription.SkipLocalsInitAttribute) Then DirectCast(arguments.Diagnostics, BindingDiagnosticBag).Add(ERRID.WRN_AttributeNotSupportedInVB, arguments.AttributeSyntaxOpt.Location, AttributeDescription.SkipLocalsInitAttribute.FullName) End If End Sub ''' <summary> ''' Called to report attribute related diagnostics after all attributes have been bound and decoded. ''' Called even if there are no attributes. ''' </summary> ''' <remarks> ''' This method is called by the binder from <see cref="LoadAndValidateAttributes"/> after it has finished binding attributes on the symbol, ''' has executed <see cref="DecodeWellKnownAttribute"/> for attributes applied on the symbol and has stored the decoded data in the ''' lazyCustomAttributesBag on the symbol. Bound attributes haven't been stored on the bag yet. ''' ''' Post-validation for attributes that is dependent on other attributes can be done here. ''' ''' This method should not have any side effects on the symbol, i.e. it SHOULD NOT change the symbol state. ''' </remarks> ''' <param name="boundAttributes">Bound attributes.</param> ''' <param name="allAttributeSyntaxNodes">Syntax nodes of attributes in order they are specified in source.</param> ''' <param name="diagnostics">Diagnostic bag.</param> ''' <param name="symbolPart">Specific part of the symbol to which the attributes apply, or <see cref="AttributeLocation.None"/> if the attributes apply to the symbol itself.</param> ''' <param name="decodedData">Decoded well known attribute data.</param> Friend Overridable Sub PostDecodeWellKnownAttributes(boundAttributes As ImmutableArray(Of VisualBasicAttributeData), allAttributeSyntaxNodes As ImmutableArray(Of AttributeSyntax), diagnostics As BindingDiagnosticBag, symbolPart As AttributeLocation, decodedData As WellKnownAttributeData) End Sub ''' <summary> ''' This method does the following set of operations in the specified order: ''' (1) GetAttributesToBind: Merge the given attributeBlockSyntaxList into a single list of attributes to bind. ''' (2) GetAttributes: Bind the attributes (attribute type, arguments and constructor). ''' (3) DecodeWellKnownAttributes: Decode and validate bound well-known attributes. ''' (4) ValidateAttributes: Perform some additional attribute validations, such as ''' 1) Duplicate attributes, ''' 2) Attribute usage target validation, etc. ''' (5) Store the bound attributes and decoded well-known attribute data in lazyCustomAttributesBag in a thread safe manner. ''' </summary> Friend Sub LoadAndValidateAttributes(attributeBlockSyntaxList As OneOrMany(Of SyntaxList(Of AttributeListSyntax)), ByRef lazyCustomAttributesBag As CustomAttributesBag(Of VisualBasicAttributeData), Optional symbolPart As AttributeLocation = 0) Dim diagnostics = BindingDiagnosticBag.GetInstance() Dim sourceAssembly = DirectCast(If(Me.Kind = SymbolKind.Assembly, Me, Me.ContainingAssembly), SourceAssemblySymbol) Dim sourceModule = sourceAssembly.SourceModule Dim compilation = sourceAssembly.DeclaringCompilation Dim binders As ImmutableArray(Of Binder) = Nothing Dim attributesToBind = GetAttributesToBind(attributeBlockSyntaxList, symbolPart, compilation, binders) Dim boundAttributes As ImmutableArray(Of VisualBasicAttributeData) Dim wellKnownAttrData As WellKnownAttributeData If attributesToBind.Any() Then Debug.Assert(attributesToBind.Any()) Debug.Assert(binders.Any()) Debug.Assert(attributesToBind.Length = binders.Length) ' Initialize the bag so that data decoded from early attributes can be stored onto it. If (lazyCustomAttributesBag Is Nothing) Then Interlocked.CompareExchange(lazyCustomAttributesBag, New CustomAttributesBag(Of VisualBasicAttributeData)(), Nothing) End If Dim boundAttributeTypes As ImmutableArray(Of NamedTypeSymbol) = Binder.BindAttributeTypes(binders, attributesToBind, Me, diagnostics) Dim attributeBuilder = New VisualBasicAttributeData(boundAttributeTypes.Length - 1) {} ' Early bind and decode some well-known attributes. Dim earlyData As EarlyWellKnownAttributeData = Me.EarlyDecodeWellKnownAttributes(binders, boundAttributeTypes, attributesToBind, attributeBuilder, symbolPart) ' Store data decoded from early bound well-known attributes. lazyCustomAttributesBag.SetEarlyDecodedWellKnownAttributeData(earlyData) ' Bind attributes. Binder.GetAttributes(binders, attributesToBind, boundAttributeTypes, attributeBuilder, Me, diagnostics) boundAttributes = attributeBuilder.AsImmutableOrNull ' Validate attribute usage and Decode remaining well-known attributes. wellKnownAttrData = Me.ValidateAttributeUsageAndDecodeWellKnownAttributes(binders, attributesToBind, boundAttributes, diagnostics, symbolPart) ' Store data decoded from remaining well-known attributes. lazyCustomAttributesBag.SetDecodedWellKnownAttributeData(wellKnownAttrData) Else boundAttributes = ImmutableArray(Of VisualBasicAttributeData).Empty wellKnownAttrData = Nothing Interlocked.CompareExchange(lazyCustomAttributesBag, CustomAttributesBag(Of VisualBasicAttributeData).WithEmptyData(), Nothing) End If Me.PostDecodeWellKnownAttributes(boundAttributes, attributesToBind, diagnostics, symbolPart, wellKnownAttrData) ' Store attributes into the bag. sourceModule.AtomicStoreAttributesAndDiagnostics(lazyCustomAttributesBag, boundAttributes, diagnostics) diagnostics.Free() Debug.Assert(lazyCustomAttributesBag.IsSealed) End Sub Private Function GetAttributesToBind(attributeDeclarationSyntaxLists As OneOrMany(Of SyntaxList(Of AttributeListSyntax)), symbolPart As AttributeLocation, compilation As VisualBasicCompilation, <Out> ByRef binders As ImmutableArray(Of Binder)) As ImmutableArray(Of AttributeSyntax) Dim attributeTarget = DirectCast(Me, IAttributeTargetSymbol) Dim sourceModule = DirectCast(compilation.SourceModule, SourceModuleSymbol) Dim syntaxBuilder As ArrayBuilder(Of AttributeSyntax) = Nothing Dim bindersBuilder As ArrayBuilder(Of Binder) = Nothing Dim attributesToBindCount As Integer = 0 For listIndex = 0 To attributeDeclarationSyntaxLists.Count - 1 Dim attributeDeclarationSyntaxList As SyntaxList(Of AttributeListSyntax) = attributeDeclarationSyntaxLists(listIndex) If attributeDeclarationSyntaxList.Any() Then Dim prevCount As Integer = attributesToBindCount For Each attributeDeclarationSyntax In attributeDeclarationSyntaxList For Each attributeSyntax In attributeDeclarationSyntax.Attributes If MatchAttributeTarget(attributeTarget, symbolPart, attributeSyntax.Target) Then If syntaxBuilder Is Nothing Then syntaxBuilder = New ArrayBuilder(Of AttributeSyntax)() bindersBuilder = New ArrayBuilder(Of Binder)() End If syntaxBuilder.Add(attributeSyntax) attributesToBindCount += 1 End If Next Next If attributesToBindCount <> prevCount Then Debug.Assert(attributeDeclarationSyntaxList.Node IsNot Nothing) Debug.Assert(bindersBuilder IsNot Nothing) Dim binder = GetAttributeBinder(attributeDeclarationSyntaxList, sourceModule) For i = 0 To attributesToBindCount - prevCount - 1 bindersBuilder.Add(binder) Next End If End If Next If syntaxBuilder IsNot Nothing Then binders = bindersBuilder.ToImmutableAndFree() Return syntaxBuilder.ToImmutableAndFree() Else binders = ImmutableArray(Of Binder).Empty Return ImmutableArray(Of AttributeSyntax).Empty End If End Function Friend Function GetAttributeBinder(syntaxList As SyntaxList(Of AttributeListSyntax), sourceModule As SourceModuleSymbol) As Binder Dim syntaxTree = syntaxList.Node.SyntaxTree Dim parent = syntaxList.Node.Parent If parent.IsKind(SyntaxKind.AttributesStatement) AndAlso parent.Parent.IsKind(SyntaxKind.CompilationUnit) Then ' Create a binder for the file-level attributes. To avoid infinite recursion, the bound file information ' must be fully computed prior to trying to bind the file attributes. Return BinderBuilder.CreateBinderForProjectLevelNamespace(sourceModule, syntaxTree) Else Return BinderBuilder.CreateBinderForAttribute(sourceModule, syntaxTree, Me) End If End Function Private Shared Function MatchAttributeTarget(attributeTarget As IAttributeTargetSymbol, symbolPart As AttributeLocation, targetOpt As AttributeTargetSyntax) As Boolean If targetOpt Is Nothing Then Return True End If Dim explicitTarget As AttributeLocation ' Parser ensures that an error is reported for anything other than "assembly" or ' "module". Only assembly and module keywords can get here. Select Case targetOpt.AttributeModifier.Kind Case SyntaxKind.AssemblyKeyword explicitTarget = AttributeLocation.Assembly Case SyntaxKind.ModuleKeyword explicitTarget = AttributeLocation.Module Case Else Throw ExceptionUtilities.UnexpectedValue(targetOpt.AttributeModifier.Kind) End Select If symbolPart = 0 Then Return explicitTarget = attributeTarget.DefaultAttributeLocation Else Return explicitTarget = symbolPart End If End Function Private Shared Function GetAttributesToBind(attributeBlockSyntaxList As SyntaxList(Of AttributeListSyntax)) As ImmutableArray(Of AttributeSyntax) Dim attributeSyntaxBuilder As ArrayBuilder(Of AttributeSyntax) = Nothing GetAttributesToBind(attributeBlockSyntaxList, attributeSyntaxBuilder) Return If(attributeSyntaxBuilder IsNot Nothing, attributeSyntaxBuilder.ToImmutableAndFree(), ImmutableArray(Of AttributeSyntax).Empty) End Function Friend Shared Sub GetAttributesToBind(attributeBlockSyntaxList As SyntaxList(Of AttributeListSyntax), ByRef attributeSyntaxBuilder As ArrayBuilder(Of AttributeSyntax)) If attributeBlockSyntaxList.Count > 0 Then If attributeSyntaxBuilder Is Nothing Then attributeSyntaxBuilder = ArrayBuilder(Of AttributeSyntax).GetInstance() End If For Each attributeBlock In attributeBlockSyntaxList attributeSyntaxBuilder.AddRange(attributeBlock.Attributes) Next End If End Sub ''' <summary> ''' Method to early decode certain well-known attributes which can be queried by the binder. ''' This method is called during attribute binding after we have bound the attribute types for all attributes, ''' but haven't yet bound the attribute arguments/attribute constructor. ''' Early decoding certain well-known attributes enables the binder to use this decoded information on this symbol ''' when binding the attribute arguments/attribute constructor without causing attribute binding cycle. ''' </summary> Private Function EarlyDecodeWellKnownAttributes(binders As ImmutableArray(Of Binder), boundAttributeTypes As ImmutableArray(Of NamedTypeSymbol), attributesToBind As ImmutableArray(Of AttributeSyntax), attributeBuilder As VisualBasicAttributeData(), symbolPart As AttributeLocation) As EarlyWellKnownAttributeData Debug.Assert(boundAttributeTypes.Any()) Debug.Assert(attributesToBind.Any()) Dim arguments = New EarlyDecodeWellKnownAttributeArguments(Of EarlyWellKnownAttributeBinder, NamedTypeSymbol, AttributeSyntax, AttributeLocation)() arguments.SymbolPart = symbolPart For i = 0 To boundAttributeTypes.Length - 1 Dim attributeType As NamedTypeSymbol = boundAttributeTypes(i) If Not attributeType.IsErrorType() Then arguments.Binder = New EarlyWellKnownAttributeBinder(Me, binders(i)) arguments.AttributeType = attributeType arguments.AttributeSyntax = attributesToBind(i) attributeBuilder(i) = Me.EarlyDecodeWellKnownAttribute(arguments) End If Next Return If(arguments.HasDecodedData, arguments.DecodedData, Nothing) End Function ''' <summary> ''' This method validates attribute usage for each bound attribute and calls <see cref="DecodeWellKnownAttribute"/> ''' on attributes with valid attribute usage. ''' This method is called by the binder when it is finished binding a set of attributes on the symbol so that ''' the symbol can extract data from the attribute arguments and potentially perform validation specific to ''' some well known attributes. ''' </summary> Friend Function ValidateAttributeUsageAndDecodeWellKnownAttributes( binders As ImmutableArray(Of Binder), attributeSyntaxList As ImmutableArray(Of AttributeSyntax), boundAttributes As ImmutableArray(Of VisualBasicAttributeData), diagnostics As BindingDiagnosticBag, symbolPart As AttributeLocation) As WellKnownAttributeData Debug.Assert(binders.Any()) Debug.Assert(attributeSyntaxList.Any()) Debug.Assert(boundAttributes.Any()) Debug.Assert(binders.Length = boundAttributes.Length) Debug.Assert(attributeSyntaxList.Length = boundAttributes.Length) Dim totalAttributesCount As Integer = boundAttributes.Length Dim uniqueAttributeTypes = New HashSet(Of NamedTypeSymbol) Dim arguments = New DecodeWellKnownAttributeArguments(Of AttributeSyntax, VisualBasicAttributeData, AttributeLocation)() arguments.AttributesCount = totalAttributesCount arguments.Diagnostics = diagnostics arguments.SymbolPart = symbolPart For i = 0 To totalAttributesCount - 1 Dim boundAttribute As VisualBasicAttributeData = boundAttributes(i) Dim attributeSyntax As AttributeSyntax = attributeSyntaxList(i) Dim binder As Binder = binders(i) If Not boundAttribute.HasErrors AndAlso ValidateAttributeUsage(boundAttribute, attributeSyntax, binder.Compilation, symbolPart, diagnostics, uniqueAttributeTypes) Then arguments.Attribute = boundAttribute arguments.AttributeSyntaxOpt = attributeSyntax arguments.Index = i Me.DecodeWellKnownAttribute(arguments) End If Next Return If(arguments.HasDecodedData, arguments.DecodedData, Nothing) End Function ''' <summary> ''' Validate attribute usage target and duplicate attributes. ''' </summary> ''' <param name="attribute">Bound attribute</param> ''' <param name="node">Syntax node for attribute specification</param> ''' <param name="compilation">Compilation</param> ''' <param name="symbolPart">Symbol part to which the attribute has been applied</param> ''' <param name="diagnostics">Diagnostics</param> ''' <param name="uniqueAttributeTypes">Set of unique attribute types applied to the symbol</param> Private Function ValidateAttributeUsage( attribute As VisualBasicAttributeData, node As AttributeSyntax, compilation As VisualBasicCompilation, symbolPart As AttributeLocation, diagnostics As BindingDiagnosticBag, uniqueAttributeTypes As HashSet(Of NamedTypeSymbol)) As Boolean Dim attributeType As NamedTypeSymbol = attribute.AttributeClass Debug.Assert(attributeType IsNot Nothing) Debug.Assert(Not attributeType.IsErrorType()) Debug.Assert(attributeType.IsOrDerivedFromWellKnownClass(WellKnownType.System_Attribute, compilation, CompoundUseSiteInfo(Of AssemblySymbol).Discarded)) ' Get attribute usage for this attribute Dim attributeUsage As AttributeUsageInfo = attributeType.GetAttributeUsageInfo() Debug.Assert(Not attributeUsage.IsNull) ' check if this attribute was used multiple times and attributeUsage.AllowMultiple is False. If Not uniqueAttributeTypes.Add(attributeType) AndAlso Not attributeUsage.AllowMultiple Then diagnostics.Add(ERRID.ERR_InvalidMultipleAttributeUsage1, node.GetLocation(), CustomSymbolDisplayFormatter.ShortErrorName(attributeType)) Return False End If Dim attributeTarget As AttributeTargets If symbolPart = AttributeLocation.Return Then Debug.Assert(Me.Kind = SymbolKind.Method OrElse Me.Kind = SymbolKind.Property) attributeTarget = AttributeTargets.ReturnValue Else attributeTarget = Me.GetAttributeTarget() End If ' VB allows NonSerialized on events even though the NonSerialized does not have this attribute usage specified. ' See Dev 10 Bindable::VerifyCustomAttributesOnSymbol Dim applicationIsValid As Boolean If attributeType Is compilation.GetWellKnownType(WellKnownType.System_NonSerializedAttribute) AndAlso Me.Kind = SymbolKind.Event AndAlso DirectCast(Me, SourceEventSymbol).AssociatedField IsNot Nothing Then applicationIsValid = True Else Dim validOn = attributeUsage.ValidTargets applicationIsValid = attributeTarget <> 0 AndAlso (validOn And attributeTarget) <> 0 End If If Not applicationIsValid Then Select Case attributeTarget Case AttributeTargets.Assembly diagnostics.Add(ERRID.ERR_InvalidAssemblyAttribute1, node.Name.GetLocation, CustomSymbolDisplayFormatter.ShortErrorName(attributeType)) Case AttributeTargets.Module diagnostics.Add(ERRID.ERR_InvalidModuleAttribute1, node.Name.GetLocation, CustomSymbolDisplayFormatter.ShortErrorName(attributeType)) Case AttributeTargets.Method If Me.Kind = SymbolKind.Method Then Dim method = DirectCast(Me, SourceMethodSymbol) Dim accessorName = TryGetAccessorDisplayName(method.MethodKind) If accessorName IsNot Nothing Then Debug.Assert(method.AssociatedSymbol IsNot Nothing) diagnostics.Add(ERRID.ERR_InvalidAttributeUsageOnAccessor, node.Name.GetLocation, CustomSymbolDisplayFormatter.ShortErrorName(attributeType), accessorName, CustomSymbolDisplayFormatter.ShortErrorName(method.AssociatedSymbol)) Exit Select End If End If diagnostics.Add(ERRID.ERR_InvalidAttributeUsage2, node.Name.GetLocation, CustomSymbolDisplayFormatter.ShortErrorName(attributeType), CustomSymbolDisplayFormatter.ShortErrorName(Me).ToString()) Case AttributeTargets.Field Dim withEventsBackingField = TryCast(Me, SourceWithEventsBackingFieldSymbol) Dim ownerName As String If withEventsBackingField IsNot Nothing Then ownerName = CustomSymbolDisplayFormatter.ShortErrorName(withEventsBackingField.AssociatedSymbol).ToString() Else ownerName = CustomSymbolDisplayFormatter.ShortErrorName(Me).ToString() End If diagnostics.Add(ERRID.ERR_InvalidAttributeUsage2, node.Name.GetLocation, CustomSymbolDisplayFormatter.ShortErrorName(attributeType), ownerName) Case AttributeTargets.ReturnValue diagnostics.Add(ERRID.ERR_InvalidAttributeUsage2, node.Name.GetLocation, CustomSymbolDisplayFormatter.ShortErrorName(attributeType), New LocalizableErrorArgument(ERRID.IDS_FunctionReturnType)) Case Else diagnostics.Add(ERRID.ERR_InvalidAttributeUsage2, node.Name.GetLocation, CustomSymbolDisplayFormatter.ShortErrorName(attributeType), CustomSymbolDisplayFormatter.ShortErrorName(Me).ToString()) End Select Return False End If If attribute.IsSecurityAttribute(compilation) Then Select Case Me.Kind Case SymbolKind.Assembly, SymbolKind.NamedType, SymbolKind.Method Exit Select Case Else ' BC36979: Security attribute '{0}' is not valid on this declaration type. Security attributes are only valid on assembly, type and method declarations. diagnostics.Add(ERRID.ERR_SecurityAttributeInvalidTarget, node.Name.GetLocation, CustomSymbolDisplayFormatter.ShortErrorName(attributeType)) Return False End Select End If Return True End Function Private Sub ReportExtensionAttributeUseSiteInfo(attribute As VisualBasicAttributeData, nodeOpt As AttributeSyntax, compilation As VisualBasicCompilation, diagnostics As BindingDiagnosticBag) ' report issues with a custom extension attribute everywhere, where the attribute is used in source ' (we will not report in location where it's implicitly used (like the containing module or assembly of extension methods) Dim useSiteInfo As UseSiteInfo(Of AssemblySymbol) = Nothing If attribute.AttributeConstructor IsNot Nothing AndAlso attribute.AttributeConstructor Is compilation.GetExtensionAttributeConstructor(useSiteInfo) Then diagnostics.Add(useSiteInfo, If(nodeOpt IsNot Nothing, nodeOpt.GetLocation(), NoLocation.Singleton)) End If End Sub Private Sub MarkEmbeddedAttributeTypeReference(attribute As VisualBasicAttributeData, nodeOpt As AttributeSyntax, compilation As VisualBasicCompilation) Debug.Assert(Not attribute.HasErrors) ' Mark embedded attribute type reference only if the owner is itself not ' embedded and the attribute syntax is actually from the current compilation. If Not Me.IsEmbedded AndAlso attribute.AttributeClass.IsEmbedded AndAlso nodeOpt IsNot Nothing AndAlso compilation.ContainsSyntaxTree(nodeOpt.SyntaxTree) Then ' Note that none of embedded symbols from referenced ' assemblies or compilations should be found/referenced. Debug.Assert(attribute.AttributeClass.ContainingAssembly Is compilation.Assembly) compilation.EmbeddedSymbolManager.MarkSymbolAsReferenced(attribute.AttributeClass) End If End Sub ''' <summary> ''' Ensure that attributes are bound and the ObsoleteState of this symbol is known. ''' </summary> Friend Sub ForceCompleteObsoleteAttribute() If Me.ObsoleteState = ThreeState.Unknown Then Me.GetAttributes() End If Debug.Assert(Me.ObsoleteState <> ThreeState.Unknown, "ObsoleteState should be true or false now.") End Sub End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Generic Imports System.Collections.Immutable Imports System.Runtime.InteropServices Imports System.Threading Imports Microsoft.CodeAnalysis.PooledObjects Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports TypeKind = Microsoft.CodeAnalysis.TypeKind Namespace Microsoft.CodeAnalysis.VisualBasic Partial Friend Class Symbol ' !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! ' Changes to the public interface of this class should remain synchronized with the C# version of Symbol. ' Do not make any changes to the public interface without making the corresponding change ' to the C# version. ' !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! ''' <summary> ''' Gets the attributes on this symbol. Returns an empty ImmutableArray if there are ''' no attributes. ''' </summary> Public Overridable Function GetAttributes() As ImmutableArray(Of VisualBasicAttributeData) Return ImmutableArray(Of VisualBasicAttributeData).Empty End Function ''' <summary> ''' Build and add synthesized attributes for this symbol. ''' </summary> Friend Overridable Sub AddSynthesizedAttributes(compilationState As ModuleCompilationState, ByRef attributes As ArrayBuilder(Of SynthesizedAttributeData)) End Sub ''' <summary> ''' Convenience helper called by subclasses to add a synthesized attribute to a collection of attributes. ''' </summary> Friend Shared Sub AddSynthesizedAttribute(ByRef attributes As ArrayBuilder(Of SynthesizedAttributeData), attribute As SynthesizedAttributeData) If attribute IsNot Nothing Then If attributes Is Nothing Then attributes = ArrayBuilder(Of SynthesizedAttributeData).GetInstance(4) End If attributes.Add(attribute) End If End Sub ''' <summary> ''' Returns the appropriate AttributeTarget for a symbol. This is used to validate attribute usage when ''' applying an attribute to a symbol. For any symbol that does not support the application of custom ''' attributes 0 is returned. ''' </summary> ''' <returns>The attribute target flag for this symbol or 0 if none apply.</returns> ''' <remarks></remarks> Friend Function GetAttributeTarget() As AttributeTargets Select Case Kind Case SymbolKind.Assembly Return AttributeTargets.Assembly Case SymbolKind.Event Return AttributeTargets.Event Case SymbolKind.Field Return AttributeTargets.Field Case SymbolKind.Method Dim method = DirectCast(Me, MethodSymbol) Select Case method.MethodKind Case MethodKind.Constructor, MethodKind.SharedConstructor Return AttributeTargets.Constructor Case MethodKind.Ordinary, MethodKind.DeclareMethod, MethodKind.UserDefinedOperator, MethodKind.Conversion, MethodKind.PropertyGet, MethodKind.PropertySet, MethodKind.EventAdd, MethodKind.EventRaise, MethodKind.EventRemove, MethodKind.DelegateInvoke Return AttributeTargets.Method End Select Case SymbolKind.Property Return AttributeTargets.Property Case SymbolKind.NamedType Dim namedType = DirectCast(Me, NamedTypeSymbol) Select Case namedType.TypeKind Case TypeKind.Class, TypeKind.Module Return AttributeTargets.Class Case TypeKind.Structure Return AttributeTargets.Struct Case TypeKind.Interface Return AttributeTargets.Interface Case TypeKind.Enum Return AttributeTargets.Enum Or AttributeTargets.Struct Case TypeKind.Delegate Return AttributeTargets.Delegate Case TypeKind.Submission ' attributes can't be applied on a submission type Throw ExceptionUtilities.UnexpectedValue(namedType.TypeKind) End Select Case SymbolKind.NetModule Return AttributeTargets.Module Case SymbolKind.Parameter Return AttributeTargets.Parameter Case SymbolKind.TypeParameter Return AttributeTargets.GenericParameter End Select Return 0 End Function ''' <summary> ''' Method to early decode applied well-known attribute which can be queried by the binder. ''' This method is called during attribute binding after we have bound the attribute types for all attributes, ''' but haven't yet bound the attribute arguments/attribute constructor. ''' Early decoding certain well-known attributes enables the binder to use this decoded information on this symbol ''' when binding the attribute arguments/attribute constructor without causing attribute binding cycle. ''' </summary> Friend Overridable Function EarlyDecodeWellKnownAttribute(ByRef arguments As EarlyDecodeWellKnownAttributeArguments(Of EarlyWellKnownAttributeBinder, NamedTypeSymbol, AttributeSyntax, AttributeLocation)) As VisualBasicAttributeData Return Nothing End Function Friend Function EarlyDecodeDeprecatedOrExperimentalOrObsoleteAttribute( ByRef arguments As EarlyDecodeWellKnownAttributeArguments(Of EarlyWellKnownAttributeBinder, NamedTypeSymbol, AttributeSyntax, AttributeLocation), <Out> ByRef boundAttribute As VisualBasicAttributeData, <Out> ByRef obsoleteData As ObsoleteAttributeData ) As Boolean Dim type = arguments.AttributeType Dim syntax = arguments.AttributeSyntax Dim kind As ObsoleteAttributeKind If VisualBasicAttributeData.IsTargetEarlyAttribute(type, syntax, AttributeDescription.ObsoleteAttribute) Then kind = ObsoleteAttributeKind.Obsolete ElseIf VisualBasicAttributeData.IsTargetEarlyAttribute(type, syntax, AttributeDescription.DeprecatedAttribute) Then kind = ObsoleteAttributeKind.Deprecated ElseIf VisualBasicAttributeData.IsTargetEarlyAttribute(type, syntax, AttributeDescription.ExperimentalAttribute) Then kind = ObsoleteAttributeKind.Experimental Else boundAttribute = Nothing obsoleteData = Nothing Return False End If Dim hasAnyDiagnostics As Boolean = False boundAttribute = arguments.Binder.GetAttribute(syntax, type, hasAnyDiagnostics) If Not boundAttribute.HasErrors Then obsoleteData = boundAttribute.DecodeObsoleteAttribute(kind) If hasAnyDiagnostics Then boundAttribute = Nothing End If Else obsoleteData = Nothing boundAttribute = Nothing End If Return True End Function ''' <summary> ''' This method is called by the binder when it is finished binding a set of attributes on the symbol so that ''' the symbol can extract data from the attribute arguments and potentially perform validation specific to ''' some well known attributes. ''' </summary> ''' <remarks> ''' <para> ''' Symbol types should override this if they want to handle a specific well-known attribute. ''' If the attribute is of a type that the symbol does not wish to handle, it should delegate back to ''' this (base) method. ''' </para> ''' </remarks> Friend Overridable Sub DecodeWellKnownAttribute(ByRef arguments As DecodeWellKnownAttributeArguments(Of AttributeSyntax, VisualBasicAttributeData, AttributeLocation)) Dim compilation = Me.DeclaringCompilation MarkEmbeddedAttributeTypeReference(arguments.Attribute, arguments.AttributeSyntaxOpt, compilation) ReportExtensionAttributeUseSiteInfo(arguments.Attribute, arguments.AttributeSyntaxOpt, compilation, DirectCast(arguments.Diagnostics, BindingDiagnosticBag)) If arguments.Attribute.IsTargetAttribute(Me, AttributeDescription.SkipLocalsInitAttribute) Then DirectCast(arguments.Diagnostics, BindingDiagnosticBag).Add(ERRID.WRN_AttributeNotSupportedInVB, arguments.AttributeSyntaxOpt.Location, AttributeDescription.SkipLocalsInitAttribute.FullName) End If End Sub ''' <summary> ''' Called to report attribute related diagnostics after all attributes have been bound and decoded. ''' Called even if there are no attributes. ''' </summary> ''' <remarks> ''' This method is called by the binder from <see cref="LoadAndValidateAttributes"/> after it has finished binding attributes on the symbol, ''' has executed <see cref="DecodeWellKnownAttribute"/> for attributes applied on the symbol and has stored the decoded data in the ''' lazyCustomAttributesBag on the symbol. Bound attributes haven't been stored on the bag yet. ''' ''' Post-validation for attributes that is dependent on other attributes can be done here. ''' ''' This method should not have any side effects on the symbol, i.e. it SHOULD NOT change the symbol state. ''' </remarks> ''' <param name="boundAttributes">Bound attributes.</param> ''' <param name="allAttributeSyntaxNodes">Syntax nodes of attributes in order they are specified in source.</param> ''' <param name="diagnostics">Diagnostic bag.</param> ''' <param name="symbolPart">Specific part of the symbol to which the attributes apply, or <see cref="AttributeLocation.None"/> if the attributes apply to the symbol itself.</param> ''' <param name="decodedData">Decoded well known attribute data.</param> Friend Overridable Sub PostDecodeWellKnownAttributes(boundAttributes As ImmutableArray(Of VisualBasicAttributeData), allAttributeSyntaxNodes As ImmutableArray(Of AttributeSyntax), diagnostics As BindingDiagnosticBag, symbolPart As AttributeLocation, decodedData As WellKnownAttributeData) End Sub ''' <summary> ''' This method does the following set of operations in the specified order: ''' (1) GetAttributesToBind: Merge the given attributeBlockSyntaxList into a single list of attributes to bind. ''' (2) GetAttributes: Bind the attributes (attribute type, arguments and constructor). ''' (3) DecodeWellKnownAttributes: Decode and validate bound well-known attributes. ''' (4) ValidateAttributes: Perform some additional attribute validations, such as ''' 1) Duplicate attributes, ''' 2) Attribute usage target validation, etc. ''' (5) Store the bound attributes and decoded well-known attribute data in lazyCustomAttributesBag in a thread safe manner. ''' </summary> Friend Sub LoadAndValidateAttributes(attributeBlockSyntaxList As OneOrMany(Of SyntaxList(Of AttributeListSyntax)), ByRef lazyCustomAttributesBag As CustomAttributesBag(Of VisualBasicAttributeData), Optional symbolPart As AttributeLocation = 0) Dim diagnostics = BindingDiagnosticBag.GetInstance() Dim sourceAssembly = DirectCast(If(Me.Kind = SymbolKind.Assembly, Me, Me.ContainingAssembly), SourceAssemblySymbol) Dim sourceModule = sourceAssembly.SourceModule Dim compilation = sourceAssembly.DeclaringCompilation Dim binders As ImmutableArray(Of Binder) = Nothing Dim attributesToBind = GetAttributesToBind(attributeBlockSyntaxList, symbolPart, compilation, binders) Dim boundAttributes As ImmutableArray(Of VisualBasicAttributeData) Dim wellKnownAttrData As WellKnownAttributeData If attributesToBind.Any() Then Debug.Assert(attributesToBind.Any()) Debug.Assert(binders.Any()) Debug.Assert(attributesToBind.Length = binders.Length) ' Initialize the bag so that data decoded from early attributes can be stored onto it. If (lazyCustomAttributesBag Is Nothing) Then Interlocked.CompareExchange(lazyCustomAttributesBag, New CustomAttributesBag(Of VisualBasicAttributeData)(), Nothing) End If Dim boundAttributeTypes As ImmutableArray(Of NamedTypeSymbol) = Binder.BindAttributeTypes(binders, attributesToBind, Me, diagnostics) Dim attributeBuilder = New VisualBasicAttributeData(boundAttributeTypes.Length - 1) {} ' Early bind and decode some well-known attributes. Dim earlyData As EarlyWellKnownAttributeData = Me.EarlyDecodeWellKnownAttributes(binders, boundAttributeTypes, attributesToBind, attributeBuilder, symbolPart) ' Store data decoded from early bound well-known attributes. lazyCustomAttributesBag.SetEarlyDecodedWellKnownAttributeData(earlyData) ' Bind attributes. Binder.GetAttributes(binders, attributesToBind, boundAttributeTypes, attributeBuilder, Me, diagnostics) boundAttributes = attributeBuilder.AsImmutableOrNull ' Validate attribute usage and Decode remaining well-known attributes. wellKnownAttrData = Me.ValidateAttributeUsageAndDecodeWellKnownAttributes(binders, attributesToBind, boundAttributes, diagnostics, symbolPart) ' Store data decoded from remaining well-known attributes. lazyCustomAttributesBag.SetDecodedWellKnownAttributeData(wellKnownAttrData) Else boundAttributes = ImmutableArray(Of VisualBasicAttributeData).Empty wellKnownAttrData = Nothing Interlocked.CompareExchange(lazyCustomAttributesBag, CustomAttributesBag(Of VisualBasicAttributeData).WithEmptyData(), Nothing) End If Me.PostDecodeWellKnownAttributes(boundAttributes, attributesToBind, diagnostics, symbolPart, wellKnownAttrData) ' Store attributes into the bag. sourceModule.AtomicStoreAttributesAndDiagnostics(lazyCustomAttributesBag, boundAttributes, diagnostics) diagnostics.Free() Debug.Assert(lazyCustomAttributesBag.IsSealed) End Sub Private Function GetAttributesToBind(attributeDeclarationSyntaxLists As OneOrMany(Of SyntaxList(Of AttributeListSyntax)), symbolPart As AttributeLocation, compilation As VisualBasicCompilation, <Out> ByRef binders As ImmutableArray(Of Binder)) As ImmutableArray(Of AttributeSyntax) Dim attributeTarget = DirectCast(Me, IAttributeTargetSymbol) Dim sourceModule = DirectCast(compilation.SourceModule, SourceModuleSymbol) Dim syntaxBuilder As ArrayBuilder(Of AttributeSyntax) = Nothing Dim bindersBuilder As ArrayBuilder(Of Binder) = Nothing Dim attributesToBindCount As Integer = 0 For listIndex = 0 To attributeDeclarationSyntaxLists.Count - 1 Dim attributeDeclarationSyntaxList As SyntaxList(Of AttributeListSyntax) = attributeDeclarationSyntaxLists(listIndex) If attributeDeclarationSyntaxList.Any() Then Dim prevCount As Integer = attributesToBindCount For Each attributeDeclarationSyntax In attributeDeclarationSyntaxList For Each attributeSyntax In attributeDeclarationSyntax.Attributes If MatchAttributeTarget(attributeTarget, symbolPart, attributeSyntax.Target) Then If syntaxBuilder Is Nothing Then syntaxBuilder = New ArrayBuilder(Of AttributeSyntax)() bindersBuilder = New ArrayBuilder(Of Binder)() End If syntaxBuilder.Add(attributeSyntax) attributesToBindCount += 1 End If Next Next If attributesToBindCount <> prevCount Then Debug.Assert(attributeDeclarationSyntaxList.Node IsNot Nothing) Debug.Assert(bindersBuilder IsNot Nothing) Dim binder = GetAttributeBinder(attributeDeclarationSyntaxList, sourceModule) For i = 0 To attributesToBindCount - prevCount - 1 bindersBuilder.Add(binder) Next End If End If Next If syntaxBuilder IsNot Nothing Then binders = bindersBuilder.ToImmutableAndFree() Return syntaxBuilder.ToImmutableAndFree() Else binders = ImmutableArray(Of Binder).Empty Return ImmutableArray(Of AttributeSyntax).Empty End If End Function Friend Function GetAttributeBinder(syntaxList As SyntaxList(Of AttributeListSyntax), sourceModule As SourceModuleSymbol) As Binder Dim syntaxTree = syntaxList.Node.SyntaxTree Dim parent = syntaxList.Node.Parent If parent.IsKind(SyntaxKind.AttributesStatement) AndAlso parent.Parent.IsKind(SyntaxKind.CompilationUnit) Then ' Create a binder for the file-level attributes. To avoid infinite recursion, the bound file information ' must be fully computed prior to trying to bind the file attributes. Return BinderBuilder.CreateBinderForProjectLevelNamespace(sourceModule, syntaxTree) Else Return BinderBuilder.CreateBinderForAttribute(sourceModule, syntaxTree, Me) End If End Function Private Shared Function MatchAttributeTarget(attributeTarget As IAttributeTargetSymbol, symbolPart As AttributeLocation, targetOpt As AttributeTargetSyntax) As Boolean If targetOpt Is Nothing Then Return True End If Dim explicitTarget As AttributeLocation ' Parser ensures that an error is reported for anything other than "assembly" or ' "module". Only assembly and module keywords can get here. Select Case targetOpt.AttributeModifier.Kind Case SyntaxKind.AssemblyKeyword explicitTarget = AttributeLocation.Assembly Case SyntaxKind.ModuleKeyword explicitTarget = AttributeLocation.Module Case Else Throw ExceptionUtilities.UnexpectedValue(targetOpt.AttributeModifier.Kind) End Select If symbolPart = 0 Then Return explicitTarget = attributeTarget.DefaultAttributeLocation Else Return explicitTarget = symbolPart End If End Function Private Shared Function GetAttributesToBind(attributeBlockSyntaxList As SyntaxList(Of AttributeListSyntax)) As ImmutableArray(Of AttributeSyntax) Dim attributeSyntaxBuilder As ArrayBuilder(Of AttributeSyntax) = Nothing GetAttributesToBind(attributeBlockSyntaxList, attributeSyntaxBuilder) Return If(attributeSyntaxBuilder IsNot Nothing, attributeSyntaxBuilder.ToImmutableAndFree(), ImmutableArray(Of AttributeSyntax).Empty) End Function Friend Shared Sub GetAttributesToBind(attributeBlockSyntaxList As SyntaxList(Of AttributeListSyntax), ByRef attributeSyntaxBuilder As ArrayBuilder(Of AttributeSyntax)) If attributeBlockSyntaxList.Count > 0 Then If attributeSyntaxBuilder Is Nothing Then attributeSyntaxBuilder = ArrayBuilder(Of AttributeSyntax).GetInstance() End If For Each attributeBlock In attributeBlockSyntaxList attributeSyntaxBuilder.AddRange(attributeBlock.Attributes) Next End If End Sub ''' <summary> ''' Method to early decode certain well-known attributes which can be queried by the binder. ''' This method is called during attribute binding after we have bound the attribute types for all attributes, ''' but haven't yet bound the attribute arguments/attribute constructor. ''' Early decoding certain well-known attributes enables the binder to use this decoded information on this symbol ''' when binding the attribute arguments/attribute constructor without causing attribute binding cycle. ''' </summary> Private Function EarlyDecodeWellKnownAttributes(binders As ImmutableArray(Of Binder), boundAttributeTypes As ImmutableArray(Of NamedTypeSymbol), attributesToBind As ImmutableArray(Of AttributeSyntax), attributeBuilder As VisualBasicAttributeData(), symbolPart As AttributeLocation) As EarlyWellKnownAttributeData Debug.Assert(boundAttributeTypes.Any()) Debug.Assert(attributesToBind.Any()) Dim arguments = New EarlyDecodeWellKnownAttributeArguments(Of EarlyWellKnownAttributeBinder, NamedTypeSymbol, AttributeSyntax, AttributeLocation)() arguments.SymbolPart = symbolPart For i = 0 To boundAttributeTypes.Length - 1 Dim attributeType As NamedTypeSymbol = boundAttributeTypes(i) If Not attributeType.IsErrorType() Then arguments.Binder = New EarlyWellKnownAttributeBinder(Me, binders(i)) arguments.AttributeType = attributeType arguments.AttributeSyntax = attributesToBind(i) attributeBuilder(i) = Me.EarlyDecodeWellKnownAttribute(arguments) End If Next Return If(arguments.HasDecodedData, arguments.DecodedData, Nothing) End Function ''' <summary> ''' This method validates attribute usage for each bound attribute and calls <see cref="DecodeWellKnownAttribute"/> ''' on attributes with valid attribute usage. ''' This method is called by the binder when it is finished binding a set of attributes on the symbol so that ''' the symbol can extract data from the attribute arguments and potentially perform validation specific to ''' some well known attributes. ''' </summary> Friend Function ValidateAttributeUsageAndDecodeWellKnownAttributes( binders As ImmutableArray(Of Binder), attributeSyntaxList As ImmutableArray(Of AttributeSyntax), boundAttributes As ImmutableArray(Of VisualBasicAttributeData), diagnostics As BindingDiagnosticBag, symbolPart As AttributeLocation) As WellKnownAttributeData Debug.Assert(binders.Any()) Debug.Assert(attributeSyntaxList.Any()) Debug.Assert(boundAttributes.Any()) Debug.Assert(binders.Length = boundAttributes.Length) Debug.Assert(attributeSyntaxList.Length = boundAttributes.Length) Dim totalAttributesCount As Integer = boundAttributes.Length Dim uniqueAttributeTypes = New HashSet(Of NamedTypeSymbol) Dim arguments = New DecodeWellKnownAttributeArguments(Of AttributeSyntax, VisualBasicAttributeData, AttributeLocation)() arguments.AttributesCount = totalAttributesCount arguments.Diagnostics = diagnostics arguments.SymbolPart = symbolPart For i = 0 To totalAttributesCount - 1 Dim boundAttribute As VisualBasicAttributeData = boundAttributes(i) Dim attributeSyntax As AttributeSyntax = attributeSyntaxList(i) Dim binder As Binder = binders(i) If Not boundAttribute.HasErrors AndAlso ValidateAttributeUsage(boundAttribute, attributeSyntax, binder.Compilation, symbolPart, diagnostics, uniqueAttributeTypes) Then arguments.Attribute = boundAttribute arguments.AttributeSyntaxOpt = attributeSyntax arguments.Index = i Me.DecodeWellKnownAttribute(arguments) End If Next Return If(arguments.HasDecodedData, arguments.DecodedData, Nothing) End Function ''' <summary> ''' Validate attribute usage target and duplicate attributes. ''' </summary> ''' <param name="attribute">Bound attribute</param> ''' <param name="node">Syntax node for attribute specification</param> ''' <param name="compilation">Compilation</param> ''' <param name="symbolPart">Symbol part to which the attribute has been applied</param> ''' <param name="diagnostics">Diagnostics</param> ''' <param name="uniqueAttributeTypes">Set of unique attribute types applied to the symbol</param> Private Function ValidateAttributeUsage( attribute As VisualBasicAttributeData, node As AttributeSyntax, compilation As VisualBasicCompilation, symbolPart As AttributeLocation, diagnostics As BindingDiagnosticBag, uniqueAttributeTypes As HashSet(Of NamedTypeSymbol)) As Boolean Dim attributeType As NamedTypeSymbol = attribute.AttributeClass Debug.Assert(attributeType IsNot Nothing) Debug.Assert(Not attributeType.IsErrorType()) Debug.Assert(attributeType.IsOrDerivedFromWellKnownClass(WellKnownType.System_Attribute, compilation, CompoundUseSiteInfo(Of AssemblySymbol).Discarded)) ' Get attribute usage for this attribute Dim attributeUsage As AttributeUsageInfo = attributeType.GetAttributeUsageInfo() Debug.Assert(Not attributeUsage.IsNull) ' check if this attribute was used multiple times and attributeUsage.AllowMultiple is False. If Not uniqueAttributeTypes.Add(attributeType) AndAlso Not attributeUsage.AllowMultiple Then diagnostics.Add(ERRID.ERR_InvalidMultipleAttributeUsage1, node.GetLocation(), CustomSymbolDisplayFormatter.ShortErrorName(attributeType)) Return False End If Dim attributeTarget As AttributeTargets If symbolPart = AttributeLocation.Return Then Debug.Assert(Me.Kind = SymbolKind.Method OrElse Me.Kind = SymbolKind.Property) attributeTarget = AttributeTargets.ReturnValue Else attributeTarget = Me.GetAttributeTarget() End If ' VB allows NonSerialized on events even though the NonSerialized does not have this attribute usage specified. ' See Dev 10 Bindable::VerifyCustomAttributesOnSymbol Dim applicationIsValid As Boolean If attributeType Is compilation.GetWellKnownType(WellKnownType.System_NonSerializedAttribute) AndAlso Me.Kind = SymbolKind.Event AndAlso DirectCast(Me, SourceEventSymbol).AssociatedField IsNot Nothing Then applicationIsValid = True Else Dim validOn = attributeUsage.ValidTargets applicationIsValid = attributeTarget <> 0 AndAlso (validOn And attributeTarget) <> 0 End If If Not applicationIsValid Then Select Case attributeTarget Case AttributeTargets.Assembly diagnostics.Add(ERRID.ERR_InvalidAssemblyAttribute1, node.Name.GetLocation, CustomSymbolDisplayFormatter.ShortErrorName(attributeType)) Case AttributeTargets.Module diagnostics.Add(ERRID.ERR_InvalidModuleAttribute1, node.Name.GetLocation, CustomSymbolDisplayFormatter.ShortErrorName(attributeType)) Case AttributeTargets.Method If Me.Kind = SymbolKind.Method Then Dim method = DirectCast(Me, SourceMethodSymbol) Dim accessorName = TryGetAccessorDisplayName(method.MethodKind) If accessorName IsNot Nothing Then Debug.Assert(method.AssociatedSymbol IsNot Nothing) diagnostics.Add(ERRID.ERR_InvalidAttributeUsageOnAccessor, node.Name.GetLocation, CustomSymbolDisplayFormatter.ShortErrorName(attributeType), accessorName, CustomSymbolDisplayFormatter.ShortErrorName(method.AssociatedSymbol)) Exit Select End If End If diagnostics.Add(ERRID.ERR_InvalidAttributeUsage2, node.Name.GetLocation, CustomSymbolDisplayFormatter.ShortErrorName(attributeType), CustomSymbolDisplayFormatter.ShortErrorName(Me).ToString()) Case AttributeTargets.Field Dim withEventsBackingField = TryCast(Me, SourceWithEventsBackingFieldSymbol) Dim ownerName As String If withEventsBackingField IsNot Nothing Then ownerName = CustomSymbolDisplayFormatter.ShortErrorName(withEventsBackingField.AssociatedSymbol).ToString() Else ownerName = CustomSymbolDisplayFormatter.ShortErrorName(Me).ToString() End If diagnostics.Add(ERRID.ERR_InvalidAttributeUsage2, node.Name.GetLocation, CustomSymbolDisplayFormatter.ShortErrorName(attributeType), ownerName) Case AttributeTargets.ReturnValue diagnostics.Add(ERRID.ERR_InvalidAttributeUsage2, node.Name.GetLocation, CustomSymbolDisplayFormatter.ShortErrorName(attributeType), New LocalizableErrorArgument(ERRID.IDS_FunctionReturnType)) Case Else diagnostics.Add(ERRID.ERR_InvalidAttributeUsage2, node.Name.GetLocation, CustomSymbolDisplayFormatter.ShortErrorName(attributeType), CustomSymbolDisplayFormatter.ShortErrorName(Me).ToString()) End Select Return False End If If attribute.IsSecurityAttribute(compilation) Then Select Case Me.Kind Case SymbolKind.Assembly, SymbolKind.NamedType, SymbolKind.Method Exit Select Case Else ' BC36979: Security attribute '{0}' is not valid on this declaration type. Security attributes are only valid on assembly, type and method declarations. diagnostics.Add(ERRID.ERR_SecurityAttributeInvalidTarget, node.Name.GetLocation, CustomSymbolDisplayFormatter.ShortErrorName(attributeType)) Return False End Select End If Return True End Function Private Sub ReportExtensionAttributeUseSiteInfo(attribute As VisualBasicAttributeData, nodeOpt As AttributeSyntax, compilation As VisualBasicCompilation, diagnostics As BindingDiagnosticBag) ' report issues with a custom extension attribute everywhere, where the attribute is used in source ' (we will not report in location where it's implicitly used (like the containing module or assembly of extension methods) Dim useSiteInfo As UseSiteInfo(Of AssemblySymbol) = Nothing If attribute.AttributeConstructor IsNot Nothing AndAlso attribute.AttributeConstructor Is compilation.GetExtensionAttributeConstructor(useSiteInfo) Then diagnostics.Add(useSiteInfo, If(nodeOpt IsNot Nothing, nodeOpt.GetLocation(), NoLocation.Singleton)) End If End Sub Private Sub MarkEmbeddedAttributeTypeReference(attribute As VisualBasicAttributeData, nodeOpt As AttributeSyntax, compilation As VisualBasicCompilation) Debug.Assert(Not attribute.HasErrors) ' Mark embedded attribute type reference only if the owner is itself not ' embedded and the attribute syntax is actually from the current compilation. If Not Me.IsEmbedded AndAlso attribute.AttributeClass.IsEmbedded AndAlso nodeOpt IsNot Nothing AndAlso compilation.ContainsSyntaxTree(nodeOpt.SyntaxTree) Then ' Note that none of embedded symbols from referenced ' assemblies or compilations should be found/referenced. Debug.Assert(attribute.AttributeClass.ContainingAssembly Is compilation.Assembly) compilation.EmbeddedSymbolManager.MarkSymbolAsReferenced(attribute.AttributeClass) End If End Sub ''' <summary> ''' Ensure that attributes are bound and the ObsoleteState of this symbol is known. ''' </summary> Friend Sub ForceCompleteObsoleteAttribute() If Me.ObsoleteState = ThreeState.Unknown Then Me.GetAttributes() End If Debug.Assert(Me.ObsoleteState <> ThreeState.Unknown, "ObsoleteState should be true or false now.") End Sub End Class End Namespace
-1
dotnet/roslyn
55,430
Fix LSP semantic tokens algorithm
This PR primarily accomplishes two tasks: 1) Overhauls the existing LSP semantic tokens edits processing algorithm to align with [Razor's](https://github.com/dotnet/aspnetcore-tooling/blob/main/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/Semantic/Services/SemanticTokensEditsDiffer.cs) (shoutout to Ryan and the rest of the Razor team for writing the original 😄). The main change here is going from calculating edits per token (i.e. five ints) to per int. The updated algorithm is much more efficient than our previous algorithm, and returns less edits back to the LSP client. 2) The interpretation of Roslyn's LongestCommonSubstring algorithm, which we use to calculate raw edits, was missing a critical piece. Namely, for insertions, we need to keep track of _where_ we should be inserting into the original token set. We don't keep track of this in the existing implementation, resulting in bugs such as #54671. Resolves #54671
allisonchou
2021-08-05T06:06:43Z
2021-08-06T23:44:44Z
b9200d03a76c74d404040d44b9bbe12b1d0a8ef2
f300a818940ea1acef66c946cfa83756729d5e59
Fix LSP semantic tokens algorithm. This PR primarily accomplishes two tasks: 1) Overhauls the existing LSP semantic tokens edits processing algorithm to align with [Razor's](https://github.com/dotnet/aspnetcore-tooling/blob/main/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/Semantic/Services/SemanticTokensEditsDiffer.cs) (shoutout to Ryan and the rest of the Razor team for writing the original 😄). The main change here is going from calculating edits per token (i.e. five ints) to per int. The updated algorithm is much more efficient than our previous algorithm, and returns less edits back to the LSP client. 2) The interpretation of Roslyn's LongestCommonSubstring algorithm, which we use to calculate raw edits, was missing a critical piece. Namely, for insertions, we need to keep track of _where_ we should be inserting into the original token set. We don't keep track of this in the existing implementation, resulting in bugs such as #54671. Resolves #54671
./src/VisualStudio/Core/Def/xlf/ServicesVSResources.tr.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="tr" original="../ServicesVSResources.resx"> <body> <trans-unit id="A_new_editorconfig_file_was_detected_at_the_root_of_your_solution_Would_you_like_to_make_it_a_solution_item"> <source>A new .editorconfig file was detected at the root of your solution. Would you like to make it a solution item?</source> <target state="translated">Çözümünüzün kökünde yeni bir .editorconfig dosyası algılandı. Bunu bir çözüm öğesi yapmak istiyor musunuz?</target> <note /> </trans-unit> <trans-unit id="A_new_namespace_will_be_created"> <source>A new namespace will be created</source> <target state="translated">Yeni bir ad alanı oluşturulacak</target> <note /> </trans-unit> <trans-unit id="A_type_and_name_must_be_provided"> <source>A type and name must be provided.</source> <target state="translated">Bir tür ve ad verilmesi gerekiyor.</target> <note /> </trans-unit> <trans-unit id="Action"> <source>Action</source> <target state="translated">Eylem</target> <note>Action to perform on an unused reference, such as remove or keep</note> </trans-unit> <trans-unit id="Add"> <source>_Add</source> <target state="translated">_Ekle</target> <note>Adding an element to a list</note> </trans-unit> <trans-unit id="Add_Parameter"> <source>Add Parameter</source> <target state="translated">Parametre Ekle</target> <note /> </trans-unit> <trans-unit id="Add_to_current_file"> <source>Add to _current file</source> <target state="translated">Geçerli _dosyaya ekle</target> <note /> </trans-unit> <trans-unit id="Added_Parameter"> <source>Added parameter.</source> <target state="translated">Parametre eklendi.</target> <note /> </trans-unit> <trans-unit id="Additional_changes_are_needed_to_complete_the_refactoring_Review_changes_below"> <source>Additional changes are needed to complete the refactoring. Review changes below.</source> <target state="translated">Yeniden düzenlemeyi tamamlamak için ek değişiklikler gerekli. Aşağıdaki değişiklikleri gözden geçirin.</target> <note /> </trans-unit> <trans-unit id="All_methods"> <source>All methods</source> <target state="translated">Tüm yöntemler</target> <note /> </trans-unit> <trans-unit id="All_sources"> <source>All sources</source> <target state="translated">Tüm kaynaklar</target> <note /> </trans-unit> <trans-unit id="Allow_colon"> <source>Allow:</source> <target state="translated">İzin ver:</target> <note /> </trans-unit> <trans-unit id="Allow_multiple_blank_lines"> <source>Allow multiple blank lines</source> <target state="translated">Birden çok boş satıra izin ver</target> <note /> </trans-unit> <trans-unit id="Allow_statement_immediately_after_block"> <source>Allow statement immediately after block</source> <target state="translated">Bloktan hemen sonra deyime izin ver</target> <note /> </trans-unit> <trans-unit id="Always_for_clarity"> <source>Always for clarity</source> <target state="translated">Açıklık sağlamak için her zaman</target> <note /> </trans-unit> <trans-unit id="Analyzer_Defaults"> <source>Analyzer Defaults</source> <target state="new">Analyzer Defaults</target> <note /> </trans-unit> <trans-unit id="Analyzers"> <source>Analyzers</source> <target state="translated">Çözümleyiciler</target> <note /> </trans-unit> <trans-unit id="Analyzing_project_references"> <source>Analyzing project references...</source> <target state="translated">Proje başvuruları analiz ediliyor...</target> <note /> </trans-unit> <trans-unit id="Apply"> <source>Apply</source> <target state="translated">Uygula</target> <note /> </trans-unit> <trans-unit id="Apply_0_keymapping_scheme"> <source>Apply '{0}' keymapping scheme</source> <target state="translated">'{0}' tuş eşlemesi düzenini uygula</target> <note /> </trans-unit> <trans-unit id="Assemblies"> <source>Assemblies</source> <target state="translated">Derlemeler</target> <note /> </trans-unit> <trans-unit id="Avoid_expression_statements_that_implicitly_ignore_value"> <source>Avoid expression statements that implicitly ignore value</source> <target state="translated">Değeri örtük olarak yok sayan ifade deyimlerini engelle</target> <note /> </trans-unit> <trans-unit id="Avoid_unused_parameters"> <source>Avoid unused parameters</source> <target state="translated">Kullanılmayan parametreleri engelle</target> <note /> </trans-unit> <trans-unit id="Avoid_unused_value_assignments"> <source>Avoid unused value assignments</source> <target state="translated">Kullanılmayan değer atamalarını engelle</target> <note /> </trans-unit> <trans-unit id="Back"> <source>Back</source> <target state="translated">Geri</target> <note /> </trans-unit> <trans-unit id="Background_analysis_scope_colon"> <source>Background analysis scope:</source> <target state="translated">Arka plan çözümleme kapsamı:</target> <note /> </trans-unit> <trans-unit id="Bitness32"> <source>32-bit</source> <target state="translated">32 bit</target> <note /> </trans-unit> <trans-unit id="Bitness64"> <source>64-bit</source> <target state="translated">64 bit</target> <note /> </trans-unit> <trans-unit id="Build_plus_live_analysis_NuGet_package"> <source>Build + live analysis (NuGet package)</source> <target state="translated">Derleme ve canlı analiz (NuGet paketi)</target> <note /> </trans-unit> <trans-unit id="CSharp_Visual_Basic_Diagnostics_Language_Client"> <source>C#/Visual Basic Diagnostics Language Client</source> <target state="translated">C#/Visual Basic Tanılama Dili İstemcisi</target> <note /> </trans-unit> <trans-unit id="Calculating"> <source>Calculating...</source> <target state="new">Calculating...</target> <note>Used in UI to represent progress in the context of loading items. </note> </trans-unit> <trans-unit id="Calculating_dependents"> <source>Calculating dependents...</source> <target state="translated">Bağımlılar hesaplanıyor...</target> <note /> </trans-unit> <trans-unit id="Call_site_value"> <source>Call site value:</source> <target state="translated">Çağrı konumu değeri:</target> <note /> </trans-unit> <trans-unit id="Callsite"> <source>Call site</source> <target state="translated">Çağrı konumu</target> <note /> </trans-unit> <trans-unit id="Carriage_Return_Newline_rn"> <source>Carriage Return + Newline (\r\n)</source> <target state="translated">Satır Başı + Yeni Satır (\r\n)</target> <note /> </trans-unit> <trans-unit id="Carriage_Return_r"> <source>Carriage Return (\r)</source> <target state="translated">Satır başı (\r)</target> <note /> </trans-unit> <trans-unit id="Category"> <source>Category</source> <target state="translated">Kategori</target> <note /> </trans-unit> <trans-unit id="Choose_which_action_you_would_like_to_perform_on_the_unused_references"> <source>Choose which action you would like to perform on the unused references.</source> <target state="translated">Kullanılmayan başvurularda hangi eylemi gerçekleştirmek istediğinizi seçin.</target> <note /> </trans-unit> <trans-unit id="Code_Style"> <source>Code Style</source> <target state="translated">Kod Stili</target> <note /> </trans-unit> <trans-unit id="Code_analysis_completed_for_0"> <source>Code analysis completed for '{0}'.</source> <target state="translated">'{0}' için kod analizi tamamlandı.</target> <note /> </trans-unit> <trans-unit id="Code_analysis_completed_for_Solution"> <source>Code analysis completed for Solution.</source> <target state="translated">Çözüm için kod analizi tamamlandı.</target> <note /> </trans-unit> <trans-unit id="Code_analysis_terminated_before_completion_for_0"> <source>Code analysis terminated before completion for '{0}'.</source> <target state="translated">Kod analizi, '{0}' için tamamlanmadan önce sonlandırıldı.</target> <note /> </trans-unit> <trans-unit id="Code_analysis_terminated_before_completion_for_Solution"> <source>Code analysis terminated before completion for Solution.</source> <target state="translated">Kod analizi, Çözüm için tamamlanmadan önce sonlandırıldı.</target> <note /> </trans-unit> <trans-unit id="Color_hints"> <source>Color hints</source> <target state="translated">Renk ipuçları</target> <note /> </trans-unit> <trans-unit id="Colorize_regular_expressions"> <source>Colorize regular expressions</source> <target state="translated">Normal ifadeleri renklendir</target> <note /> </trans-unit> <trans-unit id="Comments"> <source>Comments</source> <target state="translated">Açıklamalar</target> <note /> </trans-unit> <trans-unit id="Containing_member"> <source>Containing Member</source> <target state="translated">Kapsayan Üye</target> <note /> </trans-unit> <trans-unit id="Containing_type"> <source>Containing Type</source> <target state="translated">Kapsayan Tür</target> <note /> </trans-unit> <trans-unit id="Current_document"> <source>Current document</source> <target state="translated">Geçerli belge</target> <note /> </trans-unit> <trans-unit id="Current_parameter"> <source>Current parameter</source> <target state="translated">Geçerli parametre</target> <note /> </trans-unit> <trans-unit id="Derived_types"> <source>Derived types</source> <target state="new">Derived types</target> <note /> </trans-unit> <trans-unit id="Disabled"> <source>Disabled</source> <target state="translated">Devre dışı</target> <note /> </trans-unit> <trans-unit id="Display_all_hints_while_pressing_Alt_F1"> <source>Display all hints while pressing Alt+F1</source> <target state="translated">Alt+F1 tuşlarına basılırken tüm ipuçlarını görüntüle</target> <note /> </trans-unit> <trans-unit id="Display_inline_parameter_name_hints"> <source>Disp_lay inline parameter name hints</source> <target state="translated">Satır içi parametre adı ipuç_larını göster</target> <note /> </trans-unit> <trans-unit id="Display_inline_type_hints"> <source>Display inline type hints</source> <target state="translated">Satır içi tür ipuçlarını göster</target> <note /> </trans-unit> <trans-unit id="Edit"> <source>_Edit</source> <target state="translated">_Düzenle</target> <note /> </trans-unit> <trans-unit id="Edit_0"> <source>Edit {0}</source> <target state="translated">{0} öğesini düzenle</target> <note>{0} is a parameter description</note> </trans-unit> <trans-unit id="Editor_Color_Scheme"> <source>Editor Color Scheme</source> <target state="translated">Düzenleyici Renk Düzeni</target> <note /> </trans-unit> <trans-unit id="Editor_color_scheme_options_are_only_available_when_using_a_color_theme_bundled_with_Visual_Studio_The_color_theme_can_be_configured_from_the_Environment_General_options_page"> <source>Editor color scheme options are only available when using a color theme bundled with Visual Studio. The color theme can be configured from the Environment &gt; General options page.</source> <target state="translated">Düzenleyici renk düzeni seçenekleri yalnızca Visual Studio ile paketlenmiş bir renk teması ile birlikte kullanılabilir. Renk teması, Ortam &gt; Genel seçenekler sayfasından yapılandırılabilir.</target> <note /> </trans-unit> <trans-unit id="Element_is_not_valid"> <source>Element is not valid.</source> <target state="translated">Öğe geçerli değil.</target> <note /> </trans-unit> <trans-unit id="Enable_Razor_pull_diagnostics_experimental_requires_restart"> <source>Enable Razor 'pull' diagnostics (experimental, requires restart)</source> <target state="translated">Razor 'pull' tanılamasını etkinleştir (deneysel, yeniden başlatma gerekir)</target> <note /> </trans-unit> <trans-unit id="Enable_all_features_in_opened_files_from_source_generators_experimental"> <source>Enable all features in opened files from source generators (experimental)</source> <target state="translated">Kaynak oluşturuculardan alınan açık sayfalarda tüm özellikleri etkinleştir (deneysel)</target> <note /> </trans-unit> <trans-unit id="Enable_file_logging_for_diagnostics"> <source>Enable file logging for diagnostics (logged in '%Temp%\Roslyn' folder)</source> <target state="translated">Tanılama için dosya günlüğünü etkinleştir (oturum açan '%Temp%\Roslyn' klasörü)</target> <note /> </trans-unit> <trans-unit id="Enable_pull_diagnostics_experimental_requires_restart"> <source>Enable 'pull' diagnostics (experimental, requires restart)</source> <target state="translated">'Pull' tanılamasını etkinleştir (deneysel, yeniden başlatma gerekir)</target> <note /> </trans-unit> <trans-unit id="Enabled"> <source>Enabled</source> <target state="translated">Etkin</target> <note /> </trans-unit> <trans-unit id="Enter_a_call_site_value_or_choose_a_different_value_injection_kind"> <source>Enter a call site value or choose a different value injection kind</source> <target state="translated">Bir çağrı sitesi değeri girin veya farklı bir değer yerleştirme tipi seçin</target> <note /> </trans-unit> <trans-unit id="Entire_repository"> <source>Entire repository</source> <target state="translated">Tüm depo</target> <note /> </trans-unit> <trans-unit id="Entire_solution"> <source>Entire solution</source> <target state="translated">Tüm çözüm</target> <note /> </trans-unit> <trans-unit id="Error"> <source>Error</source> <target state="translated">Hata</target> <note /> </trans-unit> <trans-unit id="Error_updating_suppressions_0"> <source>Error updating suppressions: {0}</source> <target state="translated">Gizlemeler güncellenirken hata oluştu: {0}</target> <note /> </trans-unit> <trans-unit id="Evaluating_0_tasks_in_queue"> <source>Evaluating ({0} tasks in queue)</source> <target state="translated">Değerlendiriliyor (kuyrukta {0} görev var)</target> <note /> </trans-unit> <trans-unit id="Extract_Base_Class"> <source>Extract Base Class</source> <target state="translated">Temel Sınıfı Ayıkla</target> <note /> </trans-unit> <trans-unit id="Finish"> <source>Finish</source> <target state="translated">Son</target> <note /> </trans-unit> <trans-unit id="Format_document"> <source>Format document</source> <target state="translated">Belgeyi biçimlendir</target> <note /> </trans-unit> <trans-unit id="Generate_dot_editorconfig_file_from_settings"> <source>Generate .editorconfig file from settings</source> <target state="translated">Ayarlardan .editorconfig dosyası oluştur</target> <note /> </trans-unit> <trans-unit id="Highlight_related_components_under_cursor"> <source>Highlight related components under cursor</source> <target state="translated">İmlecin altında ilgili bileşenleri vurgula</target> <note /> </trans-unit> <trans-unit id="Id"> <source>Id</source> <target state="translated">Kimlik</target> <note /> </trans-unit> <trans-unit id="Implemented_interfaces"> <source>Implemented interfaces</source> <target state="new">Implemented interfaces</target> <note /> </trans-unit> <trans-unit id="Implemented_members"> <source>Implemented members</source> <target state="translated">Uygulanan üyeler</target> <note /> </trans-unit> <trans-unit id="Implementing_members"> <source>Implementing members</source> <target state="translated">Üyeleri uygulama</target> <note /> </trans-unit> <trans-unit id="Implementing_types"> <source>Implementing types</source> <target state="new">Implementing types</target> <note /> </trans-unit> <trans-unit id="In_other_operators"> <source>In other operators</source> <target state="translated">Diğer işleçlerde</target> <note /> </trans-unit> <trans-unit id="Index"> <source>Index</source> <target state="translated">Dizin</target> <note>Index of parameter in original signature</note> </trans-unit> <trans-unit id="Infer_from_context"> <source>Infer from context</source> <target state="translated">Bağlamdan çıkarsa</target> <note /> </trans-unit> <trans-unit id="Indexed_in_organization"> <source>Indexed in organization</source> <target state="translated">Kuruluş içinde dizini oluşturulmuş</target> <note /> </trans-unit> <trans-unit id="Indexed_in_repo"> <source>Indexed in repo</source> <target state="translated">Depo içinde dizini oluşturulmuş</target> <note /> </trans-unit> <trans-unit id="Inheritance_Margin_experimental"> <source>Inheritance Margin (experimental)</source> <target state="translated">Devralma Marjı (deneysel)</target> <note /> </trans-unit> <trans-unit id="Inherited_interfaces"> <source>Inherited interfaces</source> <target state="new">Inherited interfaces</target> <note /> </trans-unit> <trans-unit id="Inline_Hints_experimental"> <source>Inline Hints (experimental)</source> <target state="translated">Satır İçi İpuçları (deneysel)</target> <note /> </trans-unit> <trans-unit id="Inserting_call_site_value_0"> <source>Inserting call site value '{0}'</source> <target state="translated">Çağırma yeri değeri '{0}' ekleniyor</target> <note /> </trans-unit> <trans-unit id="Install_Microsoft_recommended_Roslyn_analyzers_which_provide_additional_diagnostics_and_fixes_for_common_API_design_security_performance_and_reliability_issues"> <source>Install Microsoft-recommended Roslyn analyzers, which provide additional diagnostics and fixes for common API design, security, performance, and reliability issues</source> <target state="translated">Microsoft'un önerdiği, genel API tasarımı, güvenlik, performans ve güvenilirlik sorunları için ek tanılama ve düzeltmeler sağlayan Roslyn çözümleyicilerini yükleyin</target> <note /> </trans-unit> <trans-unit id="Interface_cannot_have_field"> <source>Interface cannot have field.</source> <target state="translated">Arabirimde alan olamaz.</target> <note /> </trans-unit> <trans-unit id="IntroduceUndefinedTodoVariables"> <source>Introduce undefined TODO variables</source> <target state="translated">Tanımsız TODO değişkenlerini tanıtın</target> <note>"TODO" is an indicator that more work should be done at the location where the TODO is inserted</note> </trans-unit> <trans-unit id="Item_origin"> <source>Item origin</source> <target state="translated">Öğe çıkış noktası</target> <note /> </trans-unit> <trans-unit id="Keep"> <source>Keep</source> <target state="translated">Koru</target> <note /> </trans-unit> <trans-unit id="Keep_all_parentheses_in_colon"> <source>Keep all parentheses in:</source> <target state="translated">Şunun içindeki tüm parantezleri tut:</target> <note /> </trans-unit> <trans-unit id="Kind"> <source>Kind</source> <target state="translated">Tür</target> <note /> </trans-unit> <trans-unit id="Live_analysis_VSIX_extension"> <source>Live analysis (VSIX extension)</source> <target state="translated">Canlı analiz (VSIX uzantısı)</target> <note /> </trans-unit> <trans-unit id="Loaded_items"> <source>Loaded items</source> <target state="translated">Öğeler yüklendi</target> <note /> </trans-unit> <trans-unit id="Loaded_solution"> <source>Loaded solution</source> <target state="translated">Çözüm yüklendi</target> <note /> </trans-unit> <trans-unit id="Local"> <source>Local</source> <target state="translated">Yerel</target> <note /> </trans-unit> <trans-unit id="Local_metadata"> <source>Local metadata</source> <target state="translated">Yerel meta veriler</target> <note /> </trans-unit> <trans-unit id="Location"> <source>Location</source> <target state="new">Location</target> <note /> </trans-unit> <trans-unit id="Make_0_abstract"> <source>Make '{0}' abstract</source> <target state="translated">'{0}' değerini soyut yap</target> <note /> </trans-unit> <trans-unit id="Make_abstract"> <source>Make abstract</source> <target state="translated">Soyut yap</target> <note /> </trans-unit> <trans-unit id="Members"> <source>Members</source> <target state="translated">Üyeler</target> <note /> </trans-unit> <trans-unit id="Modifier_preferences_colon"> <source>Modifier preferences:</source> <target state="translated">Değiştirici tercihleri:</target> <note /> </trans-unit> <trans-unit id="Move_to_namespace"> <source>Move to Namespace</source> <target state="translated">Ad Alanına Taşı</target> <note /> </trans-unit> <trans-unit id="Multiple_members_are_inherited"> <source>Multiple members are inherited</source> <target state="translated">Birden fazla üye devralındı</target> <note /> </trans-unit> <trans-unit id="Multiple_members_are_inherited_on_line_0"> <source>Multiple members are inherited on line {0}</source> <target state="translated">{0}. satırda birden fazla üye devralındı</target> <note>Line number info is needed for accessibility purpose.</note> </trans-unit> <trans-unit id="Name_conflicts_with_an_existing_type_name"> <source>Name conflicts with an existing type name.</source> <target state="translated">Ad, mevcut bir tür adıyla çakışıyor.</target> <note /> </trans-unit> <trans-unit id="Name_is_not_a_valid_0_identifier"> <source>Name is not a valid {0} identifier.</source> <target state="translated">Ad geçerli bir {0} tanımlayıcısı değil.</target> <note /> </trans-unit> <trans-unit id="Namespace"> <source>Namespace</source> <target state="translated">Ad alanı</target> <note /> </trans-unit> <trans-unit id="Namespace_0"> <source>Namespace: '{0}'</source> <target state="translated">Ad alanı: '{0}'</target> <note /> </trans-unit> <trans-unit id="Namespace_declarations"> <source>Namespace declarations</source> <target state="new">Namespace declarations</target> <note /> </trans-unit> <trans-unit id="NamingSpecification_CSharp_Class"> <source>class</source> <target state="new">class</target> <note>{Locked} This string can be found under "Tools | Options | Text Editor | C# | Code Style | Naming | Manage Specifications | + | Symbol kinds". All of the "NamingSpecification_CSharp_*" strings represent language constructs, and some of them are also actual keywords (including this one).</note> </trans-unit> <trans-unit id="NamingSpecification_CSharp_Delegate"> <source>delegate</source> <target state="new">delegate</target> <note>{Locked} This string can be found under "Tools | Options | Text Editor | C# | Code Style | Naming | Manage Specifications | + | Symbol kinds". All of the "NamingSpecification_CSharp_*" strings represent language constructs, and some of them are also actual keywords (including this one).</note> </trans-unit> <trans-unit id="NamingSpecification_CSharp_Enum"> <source>enum</source> <target state="new">enum</target> <note>{Locked} This string can be found under "Tools | Options | Text Editor | C# | Code Style | Naming | Manage Specifications | + | Symbol kinds". All of the "NamingSpecification_CSharp_*" strings represent language constructs, and some of them are also actual keywords (including this one).</note> </trans-unit> <trans-unit id="NamingSpecification_CSharp_Event"> <source>event</source> <target state="new">event</target> <note>{Locked} This string can be found under "Tools | Options | Text Editor | C# | Code Style | Naming | Manage Specifications | + | Symbol kinds". All of the "NamingSpecification_CSharp_*" strings represent language constructs, and some of them are also actual keywords (including this one).</note> </trans-unit> <trans-unit id="NamingSpecification_CSharp_Field"> <source>field</source> <target state="translated">alan</target> <note>This string can be found under "Tools | Options | Text Editor | C# | Code Style | Naming | Manage Specifications | + | Symbol kinds". All of the "NamingSpecification_CSharp_*" strings represent language constructs, and some of them are also actual keywords (NOT this one). Refers to the C# programming language concept of a "field" (which stores data).</note> </trans-unit> <trans-unit id="NamingSpecification_CSharp_Interface"> <source>interface</source> <target state="new">interface</target> <note>{Locked} This string can be found under "Tools | Options | Text Editor | C# | Code Style | Naming | Manage Specifications | + | Symbol kinds". All of the "NamingSpecification_CSharp_*" strings represent language constructs, and some of them are also actual keywords (including this one).</note> </trans-unit> <trans-unit id="NamingSpecification_CSharp_Local"> <source>local</source> <target state="translated">yerel</target> <note>This string can be found under "Tools | Options | Text Editor | C# | Code Style | Naming | Manage Specifications | + | Symbol kinds". All of the "NamingSpecification_CSharp_*" strings represent language constructs, and some of them are also actual keywords (NOT this one). Refers to the C# language concept of a "local variable".</note> </trans-unit> <trans-unit id="NamingSpecification_CSharp_LocalFunction"> <source>local function</source> <target state="translated">yerel işlev</target> <note>This string can be found under "Tools | Options | Text Editor | C# | Code Style | Naming | Manage Specifications | + | Symbol kinds". All of the "NamingSpecification_CSharp_*" strings represent language constructs, and some of them are also actual keywords (NOT this one). Refers to the C# language concept of a "local function" that exists locally within another function.</note> </trans-unit> <trans-unit id="NamingSpecification_CSharp_Method"> <source>method</source> <target state="translated">yöntem</target> <note>This string can be found under "Tools | Options | Text Editor | C# | Code Style | Naming | Manage Specifications | + | Symbol kinds". All of the "NamingSpecification_CSharp_*" strings represent language constructs, and some of them are also actual keywords (NOT this one). Refers to the C# language concept of a "method" that can be called by other code.</note> </trans-unit> <trans-unit id="NamingSpecification_CSharp_Namespace"> <source>namespace</source> <target state="new">namespace</target> <note>{Locked} This string can be found under "Tools | Options | Text Editor | C# | Code Style | Naming | Manage Specifications | + | Symbol kinds". All of the "NamingSpecification_CSharp_*" strings represent language constructs, and some of them are also actual keywords (including this one).</note> </trans-unit> <trans-unit id="NamingSpecification_CSharp_Parameter"> <source>parameter</source> <target state="translated">parametre</target> <note>This string can be found under "Tools | Options | Text Editor | C# | Code Style | Naming | Manage Specifications | + | Symbol kinds". All of the "NamingSpecification_CSharp_*" strings represent language constructs, and some of them are also actual keywords (NOT this one). Refers to the C# language concept of a "parameter" being passed to a method.</note> </trans-unit> <trans-unit id="NamingSpecification_CSharp_Property"> <source>property</source> <target state="translated">özellik</target> <note>This string can be found under "Tools | Options | Text Editor | C# | Code Style | Naming | Manage Specifications | + | Symbol kinds". All of the "NamingSpecification_CSharp_*" strings represent language constructs, and some of them are also actual keywords (NOT this one). Refers to the C# language concept of a "property" (which allows for the retrieval of data).</note> </trans-unit> <trans-unit id="NamingSpecification_CSharp_Struct"> <source>struct</source> <target state="new">struct</target> <note>{Locked} This string can be found under "Tools | Options | Text Editor | C# | Code Style | Naming | Manage Specifications | + | Symbol kinds". All of the "NamingSpecification_CSharp_*" strings represent language constructs, and some of them are also actual keywords (including this one).</note> </trans-unit> <trans-unit id="NamingSpecification_CSharp_TypeParameter"> <source>type parameter</source> <target state="translated">tür parametresi</target> <note>This string can be found under "Tools | Options | Text Editor | C# | Code Style | Naming | Manage Specifications | + | Symbol kinds". All of the "NamingSpecification_CSharp_*" strings represent language constructs, and some of them are also actual keywords (NOT this one). Refers to the C# language concept of a "type parameter".</note> </trans-unit> <trans-unit id="NamingSpecification_VisualBasic_Class"> <source>Class</source> <target state="new">Class</target> <note>{Locked} This string can be found under "Tools | Options | Text Editor | Basic | Code Style | Naming | Manage Specifications | + | Symbol kinds". All of the "NamingSpecification_VisualBasic_*" strings represent language constructs, and some of them are also actual keywords (including this one).</note> </trans-unit> <trans-unit id="NamingSpecification_VisualBasic_Delegate"> <source>Delegate</source> <target state="new">Delegate</target> <note>{Locked} This string can be found under "Tools | Options | Text Editor | Basic | Code Style | Naming | Manage Specifications | + | Symbol kinds". All of the "NamingSpecification_VisualBasic_*" strings represent language constructs, and some of them are also actual keywords (including this one).</note> </trans-unit> <trans-unit id="NamingSpecification_VisualBasic_Enum"> <source>Enum</source> <target state="new">Enum</target> <note>{Locked} This string can be found under "Tools | Options | Text Editor | Basic | Code Style | Naming | Manage Specifications | + | Symbol kinds". All of the "NamingSpecification_VisualBasic_*" strings represent language constructs, and some of them are also actual keywords (including this one).</note> </trans-unit> <trans-unit id="NamingSpecification_VisualBasic_Event"> <source>Event</source> <target state="new">Event</target> <note>{Locked} This string can be found under "Tools | Options | Text Editor | Basic | Code Style | Naming | Manage Specifications | + | Symbol kinds". All of the "NamingSpecification_VisualBasic_*" strings represent language constructs, and some of them are also actual keywords (including this one).</note> </trans-unit> <trans-unit id="NamingSpecification_VisualBasic_Field"> <source>Field</source> <target state="translated">Alan</target> <note>This string can be found under "Tools | Options | Text Editor | Basic | Code Style | Naming | Manage Specifications | + | Symbol kinds". All of the "NamingSpecification_VisualBasic_*" strings represent language constructs, and some of them are also actual keywords (NOT this one). Refers to the Visual Basic language concept of a "field" (which stores data).</note> </trans-unit> <trans-unit id="NamingSpecification_VisualBasic_Interface"> <source>Interface</source> <target state="new">Interface</target> <note>{Locked} This string can be found under "Tools | Options | Text Editor | Basic | Code Style | Naming | Manage Specifications | + | Symbol kinds". All of the "NamingSpecification_VisualBasic_*" strings represent language constructs, and some of them are also actual keywords (including this one).</note> </trans-unit> <trans-unit id="NamingSpecification_VisualBasic_Local"> <source>Local</source> <target state="translated">Yerel</target> <note>This string can be found under "Tools | Options | Text Editor | Basic | Code Style | Naming | Manage Specifications | + | Symbol kinds". All of the "NamingSpecification_VisualBasic_*" strings represent language constructs, and some of them are also actual keywords (NOT this one). Refers to the Visual Basic language concept of a "local variable".</note> </trans-unit> <trans-unit id="NamingSpecification_VisualBasic_Method"> <source>Method</source> <target state="translated">yöntem</target> <note>This string can be found under "Tools | Options | Text Editor | Basic | Code Style | Naming | Manage Specifications | + | Symbol kinds". All of the "NamingSpecification_VisualBasic_*" strings represent language constructs, and some of them are also actual keywords (NOT this one). Refers to the Visual Basic language concept of a "method".</note> </trans-unit> <trans-unit id="NamingSpecification_VisualBasic_Module"> <source>Module</source> <target state="new">Module</target> <note>{Locked} This string can be found under "Tools | Options | Text Editor | Basic | Code Style | Naming | Manage Specifications | + | Symbol kinds". All of the "NamingSpecification_VisualBasic_*" strings represent language constructs, and some of them are also actual keywords (including this one).</note> </trans-unit> <trans-unit id="NamingSpecification_VisualBasic_Namespace"> <source>Namespace</source> <target state="new">Namespace</target> <note>{Locked} This string can be found under "Tools | Options | Text Editor | Basic | Code Style | Naming | Manage Specifications | + | Symbol kinds". All of the "NamingSpecification_VisualBasic_*" strings represent language constructs, and some of them are also actual keywords (including this one).</note> </trans-unit> <trans-unit id="NamingSpecification_VisualBasic_Parameter"> <source>Parameter</source> <target state="translated">Parametre</target> <note>This string can be found under "Tools | Options | Text Editor | Basic | Code Style | Naming | Manage Specifications | + | Symbol kinds". All of the "NamingSpecification_VisualBasic_*" strings represent language constructs, and some of them are also actual keywords (NOT this one). Refers to the Visual Basic language concept of a "parameter" which can be passed to a method.</note> </trans-unit> <trans-unit id="NamingSpecification_VisualBasic_Property"> <source>Property</source> <target state="new">Property</target> <note>{Locked} This string can be found under "Tools | Options | Text Editor | Basic | Code Style | Naming | Manage Specifications | + | Symbol kinds". All of the "NamingSpecification_VisualBasic_*" strings represent language constructs, and some of them are also actual keywords (including this one).</note> </trans-unit> <trans-unit id="NamingSpecification_VisualBasic_Structure"> <source>Structure</source> <target state="new">Structure</target> <note>{Locked} This string can be found under "Tools | Options | Text Editor | Basic | Code Style | Naming | Manage Specifications | + | Symbol kinds". All of the "NamingSpecification_VisualBasic_*" strings represent language constructs, and some of them are also actual keywords (including this one).</note> </trans-unit> <trans-unit id="NamingSpecification_VisualBasic_TypeParameter"> <source>Type Parameter</source> <target state="translated">Tür Parametresi</target> <note>This string can be found under "Tools | Options | Text Editor | Basic | Code Style | Naming | Manage Specifications | + | Symbol kinds". All of the "NamingSpecification_VisualBasic_*" strings represent language constructs, and some of them are also actual keywords (NOT this one). Refers to the Visual Basic language concept of a "type parameter".</note> </trans-unit> <trans-unit id="Naming_rules"> <source>Naming rules</source> <target state="translated">Adlandırma kuralları</target> <note /> </trans-unit> <trans-unit id="Navigate_to_0"> <source>Navigate to '{0}'</source> <target state="translated">'{0}' öğesine git</target> <note /> </trans-unit> <trans-unit id="Never_if_unnecessary"> <source>Never if unnecessary</source> <target state="translated">Gereksizse hiçbir zaman</target> <note /> </trans-unit> <trans-unit id="New_Type_Name_colon"> <source>New Type Name:</source> <target state="translated">Yeni Tür Adı:</target> <note /> </trans-unit> <trans-unit id="New_line_preferences_experimental_colon"> <source>New line preferences (experimental):</source> <target state="translated">Yeni satır tercihleri (deneysel):</target> <note /> </trans-unit> <trans-unit id="Newline_n"> <source>Newline (\\n)</source> <target state="translated">Yeni Satır (\\n)</target> <note /> </trans-unit> <trans-unit id="No_unused_references_were_found"> <source>No unused references were found.</source> <target state="translated">Kullanılmayan başvuru bulunamadı.</target> <note /> </trans-unit> <trans-unit id="Non_public_methods"> <source>Non-public methods</source> <target state="translated">Ortak olmayan yöntemler</target> <note /> </trans-unit> <trans-unit id="None"> <source>None</source> <target state="translated">yok</target> <note /> </trans-unit> <trans-unit id="Omit_only_for_optional_parameters"> <source>Omit (only for optional parameters)</source> <target state="translated">Atla (yalnızca isteğe bağlı parametreler için)</target> <note /> </trans-unit> <trans-unit id="Open_documents"> <source>Open documents</source> <target state="translated">Açık belgeler</target> <note /> </trans-unit> <trans-unit id="Optional_parameters_must_provide_a_default_value"> <source>Optional parameters must provide a default value</source> <target state="translated">İsteğe bağlı parametrelerde varsayılan değer sağlanmalıdır</target> <note /> </trans-unit> <trans-unit id="Optional_with_default_value_colon"> <source>Optional with default value:</source> <target state="translated">Varsayılan değerle isteğe bağlı:</target> <note /> </trans-unit> <trans-unit id="Other"> <source>Others</source> <target state="translated">Diğer</target> <note /> </trans-unit> <trans-unit id="Overridden_members"> <source>Overridden members</source> <target state="translated">Geçersiz kılınan üyeler</target> <note /> </trans-unit> <trans-unit id="Overriding_members"> <source>Overriding members</source> <target state="translated">Üyeleri geçersiz kılma</target> <note /> </trans-unit> <trans-unit id="Packages"> <source>Packages</source> <target state="translated">Paketler</target> <note /> </trans-unit> <trans-unit id="Parameter_Details"> <source>Parameter Details</source> <target state="translated">Parametre Ayrıntıları</target> <note /> </trans-unit> <trans-unit id="Parameter_Name"> <source>Parameter name:</source> <target state="translated">Parametre adı:</target> <note /> </trans-unit> <trans-unit id="Parameter_information"> <source>Parameter information</source> <target state="translated">Parametre bilgileri</target> <note /> </trans-unit> <trans-unit id="Parameter_kind"> <source>Parameter kind</source> <target state="translated">Parametre tipi</target> <note /> </trans-unit> <trans-unit id="Parameter_name_contains_invalid_characters"> <source>Parameter name contains invalid character(s).</source> <target state="translated">Parametre adı geçersiz karakterler içeriyor.</target> <note /> </trans-unit> <trans-unit id="Parameter_preferences_colon"> <source>Parameter preferences:</source> <target state="translated">Parametre tercihleri:</target> <note /> </trans-unit> <trans-unit id="Parameter_type_contains_invalid_characters"> <source>Parameter type contains invalid character(s).</source> <target state="translated">Parametre türü geçersiz karakterler içeriyor.</target> <note /> </trans-unit> <trans-unit id="Parentheses_preferences_colon"> <source>Parentheses preferences:</source> <target state="translated">Parantez tercihleri:</target> <note /> </trans-unit> <trans-unit id="Paused_0_tasks_in_queue"> <source>Paused ({0} tasks in queue)</source> <target state="translated">Duraklatıldı (kuyrukta {0} görev var)</target> <note /> </trans-unit> <trans-unit id="Please_enter_a_type_name"> <source>Please enter a type name</source> <target state="translated">Lütfen bir tür adı yazın</target> <note>"Type" is the programming language concept</note> </trans-unit> <trans-unit id="Prefer_System_HashCode_in_GetHashCode"> <source>Prefer 'System.HashCode' in 'GetHashCode'</source> <target state="translated">'GetHashCode' içinde 'System.HashCode' tercih et</target> <note /> </trans-unit> <trans-unit id="Prefer_compound_assignments"> <source>Prefer compound assignments</source> <target state="translated">Bileşik atamaları tercih et</target> <note /> </trans-unit> <trans-unit id="Prefer_index_operator"> <source>Prefer index operator</source> <target state="translated">Dizin işlecini tercih et</target> <note /> </trans-unit> <trans-unit id="Prefer_range_operator"> <source>Prefer range operator</source> <target state="translated">Aralık işlecini tercih et</target> <note /> </trans-unit> <trans-unit id="Prefer_readonly_fields"> <source>Prefer readonly fields</source> <target state="translated">Saltokunur alanları tercih et</target> <note /> </trans-unit> <trans-unit id="Prefer_simple_using_statement"> <source>Prefer simple 'using' statement</source> <target state="translated">Basit 'using' deyimini tercih et</target> <note /> </trans-unit> <trans-unit id="Prefer_simplified_boolean_expressions"> <source>Prefer simplified boolean expressions</source> <target state="translated">Basitleştirilmiş boolean ifadelerini tercih edin</target> <note /> </trans-unit> <trans-unit id="Prefer_static_local_functions"> <source>Prefer static local functions</source> <target state="translated">Statik yerel işlevleri tercih et</target> <note /> </trans-unit> <trans-unit id="Projects"> <source>Projects</source> <target state="translated">Projeler</target> <note /> </trans-unit> <trans-unit id="Pull_Members_Up"> <source>Pull Members Up</source> <target state="translated">Üyeleri Yukarı Çek</target> <note /> </trans-unit> <trans-unit id="Refactoring_Only"> <source>Refactoring Only</source> <target state="translated">Sadece Yeniden Düzenlenme</target> <note /> </trans-unit> <trans-unit id="Reference"> <source>Reference</source> <target state="translated">Başvuru</target> <note /> </trans-unit> <trans-unit id="Regular_Expressions"> <source>Regular Expressions</source> <target state="translated">Normal İfadeler</target> <note /> </trans-unit> <trans-unit id="Remove_All"> <source>Remove All</source> <target state="translated">Tümünü Kaldır</target> <note /> </trans-unit> <trans-unit id="Remove_Unused_References"> <source>Remove Unused References</source> <target state="translated">Kullanılmayan Başvuruları Kaldır</target> <note /> </trans-unit> <trans-unit id="Rename_0_to_1"> <source>Rename {0} to {1}</source> <target state="translated">{0} öğesini {1} olarak yeniden adlandır</target> <note /> </trans-unit> <trans-unit id="Report_invalid_regular_expressions"> <source>Report invalid regular expressions</source> <target state="translated">Geçersiz normal ifadeleri bildir</target> <note /> </trans-unit> <trans-unit id="Repository"> <source>Repository</source> <target state="translated">Depo</target> <note /> </trans-unit> <trans-unit id="Require_colon"> <source>Require:</source> <target state="translated">Gerektir:</target> <note /> </trans-unit> <trans-unit id="Required"> <source>Required</source> <target state="translated">Gerekli</target> <note /> </trans-unit> <trans-unit id="Requires_System_HashCode_be_present_in_project"> <source>Requires 'System.HashCode' be present in project</source> <target state="translated">Projede 'System.HashCode' bulunmasını gerektirir</target> <note /> </trans-unit> <trans-unit id="Reset_Visual_Studio_default_keymapping"> <source>Reset Visual Studio default keymapping</source> <target state="translated">Visual Studio varsayılan tuş eşlemesine sıfırla</target> <note /> </trans-unit> <trans-unit id="Review_Changes"> <source>Review Changes</source> <target state="translated">Değişiklikleri Gözden Geçir</target> <note /> </trans-unit> <trans-unit id="Run_Code_Analysis_on_0"> <source>Run Code Analysis on {0}</source> <target state="translated">{0} Öğesinde Code Analysis Çalıştır</target> <note /> </trans-unit> <trans-unit id="Running_code_analysis_for_0"> <source>Running code analysis for '{0}'...</source> <target state="translated">'{0}' için kod analizi çalıştırılıyor...</target> <note /> </trans-unit> <trans-unit id="Running_code_analysis_for_Solution"> <source>Running code analysis for Solution...</source> <target state="translated">Çözüm için kod analizi çalıştırılıyor...</target> <note /> </trans-unit> <trans-unit id="Running_low_priority_background_processes"> <source>Running low priority background processes</source> <target state="translated">Düşük öncelikli arka plan işlemleri çalıştırılıyor</target> <note /> </trans-unit> <trans-unit id="Save_dot_editorconfig_file"> <source>Save .editorconfig file</source> <target state="translated">.editorconfig dosyasını kaydet</target> <note /> </trans-unit> <trans-unit id="Search_Settings"> <source>Search Settings</source> <target state="translated">Arama Ayarları</target> <note /> </trans-unit> <trans-unit id="Select_an_appropriate_symbol_to_start_value_tracking"> <source>Select an appropriate symbol to start value tracking</source> <target state="new">Select an appropriate symbol to start value tracking</target> <note /> </trans-unit> <trans-unit id="Select_destination"> <source>Select destination</source> <target state="translated">Hedef seçin</target> <note /> </trans-unit> <trans-unit id="Select_Dependents"> <source>Select _Dependents</source> <target state="translated">_Bağımlıları Seçin</target> <note /> </trans-unit> <trans-unit id="Select_Public"> <source>Select _Public</source> <target state="translated">_Geneli Seçin</target> <note /> </trans-unit> <trans-unit id="Select_destination_and_members_to_pull_up"> <source>Select destination and members to pull up.</source> <target state="translated">Hedef ve yukarı çekilecek üyeleri seçin.</target> <note /> </trans-unit> <trans-unit id="Select_destination_colon"> <source>Select destination:</source> <target state="translated">Hedef seçin:</target> <note /> </trans-unit> <trans-unit id="Select_member"> <source>Select member</source> <target state="translated">Üye seçin</target> <note /> </trans-unit> <trans-unit id="Select_members_colon"> <source>Select members:</source> <target state="translated">Üye seçin:</target> <note /> </trans-unit> <trans-unit id="Show_Remove_Unused_References_command_in_Solution_Explorer_experimental"> <source>Show "Remove Unused References" command in Solution Explorer (experimental)</source> <target state="translated">Çözüm Gezgini'nde "Kullanılmayan Başvuruları Kaldır" komutunu göster (deneysel)</target> <note /> </trans-unit> <trans-unit id="Show_completion_list"> <source>Show completion list</source> <target state="translated">Tamamlama listesini göster</target> <note /> </trans-unit> <trans-unit id="Show_hints_for_everything_else"> <source>Show hints for everything else</source> <target state="translated">Diğer her şey için ipuçlarını göster</target> <note /> </trans-unit> <trans-unit id="Show_hints_for_implicit_object_creation"> <source>Show hints for implicit object creation</source> <target state="translated">Örtük nesne oluşturma ipuçlarını göster</target> <note /> </trans-unit> <trans-unit id="Show_hints_for_lambda_parameter_types"> <source>Show hints for lambda parameter types</source> <target state="translated">Lambda parametre türleri için ipuçlarını göster</target> <note /> </trans-unit> <trans-unit id="Show_hints_for_literals"> <source>Show hints for literals</source> <target state="translated">Sabit değerler için ipuçlarını göster</target> <note /> </trans-unit> <trans-unit id="Show_hints_for_variables_with_inferred_types"> <source>Show hints for variables with inferred types</source> <target state="translated">Çıkarsanan türlere sahip değişkenler için ipuçlarını göster</target> <note /> </trans-unit> <trans-unit id="Show_inheritance_margin"> <source>Show inheritance margin</source> <target state="translated">Devralma boşluğunu göster</target> <note /> </trans-unit> <trans-unit id="Skip_analyzers_for_implicitly_triggered_builds"> <source>Skip analyzers for implicitly triggered builds</source> <target state="new">Skip analyzers for implicitly triggered builds</target> <note /> </trans-unit> <trans-unit id="Some_color_scheme_colors_are_being_overridden_by_changes_made_in_the_Environment_Fonts_and_Colors_options_page_Choose_Use_Defaults_in_the_Fonts_and_Colors_page_to_revert_all_customizations"> <source>Some color scheme colors are being overridden by changes made in the Environment &gt; Fonts and Colors options page. Choose `Use Defaults` in the Fonts and Colors page to revert all customizations.</source> <target state="translated">Bazı renk düzeni renkleri, Ortam &gt; Yazı Tipleri ve Renkler seçenek sayfasında yapılan değişiklikler tarafından geçersiz kılınıyor. Tüm özelleştirmeleri geri döndürmek için Yazı Tipleri ve Renkler sayfasında `Varsayılanları Kullan` seçeneğini belirleyin.</target> <note /> </trans-unit> <trans-unit id="Suggestion"> <source>Suggestion</source> <target state="translated">Öneri</target> <note /> </trans-unit> <trans-unit id="Suppress_hints_when_parameter_name_matches_the_method_s_intent"> <source>Suppress hints when parameter name matches the method's intent</source> <target state="translated">Parametre adı metodun hedefi ile eşleştiğinde ipuçlarını gizle</target> <note /> </trans-unit> <trans-unit id="Suppress_hints_when_parameter_names_differ_only_by_suffix"> <source>Suppress hints when parameter names differ only by suffix</source> <target state="translated">Parametre adlarının yalnızca sonekleri farklı olduğunda ipuçlarını gizle</target> <note /> </trans-unit> <trans-unit id="Symbols_without_references"> <source>Symbols without references</source> <target state="translated">Başvuruları olmayan semboller</target> <note /> </trans-unit> <trans-unit id="Tab_twice_to_insert_arguments"> <source>Tab twice to insert arguments (experimental)</source> <target state="translated">Bağımsız değişkenleri eklemek için iki kez dokunun (deneysel)</target> <note /> </trans-unit> <trans-unit id="Target_Namespace_colon"> <source>Target Namespace:</source> <target state="translated">Hedef Ad Alanı:</target> <note /> </trans-unit> <trans-unit id="The_generator_0_that_generated_this_file_has_been_removed_from_the_project"> <source>The generator '{0}' that generated this file has been removed from the project; this file is no longer being included in your project.</source> <target state="translated">Bu dosyayı oluşturan '{0}' oluşturucusu projeden kaldırıldı; bu dosya artık projenize dahil edilmiyor.</target> <note /> </trans-unit> <trans-unit id="The_generator_0_that_generated_this_file_has_stopped_generating_this_file"> <source>The generator '{0}' that generated this file has stopped generating this file; this file is no longer being included in your project.</source> <target state="translated">Bu dosyayı oluşturan '{0}' oluşturucusu bu dosyayı oluşturmayı durdurdu; bu dosya artık projenize dahil edilmiyor.</target> <note /> </trans-unit> <trans-unit id="This_action_cannot_be_undone_Do_you_wish_to_continue"> <source>This action cannot be undone. Do you wish to continue?</source> <target state="translated">Bu işlem geri alınamaz. Devam etmek istiyor musunuz?</target> <note /> </trans-unit> <trans-unit id="This_file_is_autogenerated_by_0_and_cannot_be_edited"> <source>This file is auto-generated by the generator '{0}' and cannot be edited.</source> <target state="translated">Bu dosya, '{0}' oluşturucusu tarafından otomatik olarak oluşturuldu ve düzenlenemez.</target> <note /> </trans-unit> <trans-unit id="This_is_an_invalid_namespace"> <source>This is an invalid namespace</source> <target state="translated">Bu geçersiz bir ad alanı</target> <note /> </trans-unit> <trans-unit id="Title"> <source>Title</source> <target state="translated">Başlık</target> <note /> </trans-unit> <trans-unit id="Type_Name"> <source>Type name:</source> <target state="translated">Tür adı:</target> <note /> </trans-unit> <trans-unit id="Type_name_has_a_syntax_error"> <source>Type name has a syntax error</source> <target state="translated">Tür adında söz dizimi hatası var</target> <note>"Type" is the programming language concept</note> </trans-unit> <trans-unit id="Type_name_is_not_recognized"> <source>Type name is not recognized</source> <target state="translated">Tür adı tanınmıyor</target> <note>"Type" is the programming language concept</note> </trans-unit> <trans-unit id="Type_name_is_recognized"> <source>Type name is recognized</source> <target state="translated">Tür adı tanınıyor</target> <note>"Type" is the programming language concept</note> </trans-unit> <trans-unit id="Underline_reassigned_variables"> <source>Underline reassigned variables</source> <target state="new">Underline reassigned variables</target> <note /> </trans-unit> <trans-unit id="Unused_value_is_explicitly_assigned_to_an_unused_local"> <source>Unused value is explicitly assigned to an unused local</source> <target state="translated">Kullanılmayan değer açıkça kullanılmayan bir yerele atandı</target> <note /> </trans-unit> <trans-unit id="Unused_value_is_explicitly_assigned_to_discard"> <source>Unused value is explicitly assigned to discard</source> <target state="translated">Kullanılmayan değer açıkça atılmak üzere atandı</target> <note /> </trans-unit> <trans-unit id="Updating_project_references"> <source>Updating project references...</source> <target state="translated">Proje başvuruları güncelleştiriliyor...</target> <note /> </trans-unit> <trans-unit id="Updating_severity"> <source>Updating severity</source> <target state="translated">Önem derecesi güncelleştiriliyor</target> <note /> </trans-unit> <trans-unit id="Use_64_bit_process_for_code_analysis_requires_restart"> <source>Use 64-bit process for code analysis (requires restart)</source> <target state="translated">Kod analizi için 64 bit işlemi kullanın (yeniden başlatma gerekir)</target> <note /> </trans-unit> <trans-unit id="Use_expression_body_for_lambdas"> <source>Use expression body for lambdas</source> <target state="translated">Lambdalar için ifade gövdesi kullan</target> <note /> </trans-unit> <trans-unit id="Use_expression_body_for_local_functions"> <source>Use expression body for local functions</source> <target state="translated">Yerel işlevler için ifade gövdesi kullan</target> <note /> </trans-unit> <trans-unit id="Use_named_argument"> <source>Use named argument</source> <target state="translated">Adlandırılmış bağımsız değişken kullan</target> <note>"argument" is a programming term for a value passed to a function</note> </trans-unit> <trans-unit id="Value"> <source>Value</source> <target state="translated">Değer</target> <note /> </trans-unit> <trans-unit id="Value_Tracking"> <source>Value Tracking</source> <target state="new">Value Tracking</target> <note>Title of the "Value Tracking" tool window. "Value" is the variable/symbol and "Tracking" is the action the tool is doing to follow where the value can originate from.</note> </trans-unit> <trans-unit id="Value_assigned_here_is_never_used"> <source>Value assigned here is never used</source> <target state="translated">Burada atanan değer hiçbir zaman kullanılmadı</target> <note /> </trans-unit> <trans-unit id="Value_colon"> <source>Value:</source> <target state="translated">Değer:</target> <note /> </trans-unit> <trans-unit id="Value_returned_by_invocation_is_implicitly_ignored"> <source>Value returned by invocation is implicitly ignored</source> <target state="translated">Çağrı ile döndürülen değer örtük olarak yok sayıldı</target> <note /> </trans-unit> <trans-unit id="Value_to_inject_at_call_sites"> <source>Value to inject at call sites</source> <target state="translated">Çağrı sitelerinde eklenecek değer</target> <note /> </trans-unit> <trans-unit id="Visual_Studio_2017"> <source>Visual Studio 2017</source> <target state="translated">Visual Studio 2017</target> <note /> </trans-unit> <trans-unit id="Visual_Studio_2019"> <source>Visual Studio 2019</source> <target state="translated">Visual Studio 2019</target> <note /> </trans-unit> <trans-unit id="Visual_Studio_Settings"> <source>Visual Studio Settings</source> <target state="new">Visual Studio Settings</target> <note /> </trans-unit> <trans-unit id="Warning"> <source>Warning</source> <target state="translated">Uyarı</target> <note /> </trans-unit> <trans-unit id="Warning_colon_duplicate_parameter_name"> <source>Warning: duplicate parameter name</source> <target state="translated">Uyarı: Yinelenen parametre adı</target> <note /> </trans-unit> <trans-unit id="Warning_colon_type_does_not_bind"> <source>Warning: type does not bind</source> <target state="translated">Uyarı: Tür bağlamıyor</target> <note /> </trans-unit> <trans-unit id="We_notice_you_suspended_0_Reset_keymappings_to_continue_to_navigate_and_refactor"> <source>We notice you suspended '{0}'. Reset keymappings to continue to navigate and refactor.</source> <target state="translated">'{0}' öğesini askıya aldığınızı fark ettik. Gezintiye ve yeniden düzenlemeye devam etmek için tuş eşlemelerini sıfırlayın.</target> <note /> </trans-unit> <trans-unit id="This_workspace_does_not_support_updating_Visual_Basic_compilation_options"> <source>This workspace does not support updating Visual Basic compilation options.</source> <target state="translated">Bu çalışma alanı Visual Basic derleme seçeneklerinin güncelleştirilmesini desteklemiyor.</target> <note /> </trans-unit> <trans-unit id="Whitespace"> <source>Whitespace</source> <target state="new">Whitespace</target> <note /> </trans-unit> <trans-unit id="You_must_change_the_signature"> <source>You must change the signature</source> <target state="translated">İmzayı değiştirmelisiniz</target> <note>"signature" here means the definition of a method</note> </trans-unit> <trans-unit id="You_must_select_at_least_one_member"> <source>You must select at least one member.</source> <target state="translated">En az bir üye seçmelisiniz.</target> <note /> </trans-unit> <trans-unit id="Illegal_characters_in_path"> <source>Illegal characters in path.</source> <target state="translated">Yolda geçersiz karakterler var.</target> <note /> </trans-unit> <trans-unit id="File_name_must_have_the_0_extension"> <source>File name must have the "{0}" extension.</source> <target state="translated">Dosya adı "{0}" uzantısını içermelidir.</target> <note /> </trans-unit> <trans-unit id="Debugger"> <source>Debugger</source> <target state="translated">Hata Ayıklayıcı</target> <note /> </trans-unit> <trans-unit id="Determining_breakpoint_location"> <source>Determining breakpoint location...</source> <target state="translated">Kesme noktası konumu belirleniyor...</target> <note /> </trans-unit> <trans-unit id="Determining_autos"> <source>Determining autos...</source> <target state="translated">İfade ve değişkenler belirleniyor...</target> <note /> </trans-unit> <trans-unit id="Resolving_breakpoint_location"> <source>Resolving breakpoint location...</source> <target state="translated">Kesme noktası konumu çözümleniyor...</target> <note /> </trans-unit> <trans-unit id="Validating_breakpoint_location"> <source>Validating breakpoint location...</source> <target state="translated">Kesme noktası konumu doğrulanıyor...</target> <note /> </trans-unit> <trans-unit id="Getting_DataTip_text"> <source>Getting DataTip text...</source> <target state="translated">DataTip metni alınıyor...</target> <note /> </trans-unit> <trans-unit id="Preview_unavailable"> <source>Preview unavailable</source> <target state="translated">Önizleme kullanılamıyor</target> <note /> </trans-unit> <trans-unit id="Overrides_"> <source>Overrides</source> <target state="translated">Geçersiz Kılan</target> <note /> </trans-unit> <trans-unit id="Overridden_By"> <source>Overridden By</source> <target state="translated">Geçersiz Kılınan</target> <note /> </trans-unit> <trans-unit id="Inherits_"> <source>Inherits</source> <target state="translated">Devralınan</target> <note /> </trans-unit> <trans-unit id="Inherited_By"> <source>Inherited By</source> <target state="translated">Devralan</target> <note /> </trans-unit> <trans-unit id="Implements_"> <source>Implements</source> <target state="translated">Uygulanan</target> <note /> </trans-unit> <trans-unit id="Implemented_By"> <source>Implemented By</source> <target state="translated">Uygulayan</target> <note /> </trans-unit> <trans-unit id="Maximum_number_of_documents_are_open"> <source>Maximum number of documents are open.</source> <target state="translated">Açılabilecek en fazla belge sayısına ulaşıldı.</target> <note /> </trans-unit> <trans-unit id="Failed_to_create_document_in_miscellaneous_files_project"> <source>Failed to create document in miscellaneous files project.</source> <target state="translated">Diğer Dosyalar projesinde belge oluşturulamadı.</target> <note /> </trans-unit> <trans-unit id="Invalid_access"> <source>Invalid access.</source> <target state="translated">Geçersiz erişim.</target> <note /> </trans-unit> <trans-unit id="The_following_references_were_not_found_0_Please_locate_and_add_them_manually"> <source>The following references were not found. {0}Please locate and add them manually.</source> <target state="translated">Aşağıdaki başvurular bulunamadı. {0}Lütfen bu başvuruları el ile bulun ve ekleyin.</target> <note /> </trans-unit> <trans-unit id="End_position_must_be_start_position"> <source>End position must be &gt;= start position</source> <target state="translated">Bitiş konumu, başlangıç konumuna eşit veya bundan sonra olmalıdır</target> <note /> </trans-unit> <trans-unit id="Not_a_valid_value"> <source>Not a valid value</source> <target state="translated">Geçerli bir değer değil</target> <note /> </trans-unit> <trans-unit id="_0_is_inherited"> <source>'{0}' is inherited</source> <target state="translated">'{0}' devralındı</target> <note /> </trans-unit> <trans-unit id="_0_will_be_changed_to_abstract"> <source>'{0}' will be changed to abstract.</source> <target state="translated">'{0}' soyut olacak şekilde değiştirildi.</target> <note /> </trans-unit> <trans-unit id="_0_will_be_changed_to_non_static"> <source>'{0}' will be changed to non-static.</source> <target state="translated">'{0}' statik olmayacak şekilde değiştirildi.</target> <note /> </trans-unit> <trans-unit id="_0_will_be_changed_to_public"> <source>'{0}' will be changed to public.</source> <target state="translated">'{0}' ortak olacak şekilde değiştirildi.</target> <note /> </trans-unit> <trans-unit id="generated_by_0_suffix"> <source>[generated by {0}]</source> <target state="translated">[{0} tarafından oluşturuldu]</target> <note>{0} is the name of a generator.</note> </trans-unit> <trans-unit id="generated_suffix"> <source>[generated]</source> <target state="translated">[oluşturuldu]</target> <note /> </trans-unit> <trans-unit id="given_workspace_doesn_t_support_undo"> <source>given workspace doesn't support undo</source> <target state="translated">sağlanan çalışma alanı, geri almayı desteklemiyor</target> <note /> </trans-unit> <trans-unit id="Add_a_reference_to_0"> <source>Add a reference to '{0}'</source> <target state="translated">'{0}' öğesine başvuru ekleyin</target> <note /> </trans-unit> <trans-unit id="Event_type_is_invalid"> <source>Event type is invalid</source> <target state="translated">Olay türü geçersiz</target> <note /> </trans-unit> <trans-unit id="Can_t_find_where_to_insert_member"> <source>Can't find where to insert member</source> <target state="translated">Üyenin ekleneceği konum bulunamıyor</target> <note /> </trans-unit> <trans-unit id="Can_t_rename_other_elements"> <source>Can't rename 'other' elements</source> <target state="translated">other' öğeleri yeniden adlandırılamıyor</target> <note /> </trans-unit> <trans-unit id="Unknown_rename_type"> <source>Unknown rename type</source> <target state="translated">Bilinmeyen yeniden adlandırma türü</target> <note /> </trans-unit> <trans-unit id="IDs_are_not_supported_for_this_symbol_type"> <source>IDs are not supported for this symbol type.</source> <target state="translated">Bu sembol türü için kimlikler desteklenmiyor.</target> <note /> </trans-unit> <trans-unit id="Can_t_create_a_node_id_for_this_symbol_kind_colon_0"> <source>Can't create a node id for this symbol kind: '{0}'</source> <target state="translated">'{0}' sembol türü için düğüm kimliği oluşturulamıyor</target> <note /> </trans-unit> <trans-unit id="Project_References"> <source>Project References</source> <target state="translated">Proje Başvuruları</target> <note /> </trans-unit> <trans-unit id="Base_Types"> <source>Base Types</source> <target state="translated">Temel Türler</target> <note /> </trans-unit> <trans-unit id="Miscellaneous_Files"> <source>Miscellaneous Files</source> <target state="translated">Diğer Dosyalar</target> <note /> </trans-unit> <trans-unit id="Could_not_find_project_0"> <source>Could not find project '{0}'</source> <target state="translated">'{0}' adlı proje bulunamadı</target> <note /> </trans-unit> <trans-unit id="Could_not_find_location_of_folder_on_disk"> <source>Could not find location of folder on disk</source> <target state="translated">Diskte klasörün konumu bulunamadı</target> <note /> </trans-unit> <trans-unit id="Assembly"> <source>Assembly </source> <target state="translated">Bütünleştirilmiş Kod </target> <note /> </trans-unit> <trans-unit id="Exceptions_colon"> <source>Exceptions:</source> <target state="translated">Özel Durumlar:</target> <note /> </trans-unit> <trans-unit id="Member_of_0"> <source>Member of {0}</source> <target state="translated">{0} üyesi</target> <note /> </trans-unit> <trans-unit id="Parameters_colon1"> <source>Parameters:</source> <target state="translated">Parametreler:</target> <note /> </trans-unit> <trans-unit id="Project"> <source>Project </source> <target state="translated">Proje </target> <note /> </trans-unit> <trans-unit id="Remarks_colon"> <source>Remarks:</source> <target state="translated">Açıklamalar:</target> <note /> </trans-unit> <trans-unit id="Returns_colon"> <source>Returns:</source> <target state="translated">Döndürülenler:</target> <note /> </trans-unit> <trans-unit id="Summary_colon"> <source>Summary:</source> <target state="translated">Özet:</target> <note /> </trans-unit> <trans-unit id="Type_Parameters_colon"> <source>Type Parameters:</source> <target state="translated">Tür Parametreleri:</target> <note /> </trans-unit> <trans-unit id="File_already_exists"> <source>File already exists</source> <target state="translated">Dosya zaten var</target> <note /> </trans-unit> <trans-unit id="File_path_cannot_use_reserved_keywords"> <source>File path cannot use reserved keywords</source> <target state="translated">Dosya yolunda ayrılmış anahtar sözcükler kullanılamaz</target> <note /> </trans-unit> <trans-unit id="DocumentPath_is_illegal"> <source>DocumentPath is illegal</source> <target state="translated">DocumentPath geçersiz</target> <note /> </trans-unit> <trans-unit id="Project_Path_is_illegal"> <source>Project Path is illegal</source> <target state="translated">Proje Yolu geçersiz</target> <note /> </trans-unit> <trans-unit id="Path_cannot_have_empty_filename"> <source>Path cannot have empty filename</source> <target state="translated">Yoldaki dosya adı boş olamaz</target> <note /> </trans-unit> <trans-unit id="The_given_DocumentId_did_not_come_from_the_Visual_Studio_workspace"> <source>The given DocumentId did not come from the Visual Studio workspace.</source> <target state="translated">Sağlanan DocumentId değeri, Visual Studio çalışma alanında bulunmuyor.</target> <note /> </trans-unit> <trans-unit id="Project_colon_0_1_Use_the_dropdown_to_view_and_switch_to_other_projects_this_file_may_belong_to"> <source>Project: {0} ({1}) Use the dropdown to view and switch to other projects this file may belong to.</source> <target state="translated">Proje: {0} ({1}) Bu dosyanın ait olabileceği diğer projeleri görüntülemek ve bunlara geçiş yapmak için açılan menüyü kullanın.</target> <note /> </trans-unit> <trans-unit id="_0_Use_the_dropdown_to_view_and_navigate_to_other_items_in_this_file"> <source>{0} Use the dropdown to view and navigate to other items in this file.</source> <target state="translated">{0} Bu dosyadaki diğer öğeleri görüntülemek ve bu öğelere gitmek için açılan menüyü kullanın.</target> <note /> </trans-unit> <trans-unit id="Project_colon_0_Use_the_dropdown_to_view_and_switch_to_other_projects_this_file_may_belong_to"> <source>Project: {0} Use the dropdown to view and switch to other projects this file may belong to.</source> <target state="translated">Proje: {0} Bu dosyanın ait olabileceği diğer projeleri görüntülemek ve bunlara geçiş yapmak için açılan menüyü kullanın.</target> <note /> </trans-unit> <trans-unit id="AnalyzerChangedOnDisk"> <source>AnalyzerChangedOnDisk</source> <target state="translated">AnalyzerChangedOnDisk</target> <note /> </trans-unit> <trans-unit id="The_analyzer_assembly_0_has_changed_Diagnostics_may_be_incorrect_until_Visual_Studio_is_restarted"> <source>The analyzer assembly '{0}' has changed. Diagnostics may be incorrect until Visual Studio is restarted.</source> <target state="translated">Çözümleyici bütünleştirilmiş kodu '{0}' değiştirildi. Visual Studio yeniden başlatılmazsa tanılama yanlış olabilir.</target> <note /> </trans-unit> <trans-unit id="CSharp_VB_Diagnostics_Table_Data_Source"> <source>C#/VB Diagnostics Table Data Source</source> <target state="translated">C#/VB Tanılama Tablosu Veri Kaynağı</target> <note /> </trans-unit> <trans-unit id="CSharp_VB_Todo_List_Table_Data_Source"> <source>C#/VB Todo List Table Data Source</source> <target state="translated">C#/VB Yapılacaklar Listesi Tablosu Veri Kaynağı</target> <note /> </trans-unit> <trans-unit id="Cancel"> <source>Cancel</source> <target state="translated">İptal</target> <note /> </trans-unit> <trans-unit id="Deselect_All"> <source>_Deselect All</source> <target state="translated">_Tüm Seçimleri Kaldır</target> <note /> </trans-unit> <trans-unit id="Extract_Interface"> <source>Extract Interface</source> <target state="translated">Arabirimi Ayıkla</target> <note /> </trans-unit> <trans-unit id="Generated_name_colon"> <source>Generated name:</source> <target state="translated">Oluşturulan ad:</target> <note /> </trans-unit> <trans-unit id="New_file_name_colon"> <source>New _file name:</source> <target state="translated">Yeni _dosya adı:</target> <note /> </trans-unit> <trans-unit id="New_interface_name_colon"> <source>New _interface name:</source> <target state="translated">Yeni _arabirim adı:</target> <note /> </trans-unit> <trans-unit id="OK"> <source>OK</source> <target state="translated">Tamam</target> <note /> </trans-unit> <trans-unit id="Select_All"> <source>_Select All</source> <target state="translated">_Tümünü Seç</target> <note /> </trans-unit> <trans-unit id="Select_public_members_to_form_interface"> <source>Select public _members to form interface</source> <target state="translated">Arabirim oluşturmak için ortak _üyeleri seçin</target> <note /> </trans-unit> <trans-unit id="Access_colon"> <source>_Access:</source> <target state="translated">_Erişim:</target> <note /> </trans-unit> <trans-unit id="Add_to_existing_file"> <source>Add to _existing file</source> <target state="translated">_Mevcut dosyaya ekle</target> <note /> </trans-unit> <trans-unit id="Change_Signature"> <source>Change Signature</source> <target state="translated">İmzayı Değiştir</target> <note /> </trans-unit> <trans-unit id="Create_new_file"> <source>_Create new file</source> <target state="translated">Yeni dosya _oluştur</target> <note /> </trans-unit> <trans-unit id="Default_"> <source>Default</source> <target state="translated">Varsayılan</target> <note /> </trans-unit> <trans-unit id="File_Name_colon"> <source>File Name:</source> <target state="translated">Dosya Adı:</target> <note /> </trans-unit> <trans-unit id="Generate_Type"> <source>Generate Type</source> <target state="translated">Tür Oluştur</target> <note /> </trans-unit> <trans-unit id="Kind_colon"> <source>_Kind:</source> <target state="translated">_Tür:</target> <note /> </trans-unit> <trans-unit id="Location_colon"> <source>Location:</source> <target state="translated">Konum:</target> <note /> </trans-unit> <trans-unit id="Modifier"> <source>Modifier</source> <target state="translated">Değiştirici</target> <note /> </trans-unit> <trans-unit id="Name_colon1"> <source>Name:</source> <target state="translated">Ad:</target> <note /> </trans-unit> <trans-unit id="Parameter"> <source>Parameter</source> <target state="translated">Parametre</target> <note /> </trans-unit> <trans-unit id="Parameters_colon2"> <source>Parameters:</source> <target state="translated">Parametreler:</target> <note /> </trans-unit> <trans-unit id="Preview_method_signature_colon"> <source>Preview method signature:</source> <target state="translated">Metot imzasını önizle:</target> <note /> </trans-unit> <trans-unit id="Preview_reference_changes"> <source>Preview reference changes</source> <target state="translated">Başvuru değişikliklerini önizle</target> <note /> </trans-unit> <trans-unit id="Project_colon"> <source>_Project:</source> <target state="translated">_Proje:</target> <note /> </trans-unit> <trans-unit id="Type"> <source>Type</source> <target state="translated">Tür</target> <note /> </trans-unit> <trans-unit id="Type_Details_colon"> <source>Type Details:</source> <target state="translated">Tür Ayrıntıları:</target> <note /> </trans-unit> <trans-unit id="Re_move"> <source>Re_move</source> <target state="translated">_Kaldır</target> <note /> </trans-unit> <trans-unit id="Restore"> <source>_Restore</source> <target state="translated">_Geri yükle</target> <note /> </trans-unit> <trans-unit id="More_about_0"> <source>More about {0}</source> <target state="translated">{0} hakkında daha fazla bilgi</target> <note /> </trans-unit> <trans-unit id="Navigation_must_be_performed_on_the_foreground_thread"> <source>Navigation must be performed on the foreground thread.</source> <target state="translated">Gezintinin, ön plan iş parçacığında gerçekleştirilmesi gerekir.</target> <note /> </trans-unit> <trans-unit id="bracket_plus_bracket"> <source>[+] </source> <target state="translated">[+] </target> <note /> </trans-unit> <trans-unit id="bracket_bracket"> <source>[-] </source> <target state="translated">[-] </target> <note /> </trans-unit> <trans-unit id="Reference_to_0_in_project_1"> <source>Reference to '{0}' in project '{1}'</source> <target state="translated">'{1}' adlı projedeki '{0}' öğesine yönelik başvuru</target> <note /> </trans-unit> <trans-unit id="Unknown1"> <source>&lt;Unknown&gt;</source> <target state="translated">&lt;Bilinmiyor&gt;</target> <note /> </trans-unit> <trans-unit id="Analyzer_reference_to_0_in_project_1"> <source>Analyzer reference to '{0}' in project '{1}'</source> <target state="translated">'{1}' projesindeki '{0}' öğesine yönelik çözümleyici başvurusu</target> <note /> </trans-unit> <trans-unit id="Project_reference_to_0_in_project_1"> <source>Project reference to '{0}' in project '{1}'</source> <target state="translated">'{1}' adlı projedeki '{0}' öğesine yönelik proje başvurusu</target> <note /> </trans-unit> <trans-unit id="AnalyzerDependencyConflict"> <source>AnalyzerDependencyConflict</source> <target state="translated">AnalyzerDependencyConflict</target> <note /> </trans-unit> <trans-unit id="Analyzer_assemblies_0_and_1_both_have_identity_2_but_different_contents_Only_one_will_be_loaded_and_analyzers_using_these_assemblies_may_not_run_correctly"> <source>Analyzer assemblies '{0}' and '{1}' both have identity '{2}' but different contents. Only one will be loaded and analyzers using these assemblies may not run correctly.</source> <target state="translated">'{0}' ve '{1}' çözümleyici bütünleştirilmiş kodlarının ikisi de '{2}' kimliğine sahip, ancak içerikleri farklı. Yalnızca biri yüklenecek; bu bütünleştirilmiş kodları kullanan çözümleyiciler düzgün şekilde çalışmayabilir.</target> <note /> </trans-unit> <trans-unit id="_0_references"> <source>{0} references</source> <target state="translated">{0} başvuru</target> <note /> </trans-unit> <trans-unit id="_1_reference"> <source>1 reference</source> <target state="translated">1 başvuru</target> <note /> </trans-unit> <trans-unit id="_0_encountered_an_error_and_has_been_disabled"> <source>'{0}' encountered an error and has been disabled.</source> <target state="translated">'{0}' bir hatayla karşılaştı ve devre dışı bırakıldı.</target> <note /> </trans-unit> <trans-unit id="Enable"> <source>Enable</source> <target state="translated">Etkinleştir</target> <note /> </trans-unit> <trans-unit id="Enable_and_ignore_future_errors"> <source>Enable and ignore future errors</source> <target state="translated">Etkinleştir ve gelecekteki hataları yoksay</target> <note /> </trans-unit> <trans-unit id="No_Changes"> <source>No Changes</source> <target state="translated">Değişiklik Yok</target> <note /> </trans-unit> <trans-unit id="Current_block"> <source>Current block</source> <target state="translated">Geçerli blok</target> <note /> </trans-unit> <trans-unit id="Determining_current_block"> <source>Determining current block.</source> <target state="translated">Geçerli blok belirleniyor.</target> <note /> </trans-unit> <trans-unit id="IntelliSense"> <source>IntelliSense</source> <target state="translated">IntelliSense</target> <note /> </trans-unit> <trans-unit id="CSharp_VB_Build_Table_Data_Source"> <source>C#/VB Build Table Data Source</source> <target state="translated">C#/VB Derleme Tablosu Veri Kaynağı</target> <note /> </trans-unit> <trans-unit id="MissingAnalyzerReference"> <source>MissingAnalyzerReference</source> <target state="translated">MissingAnalyzerReference</target> <note /> </trans-unit> <trans-unit id="Analyzer_assembly_0_depends_on_1_but_it_was_not_found_Analyzers_may_not_run_correctly_unless_the_missing_assembly_is_added_as_an_analyzer_reference_as_well"> <source>Analyzer assembly '{0}' depends on '{1}' but it was not found. Analyzers may not run correctly unless the missing assembly is added as an analyzer reference as well.</source> <target state="translated">Çözümleyici bütünleştirilmiş kodu '{0}', '{1}' öğesine bağımlı ancak bu öğe bulunamadı. Eksik bütünleştirilmiş kod da çözümleyici başvurusu olarak eklenmeden, çözümleyiciler düzgün şekilde çalışmayabilir.</target> <note /> </trans-unit> <trans-unit id="Suppress_diagnostics"> <source>Suppress diagnostics</source> <target state="translated">Tanılamayı gizle</target> <note /> </trans-unit> <trans-unit id="Computing_suppressions_fix"> <source>Computing suppressions fix...</source> <target state="translated">Gizlemeler düzeltmesi hesaplanıyor...</target> <note /> </trans-unit> <trans-unit id="Applying_suppressions_fix"> <source>Applying suppressions fix...</source> <target state="translated">Gizlemeler düzeltmesi uygulanıyor...</target> <note /> </trans-unit> <trans-unit id="Remove_suppressions"> <source>Remove suppressions</source> <target state="translated">Gizlemeleri kaldır</target> <note /> </trans-unit> <trans-unit id="Computing_remove_suppressions_fix"> <source>Computing remove suppressions fix...</source> <target state="translated">Gizlemeleri kaldırma düzeltmesi hesaplanıyor...</target> <note /> </trans-unit> <trans-unit id="Applying_remove_suppressions_fix"> <source>Applying remove suppressions fix...</source> <target state="translated">Gizlemeleri kaldırma düzeltmesi uygulanıyor...</target> <note /> </trans-unit> <trans-unit id="This_workspace_only_supports_opening_documents_on_the_UI_thread"> <source>This workspace only supports opening documents on the UI thread.</source> <target state="translated">Bu çalışma alanı, belgelerin yalnızca kullanıcı arabirimi iş parçacığında açılmasını destekler.</target> <note /> </trans-unit> <trans-unit id="This_workspace_does_not_support_updating_Visual_Basic_parse_options"> <source>This workspace does not support updating Visual Basic parse options.</source> <target state="translated">Bu çalışma alanı Visual Basic ayrıştırma seçeneklerinin güncelleştirilmesini desteklemiyor.</target> <note /> </trans-unit> <trans-unit id="Synchronize_0"> <source>Synchronize {0}</source> <target state="translated">{0} ile eşitle</target> <note /> </trans-unit> <trans-unit id="Synchronizing_with_0"> <source>Synchronizing with {0}...</source> <target state="translated">{0} ile eşitleniyor...</target> <note /> </trans-unit> <trans-unit id="Visual_Studio_has_suspended_some_advanced_features_to_improve_performance"> <source>Visual Studio has suspended some advanced features to improve performance.</source> <target state="translated">Visual Studio, performansı artırmak için bazı gelişmiş özellikleri askıya aldı.</target> <note /> </trans-unit> <trans-unit id="Installing_0"> <source>Installing '{0}'</source> <target state="translated">'{0}' yükleniyor</target> <note /> </trans-unit> <trans-unit id="Installing_0_completed"> <source>Installing '{0}' completed</source> <target state="translated">'{0}' yüklendi</target> <note /> </trans-unit> <trans-unit id="Package_install_failed_colon_0"> <source>Package install failed: {0}</source> <target state="translated">Paket yüklenemedi: {0}</target> <note /> </trans-unit> <trans-unit id="Unknown2"> <source>&lt;Unknown&gt;</source> <target state="translated">&lt;Bilinmiyor&gt;</target> <note /> </trans-unit> <trans-unit id="No"> <source>No</source> <target state="translated">Hayır</target> <note /> </trans-unit> <trans-unit id="Yes"> <source>Yes</source> <target state="translated">Evet</target> <note /> </trans-unit> <trans-unit id="Choose_a_Symbol_Specification_and_a_Naming_Style"> <source>Choose a Symbol Specification and a Naming Style.</source> <target state="translated">Sembol Belirtimi ve Adlandırma Stili seçin.</target> <note /> </trans-unit> <trans-unit id="Enter_a_title_for_this_Naming_Rule"> <source>Enter a title for this Naming Rule.</source> <target state="translated">Bu Adlandırma Kuralı için bir başlık girin.</target> <note /> </trans-unit> <trans-unit id="Enter_a_title_for_this_Naming_Style"> <source>Enter a title for this Naming Style.</source> <target state="translated">Bu Adlandırma Stili için bir başlık girin.</target> <note /> </trans-unit> <trans-unit id="Enter_a_title_for_this_Symbol_Specification"> <source>Enter a title for this Symbol Specification.</source> <target state="translated">Bu Sembol Belirtimi için bir başlık girin.</target> <note /> </trans-unit> <trans-unit id="Accessibilities_can_match_any"> <source>Accessibilities (can match any)</source> <target state="translated">Erişim düzeyleri (herhangi biriyle eşleşebilir)</target> <note /> </trans-unit> <trans-unit id="Capitalization_colon"> <source>Capitalization:</source> <target state="translated">Büyük Harfe Çevirme:</target> <note /> </trans-unit> <trans-unit id="all_lower"> <source>all lower</source> <target state="translated">tümü küçük harf</target> <note /> </trans-unit> <trans-unit id="ALL_UPPER"> <source>ALL UPPER</source> <target state="translated">TÜMÜ BÜYÜK HARF</target> <note /> </trans-unit> <trans-unit id="camel_Case_Name"> <source>camel Case Name</source> <target state="translated">orta Harfleri Büyük Ad</target> <note /> </trans-unit> <trans-unit id="First_word_upper"> <source>First word upper</source> <target state="translated">İlk sözcük büyük harfle</target> <note /> </trans-unit> <trans-unit id="Pascal_Case_Name"> <source>Pascal Case Name</source> <target state="translated">Baş Harfleri Büyük Ad</target> <note /> </trans-unit> <trans-unit id="Severity_colon"> <source>Severity:</source> <target state="translated">Önem Derecesi:</target> <note /> </trans-unit> <trans-unit id="Modifiers_must_match_all"> <source>Modifiers (must match all)</source> <target state="translated">Değiştiriciler (tümüyle eşleşmelidir)</target> <note /> </trans-unit> <trans-unit id="Name_colon2"> <source>Name:</source> <target state="translated">Ad:</target> <note /> </trans-unit> <trans-unit id="Naming_Rule"> <source>Naming Rule</source> <target state="translated">Adlandırma Kuralı</target> <note /> </trans-unit> <trans-unit id="Naming_Style"> <source>Naming Style</source> <target state="translated">Adlandırma Stili</target> <note /> </trans-unit> <trans-unit id="Naming_Style_colon"> <source>Naming Style:</source> <target state="translated">Adlandırma Stili:</target> <note /> </trans-unit> <trans-unit id="Naming_Rules_allow_you_to_define_how_particular_sets_of_symbols_should_be_named_and_how_incorrectly_named_symbols_should_be_handled"> <source>Naming Rules allow you to define how particular sets of symbols should be named and how incorrectly-named symbols should be handled.</source> <target state="translated">Adlandırma Kuralları, belirli sembol kümelerinin nasıl adlandırılması gerektiğini ve yanlış adlandırılan sembollerin nasıl işlenmesi gerektiğini tanımlamanızı sağlar.</target> <note /> </trans-unit> <trans-unit id="The_first_matching_top_level_Naming_Rule_is_used_by_default_when_naming_a_symbol_while_any_special_cases_are_handled_by_a_matching_child_rule"> <source>The first matching top-level Naming Rule is used by default when naming a symbol, while any special cases are handled by a matching child rule.</source> <target state="translated">Sembol adlandırılırken varsayılan olarak, eşleşen ilk üst düzey Adlandırma Kuralı kullanılır. Özel durumlar ise eşleşen bir alt kural tarafından işlenir.</target> <note /> </trans-unit> <trans-unit id="Naming_Style_Title_colon"> <source>Naming Style Title:</source> <target state="translated">Adlandırma Stili Başlığı:</target> <note /> </trans-unit> <trans-unit id="Parent_Rule_colon"> <source>Parent Rule:</source> <target state="translated">Üst Kural:</target> <note /> </trans-unit> <trans-unit id="Required_Prefix_colon"> <source>Required Prefix:</source> <target state="translated">Gerekli Ön Ek:</target> <note /> </trans-unit> <trans-unit id="Required_Suffix_colon"> <source>Required Suffix:</source> <target state="translated">Gerekli Sonek:</target> <note /> </trans-unit> <trans-unit id="Sample_Identifier_colon"> <source>Sample Identifier:</source> <target state="translated">Örnek Tanımlayıcı:</target> <note /> </trans-unit> <trans-unit id="Symbol_Kinds_can_match_any"> <source>Symbol Kinds (can match any)</source> <target state="translated">Sembol Türleri (tümüyle eşleşebilir)</target> <note /> </trans-unit> <trans-unit id="Symbol_Specification"> <source>Symbol Specification</source> <target state="translated">Sembol Belirtimi</target> <note /> </trans-unit> <trans-unit id="Symbol_Specification_colon"> <source>Symbol Specification:</source> <target state="translated">Sembol Belirtimi:</target> <note /> </trans-unit> <trans-unit id="Symbol_Specification_Title_colon"> <source>Symbol Specification Title:</source> <target state="translated">Sembol Belirtimi Başlığı:</target> <note /> </trans-unit> <trans-unit id="Word_Separator_colon"> <source>Word Separator:</source> <target state="translated">Sözcük Ayırıcı:</target> <note /> </trans-unit> <trans-unit id="example"> <source>example</source> <target state="translated">örnek</target> <note>IdentifierWord_Example and IdentifierWord_Identifier are combined (with prefixes, suffixes, and word separators) into an example identifier name in the NamingStyle UI.</note> </trans-unit> <trans-unit id="identifier"> <source>identifier</source> <target state="translated">tanımlayıcı</target> <note>IdentifierWord_Example and IdentifierWord_Identifier are combined (with prefixes, suffixes, and word separators) into an example identifier name in the NamingStyle UI.</note> </trans-unit> <trans-unit id="Install_0"> <source>Install '{0}'</source> <target state="translated">'{0}' öğesini yükle</target> <note /> </trans-unit> <trans-unit id="Uninstalling_0"> <source>Uninstalling '{0}'</source> <target state="translated">'{0}' kaldırılıyor</target> <note /> </trans-unit> <trans-unit id="Uninstalling_0_completed"> <source>Uninstalling '{0}' completed</source> <target state="translated">'{0}' kaldırıldı</target> <note /> </trans-unit> <trans-unit id="Uninstall_0"> <source>Uninstall '{0}'</source> <target state="translated">'{0}' öğesini kaldır</target> <note /> </trans-unit> <trans-unit id="Package_uninstall_failed_colon_0"> <source>Package uninstall failed: {0}</source> <target state="translated">Paket kaldırılamadı: {0}</target> <note /> </trans-unit> <trans-unit id="Error_encountered_while_loading_the_project_Some_project_features_such_as_full_solution_analysis_for_the_failed_project_and_projects_that_depend_on_it_have_been_disabled"> <source>Error encountered while loading the project. Some project features, such as full solution analysis for the failed project and projects that depend on it, have been disabled.</source> <target state="translated">Proje yüklenirken hatayla karşılaşıldı. Başarısız olan proje ve buna bağımlı projeler için, tam çözüm denetimi gibi bazı proje özellikleri devre dışı bırakıldı.</target> <note /> </trans-unit> <trans-unit id="Project_loading_failed"> <source>Project loading failed.</source> <target state="translated">Proje yüklenemedi.</target> <note /> </trans-unit> <trans-unit id="To_see_what_caused_the_issue_please_try_below_1_Close_Visual_Studio_long_paragraph_follows"> <source>To see what caused the issue, please try below. 1. Close Visual Studio 2. Open a Visual Studio Developer Command Prompt 3. Set environment variable “TraceDesignTime” to true (set TraceDesignTime=true) 4. Delete .vs directory/.suo file 5. Restart VS from the command prompt you set the environment variable (devenv) 6. Open the solution 7. Check '{0}' and look for the failed tasks (FAILED)</source> <target state="translated">Sorunun neden kaynaklandığını görmek için lütfen aşağıdaki çözümleri deneyin. 1. Visual Studio'yu kapatın 2. Visual Studio Geliştirici Komut İstemi'ni açın 3. “TraceDesignTime” ortam değişkenini true olarak ayarlayın (set TraceDesignTime=true) 4. .vs dizini/.suo dosyasını silin 5. Visual Studio'yu, ortam değişkenini ayarladığınız komut isteminden yeniden başlatın (devenv) 6. Çözümü açın 7. '{0}' konumuna giderek başarısız olan görevlere bakın (FAILED)</target> <note /> </trans-unit> <trans-unit id="Additional_information_colon"> <source>Additional information:</source> <target state="translated">Ek bilgi:</target> <note /> </trans-unit> <trans-unit id="Installing_0_failed_Additional_information_colon_1"> <source>Installing '{0}' failed. Additional information: {1}</source> <target state="translated">'{0}' yüklenemedi. Ek bilgiler: {1}</target> <note /> </trans-unit> <trans-unit id="Uninstalling_0_failed_Additional_information_colon_1"> <source>Uninstalling '{0}' failed. Additional information: {1}</source> <target state="translated">'{0}' kaldırılamadı. Ek bilgiler: {1}</target> <note /> </trans-unit> <trans-unit id="Move_0_below_1"> <source>Move {0} below {1}</source> <target state="translated">{0} öğesini {1} öğesinin altına taşı</target> <note>{0} and {1} are parameter descriptions</note> </trans-unit> <trans-unit id="Move_0_above_1"> <source>Move {0} above {1}</source> <target state="translated">{0} öğesini {1} öğesinin üstüne taşı</target> <note>{0} and {1} are parameter descriptions</note> </trans-unit> <trans-unit id="Remove_0"> <source>Remove {0}</source> <target state="translated">{0} öğesini kaldır</target> <note>{0} is a parameter description</note> </trans-unit> <trans-unit id="Restore_0"> <source>Restore {0}</source> <target state="translated">{0} öğesini geri yükle</target> <note>{0} is a parameter description</note> </trans-unit> <trans-unit id="Re_enable"> <source>Re-enable</source> <target state="translated">Yeniden etkinleştir</target> <note /> </trans-unit> <trans-unit id="Learn_more"> <source>Learn more</source> <target state="translated">Daha fazla bilgi</target> <note /> </trans-unit> <trans-unit id="Prefer_framework_type"> <source>Prefer framework type</source> <target state="translated">Çerçeve türünü tercih et</target> <note /> </trans-unit> <trans-unit id="Prefer_predefined_type"> <source>Prefer predefined type</source> <target state="translated">Önceden tanımlanmış türü tercih et</target> <note /> </trans-unit> <trans-unit id="Copy_to_Clipboard"> <source>Copy to Clipboard</source> <target state="translated">Panoya Kopyala</target> <note /> </trans-unit> <trans-unit id="Close"> <source>Close</source> <target state="translated">Kapat</target> <note /> </trans-unit> <trans-unit id="Unknown_parameters"> <source>&lt;Unknown Parameters&gt;</source> <target state="translated">&lt;Bilinmeyen Parametreler&gt;</target> <note /> </trans-unit> <trans-unit id="End_of_inner_exception_stack"> <source>--- End of inner exception stack trace ---</source> <target state="translated">--- İç özel durum yığın izlemesi sonu ---</target> <note /> </trans-unit> <trans-unit id="For_locals_parameters_and_members"> <source>For locals, parameters and members</source> <target state="translated">Yerel öğeler, parametreler ve üyeler için</target> <note /> </trans-unit> <trans-unit id="For_member_access_expressions"> <source>For member access expressions</source> <target state="translated">Üye erişimi ifadeleri için</target> <note /> </trans-unit> <trans-unit id="Prefer_object_initializer"> <source>Prefer object initializer</source> <target state="translated">Nesne başlatıcısını tercih et</target> <note /> </trans-unit> <trans-unit id="Expression_preferences_colon"> <source>Expression preferences:</source> <target state="translated">İfade tercihleri:</target> <note /> </trans-unit> <trans-unit id="Block_Structure_Guides"> <source>Block Structure Guides</source> <target state="translated">Blok Yapısı Kılavuzları</target> <note /> </trans-unit> <trans-unit id="Outlining"> <source>Outlining</source> <target state="translated">Ana Hat</target> <note /> </trans-unit> <trans-unit id="Show_guides_for_code_level_constructs"> <source>Show guides for code level constructs</source> <target state="translated">Kod düzeyinde yapılar için kılavuzları göster</target> <note /> </trans-unit> <trans-unit id="Show_guides_for_comments_and_preprocessor_regions"> <source>Show guides for comments and preprocessor regions</source> <target state="translated">Açıklamalar ve ön işlemci bölgeleri için kılavuzları göster</target> <note /> </trans-unit> <trans-unit id="Show_guides_for_declaration_level_constructs"> <source>Show guides for declaration level constructs</source> <target state="translated">Bildirim düzeyinde yapılar için kılavuzları göster</target> <note /> </trans-unit> <trans-unit id="Show_outlining_for_code_level_constructs"> <source>Show outlining for code level constructs</source> <target state="translated">Kod düzeyinde yapılar için ana hattı göster</target> <note /> </trans-unit> <trans-unit id="Show_outlining_for_comments_and_preprocessor_regions"> <source>Show outlining for comments and preprocessor regions</source> <target state="translated">Açıklamalar ve ön işlemci bölgeleri için ana hattı göster</target> <note /> </trans-unit> <trans-unit id="Show_outlining_for_declaration_level_constructs"> <source>Show outlining for declaration level constructs</source> <target state="translated">Bildirim düzeyinde yapılar için ana hattı göster</target> <note /> </trans-unit> <trans-unit id="Variable_preferences_colon"> <source>Variable preferences:</source> <target state="translated">Değişken tercihleri:</target> <note /> </trans-unit> <trans-unit id="Prefer_inlined_variable_declaration"> <source>Prefer inlined variable declaration</source> <target state="translated">Satır içine alınmış değişken bildirimini tercih et</target> <note /> </trans-unit> <trans-unit id="Use_expression_body_for_methods"> <source>Use expression body for methods</source> <target state="translated">Metotlar için ifade gövdesi kullan</target> <note /> </trans-unit> <trans-unit id="Code_block_preferences_colon"> <source>Code block preferences:</source> <target state="translated">Kod bloğu tercihleri:</target> <note /> </trans-unit> <trans-unit id="Use_expression_body_for_accessors"> <source>Use expression body for accessors</source> <target state="translated">Erişimciler için ifade gövdesi kullan</target> <note /> </trans-unit> <trans-unit id="Use_expression_body_for_constructors"> <source>Use expression body for constructors</source> <target state="translated">Oluşturucular için ifade gövdesi kullan</target> <note /> </trans-unit> <trans-unit id="Use_expression_body_for_indexers"> <source>Use expression body for indexers</source> <target state="translated">Dizin oluşturucular için ifade gövdesi kullan</target> <note /> </trans-unit> <trans-unit id="Use_expression_body_for_operators"> <source>Use expression body for operators</source> <target state="translated">İşleçler için ifade gövdesi kullan</target> <note /> </trans-unit> <trans-unit id="Use_expression_body_for_properties"> <source>Use expression body for properties</source> <target state="translated">Özellikler için ifade gövdesi kullan</target> <note /> </trans-unit> <trans-unit id="Some_naming_rules_are_incomplete_Please_complete_or_remove_them"> <source>Some naming rules are incomplete. Please complete or remove them.</source> <target state="translated">Bazı adlandırma kuralları eksik. Lütfen bunları tamamlayın veya kaldırın.</target> <note /> </trans-unit> <trans-unit id="Manage_specifications"> <source>Manage specifications</source> <target state="translated">Belirtimleri yönet</target> <note /> </trans-unit> <trans-unit id="Reorder"> <source>Reorder</source> <target state="translated">Yeniden sırala</target> <note /> </trans-unit> <trans-unit id="Severity"> <source>Severity</source> <target state="translated">Önem Derecesi</target> <note /> </trans-unit> <trans-unit id="Specification"> <source>Specification</source> <target state="translated">Belirtim</target> <note /> </trans-unit> <trans-unit id="Required_Style"> <source>Required Style</source> <target state="translated">Gerekli Stil</target> <note /> </trans-unit> <trans-unit id="This_item_cannot_be_deleted_because_it_is_used_by_an_existing_Naming_Rule"> <source>This item cannot be deleted because it is used by an existing Naming Rule.</source> <target state="translated">Öğe, mevcut bir Adlandırma Kuralı tarafından kullanıldığından silinemiyor.</target> <note /> </trans-unit> <trans-unit id="Prefer_collection_initializer"> <source>Prefer collection initializer</source> <target state="translated">Koleksiyon başlatıcısını tercih et</target> <note /> </trans-unit> <trans-unit id="Prefer_coalesce_expression"> <source>Prefer coalesce expression</source> <target state="translated">Birleştirme ifadesini tercih et</target> <note /> </trans-unit> <trans-unit id="Collapse_regions_when_collapsing_to_definitions"> <source>Collapse #regions when collapsing to definitions</source> <target state="translated">Tanımlara daraltırken #region öğelerini daralt</target> <note /> </trans-unit> <trans-unit id="Prefer_null_propagation"> <source>Prefer null propagation</source> <target state="translated">Null yaymayı tercih et</target> <note /> </trans-unit> <trans-unit id="Prefer_explicit_tuple_name"> <source>Prefer explicit tuple name</source> <target state="translated">Açık demet adını tercih et</target> <note /> </trans-unit> <trans-unit id="Description"> <source>Description</source> <target state="translated">Açıklama</target> <note /> </trans-unit> <trans-unit id="Preference"> <source>Preference</source> <target state="translated">Tercih</target> <note /> </trans-unit> <trans-unit id="Implement_Interface_or_Abstract_Class"> <source>Implement Interface or Abstract Class</source> <target state="translated">Interface veya Abstract Sınıfı Uygula</target> <note /> </trans-unit> <trans-unit id="For_a_given_symbol_only_the_topmost_rule_with_a_matching_Specification_will_be_applied_Violation_of_that_rules_Required_Style_will_be_reported_at_the_chosen_Severity_level"> <source>For a given symbol, only the topmost rule with a matching 'Specification' will be applied. Violation of that rule's 'Required Style' will be reported at the chosen 'Severity' level.</source> <target state="translated">Sağlanan bir sembolde yalnızca, eşleşen bir 'Belirtim' içeren kurallardan en üstte bulunanı uygulanır. Bu kural için 'Gerekli Stil' ihlal edilirse, bu durum seçilen 'Önem Derecesi' düzeyinde bildirilir.</target> <note /> </trans-unit> <trans-unit id="at_the_end"> <source>at the end</source> <target state="translated">sonda</target> <note /> </trans-unit> <trans-unit id="When_inserting_properties_events_and_methods_place_them"> <source>When inserting properties, events and methods, place them:</source> <target state="translated">Özellik, olay ve metot eklerken, bunları şuraya yerleştir:</target> <note /> </trans-unit> <trans-unit id="with_other_members_of_the_same_kind"> <source>with other members of the same kind</source> <target state="translated">aynı türden başka üyelerle birlikte</target> <note /> </trans-unit> <trans-unit id="Prefer_braces"> <source>Prefer braces</source> <target state="translated">Küme ayraçlarını tercih et</target> <note /> </trans-unit> <trans-unit id="Over_colon"> <source>Over:</source> <target state="translated">Bunun yerine:</target> <note /> </trans-unit> <trans-unit id="Prefer_colon"> <source>Prefer:</source> <target state="translated">Tercih edilen:</target> <note /> </trans-unit> <trans-unit id="or"> <source>or</source> <target state="translated">veya</target> <note /> </trans-unit> <trans-unit id="built_in_types"> <source>built-in types</source> <target state="translated">yerleşik türler</target> <note /> </trans-unit> <trans-unit id="everywhere_else"> <source>everywhere else</source> <target state="translated">diğer yerlerde</target> <note /> </trans-unit> <trans-unit id="type_is_apparent_from_assignment_expression"> <source>type is apparent from assignment expression</source> <target state="translated">tür, atama ifadesinden görünür</target> <note /> </trans-unit> <trans-unit id="Move_down"> <source>Move down</source> <target state="translated">Aşağı taşı</target> <note /> </trans-unit> <trans-unit id="Move_up"> <source>Move up</source> <target state="translated">Yukarı taşı</target> <note /> </trans-unit> <trans-unit id="Remove"> <source>Remove</source> <target state="translated">Kaldır</target> <note /> </trans-unit> <trans-unit id="Pick_members"> <source>Pick members</source> <target state="translated">Üyeleri seçin</target> <note /> </trans-unit> <trans-unit id="Unfortunately_a_process_used_by_Visual_Studio_has_encountered_an_unrecoverable_error_We_recommend_saving_your_work_and_then_closing_and_restarting_Visual_Studio"> <source>Unfortunately, a process used by Visual Studio has encountered an unrecoverable error. We recommend saving your work, and then closing and restarting Visual Studio.</source> <target state="translated">Visual Studio tarafından kullanılan bir işlemde, kurtarılamayan bir hatayla karşılaşıldı. Çalışmanızı kaydettikten sonra Visual Studio'yu kapatıp yeniden başlatmanız önerilir.</target> <note /> </trans-unit> <trans-unit id="Add_a_symbol_specification"> <source>Add a symbol specification</source> <target state="translated">Sembol belirtimi ekle</target> <note /> </trans-unit> <trans-unit id="Remove_symbol_specification"> <source>Remove symbol specification</source> <target state="translated">Sembol belirtimini kaldır</target> <note /> </trans-unit> <trans-unit id="Add_item"> <source>Add item</source> <target state="translated">Öğe ekle</target> <note /> </trans-unit> <trans-unit id="Edit_item"> <source>Edit item</source> <target state="translated">Öğeyi düzenle</target> <note /> </trans-unit> <trans-unit id="Remove_item"> <source>Remove item</source> <target state="translated">Öğeyi kaldır</target> <note /> </trans-unit> <trans-unit id="Add_a_naming_rule"> <source>Add a naming rule</source> <target state="translated">Adlandırma kuralı ekle</target> <note /> </trans-unit> <trans-unit id="Remove_naming_rule"> <source>Remove naming rule</source> <target state="translated">Adlandırma kuralını kaldır</target> <note /> </trans-unit> <trans-unit id="VisualStudioWorkspace_TryApplyChanges_cannot_be_called_from_a_background_thread"> <source>VisualStudioWorkspace.TryApplyChanges cannot be called from a background thread.</source> <target state="translated">VisualStudioWorkspace.TryApplyChanges bir arka plan iş parçacığından çağırılamaz.</target> <note /> </trans-unit> <trans-unit id="prefer_throwing_properties"> <source>prefer throwing properties</source> <target state="translated">özel durum oluşturan özellikleri tercih et</target> <note /> </trans-unit> <trans-unit id="When_generating_properties"> <source>When generating properties:</source> <target state="translated">Özellikler oluşturulurken:</target> <note /> </trans-unit> <trans-unit id="Options"> <source>Options</source> <target state="translated">Seçenekler</target> <note /> </trans-unit> <trans-unit id="Never_show_this_again"> <source>Never show this again</source> <target state="translated">Bunu bir daha gösterme</target> <note /> </trans-unit> <trans-unit id="Prefer_simple_default_expression"> <source>Prefer simple 'default' expression</source> <target state="translated">Basit 'default' ifadesini tercih et</target> <note /> </trans-unit> <trans-unit id="Prefer_inferred_tuple_names"> <source>Prefer inferred tuple element names</source> <target state="translated">Gösterilen demet öğesi adlarını tercih et</target> <note /> </trans-unit> <trans-unit id="Prefer_inferred_anonymous_type_member_names"> <source>Prefer inferred anonymous type member names</source> <target state="translated">Gösterilen anonim tip üye adlarını tercih et</target> <note /> </trans-unit> <trans-unit id="Preview_pane"> <source>Preview pane</source> <target state="translated">Önizleme bölmesi</target> <note /> </trans-unit> <trans-unit id="Analysis"> <source>Analysis</source> <target state="translated">Analiz</target> <note /> </trans-unit> <trans-unit id="Fade_out_unreachable_code"> <source>Fade out unreachable code</source> <target state="translated">Erişilemeyen kodu soluklaştır</target> <note /> </trans-unit> <trans-unit id="Fading"> <source>Fading</source> <target state="translated">Soluklaştırılıyor</target> <note /> </trans-unit> <trans-unit id="Prefer_local_function_over_anonymous_function"> <source>Prefer local function over anonymous function</source> <target state="translated">Anonim işlevler yerine yerel işlevleri tercih et</target> <note /> </trans-unit> <trans-unit id="Prefer_deconstructed_variable_declaration"> <source>Prefer deconstructed variable declaration</source> <target state="translated">Ayrıştırılmış değişken bildirimini tercih et</target> <note /> </trans-unit> <trans-unit id="External_reference_found"> <source>External reference found</source> <target state="translated">Dış başvuru bulundu</target> <note /> </trans-unit> <trans-unit id="No_references_found_to_0"> <source>No references found to '{0}'</source> <target state="translated">'{0}' için başvuru bulunamadı</target> <note /> </trans-unit> <trans-unit id="Search_found_no_results"> <source>Search found no results</source> <target state="translated">Aramada sonuç bulunamadı</target> <note /> </trans-unit> <trans-unit id="analyzer_Prefer_auto_properties"> <source>Prefer auto properties</source> <target state="translated">Otomatik özellikleri tercih et</target> <note /> </trans-unit> <trans-unit id="codegen_prefer_auto_properties"> <source>prefer auto properties</source> <target state="translated">otomatik özellikleri tercih et</target> <note /> </trans-unit> <trans-unit id="ModuleHasBeenUnloaded"> <source>Module has been unloaded.</source> <target state="translated">Modül kaldırıldı.</target> <note /> </trans-unit> <trans-unit id="Enable_navigation_to_decompiled_sources"> <source>Enable navigation to decompiled sources</source> <target state="needs-review-translation">Derlemesi ayrılan kaynaklar için gezintiyi etkinleştirme (deneysel)</target> <note /> </trans-unit> <trans-unit id="Code_style_header_use_editor_config"> <source>Your .editorconfig file might override the local settings configured on this page which only apply to your machine. To configure these settings to travel with your solution use EditorConfig files. More info</source> <target state="translated">.editorconfig dosyanız, bu sayfada yapılandırılan ve yalnızca makinenizde uygulanan yerel ayarları geçersiz kılabilir. Bu ayarları çözümünüzle birlikte hareket etmek üzere yapılandırmak için EditorConfig dosyalarını kullanın. Daha fazla bilgi</target> <note /> </trans-unit> <trans-unit id="Sync_Class_View"> <source>Sync Class View</source> <target state="translated">Sınıf Görünümünü Eşitle</target> <note /> </trans-unit> <trans-unit id="Analyzing_0"> <source>Analyzing '{0}'</source> <target state="translated">'{0}' Analiz Ediliyor</target> <note /> </trans-unit> <trans-unit id="Manage_naming_styles"> <source>Manage naming styles</source> <target state="translated">Adlandırma stillerini yönetme</target> <note /> </trans-unit> <trans-unit id="Prefer_conditional_expression_over_if_with_assignments"> <source>Prefer conditional expression over 'if' with assignments</source> <target state="translated">Atamalarda 'if' yerine koşullu deyim tercih et</target> <note /> </trans-unit> <trans-unit id="Prefer_conditional_expression_over_if_with_returns"> <source>Prefer conditional expression over 'if' with returns</source> <target state="translated">Dönüşlerde 'if' yerine koşullu deyim tercih et</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="tr" original="../ServicesVSResources.resx"> <body> <trans-unit id="A_new_editorconfig_file_was_detected_at_the_root_of_your_solution_Would_you_like_to_make_it_a_solution_item"> <source>A new .editorconfig file was detected at the root of your solution. Would you like to make it a solution item?</source> <target state="translated">Çözümünüzün kökünde yeni bir .editorconfig dosyası algılandı. Bunu bir çözüm öğesi yapmak istiyor musunuz?</target> <note /> </trans-unit> <trans-unit id="A_new_namespace_will_be_created"> <source>A new namespace will be created</source> <target state="translated">Yeni bir ad alanı oluşturulacak</target> <note /> </trans-unit> <trans-unit id="A_type_and_name_must_be_provided"> <source>A type and name must be provided.</source> <target state="translated">Bir tür ve ad verilmesi gerekiyor.</target> <note /> </trans-unit> <trans-unit id="Action"> <source>Action</source> <target state="translated">Eylem</target> <note>Action to perform on an unused reference, such as remove or keep</note> </trans-unit> <trans-unit id="Add"> <source>_Add</source> <target state="translated">_Ekle</target> <note>Adding an element to a list</note> </trans-unit> <trans-unit id="Add_Parameter"> <source>Add Parameter</source> <target state="translated">Parametre Ekle</target> <note /> </trans-unit> <trans-unit id="Add_to_current_file"> <source>Add to _current file</source> <target state="translated">Geçerli _dosyaya ekle</target> <note /> </trans-unit> <trans-unit id="Added_Parameter"> <source>Added parameter.</source> <target state="translated">Parametre eklendi.</target> <note /> </trans-unit> <trans-unit id="Additional_changes_are_needed_to_complete_the_refactoring_Review_changes_below"> <source>Additional changes are needed to complete the refactoring. Review changes below.</source> <target state="translated">Yeniden düzenlemeyi tamamlamak için ek değişiklikler gerekli. Aşağıdaki değişiklikleri gözden geçirin.</target> <note /> </trans-unit> <trans-unit id="All_methods"> <source>All methods</source> <target state="translated">Tüm yöntemler</target> <note /> </trans-unit> <trans-unit id="All_sources"> <source>All sources</source> <target state="translated">Tüm kaynaklar</target> <note /> </trans-unit> <trans-unit id="Allow_colon"> <source>Allow:</source> <target state="translated">İzin ver:</target> <note /> </trans-unit> <trans-unit id="Allow_multiple_blank_lines"> <source>Allow multiple blank lines</source> <target state="translated">Birden çok boş satıra izin ver</target> <note /> </trans-unit> <trans-unit id="Allow_statement_immediately_after_block"> <source>Allow statement immediately after block</source> <target state="translated">Bloktan hemen sonra deyime izin ver</target> <note /> </trans-unit> <trans-unit id="Always_for_clarity"> <source>Always for clarity</source> <target state="translated">Açıklık sağlamak için her zaman</target> <note /> </trans-unit> <trans-unit id="Analyzer_Defaults"> <source>Analyzer Defaults</source> <target state="new">Analyzer Defaults</target> <note /> </trans-unit> <trans-unit id="Analyzers"> <source>Analyzers</source> <target state="translated">Çözümleyiciler</target> <note /> </trans-unit> <trans-unit id="Analyzing_project_references"> <source>Analyzing project references...</source> <target state="translated">Proje başvuruları analiz ediliyor...</target> <note /> </trans-unit> <trans-unit id="Apply"> <source>Apply</source> <target state="translated">Uygula</target> <note /> </trans-unit> <trans-unit id="Apply_0_keymapping_scheme"> <source>Apply '{0}' keymapping scheme</source> <target state="translated">'{0}' tuş eşlemesi düzenini uygula</target> <note /> </trans-unit> <trans-unit id="Assemblies"> <source>Assemblies</source> <target state="translated">Derlemeler</target> <note /> </trans-unit> <trans-unit id="Avoid_expression_statements_that_implicitly_ignore_value"> <source>Avoid expression statements that implicitly ignore value</source> <target state="translated">Değeri örtük olarak yok sayan ifade deyimlerini engelle</target> <note /> </trans-unit> <trans-unit id="Avoid_unused_parameters"> <source>Avoid unused parameters</source> <target state="translated">Kullanılmayan parametreleri engelle</target> <note /> </trans-unit> <trans-unit id="Avoid_unused_value_assignments"> <source>Avoid unused value assignments</source> <target state="translated">Kullanılmayan değer atamalarını engelle</target> <note /> </trans-unit> <trans-unit id="Back"> <source>Back</source> <target state="translated">Geri</target> <note /> </trans-unit> <trans-unit id="Background_analysis_scope_colon"> <source>Background analysis scope:</source> <target state="translated">Arka plan çözümleme kapsamı:</target> <note /> </trans-unit> <trans-unit id="Bitness32"> <source>32-bit</source> <target state="translated">32 bit</target> <note /> </trans-unit> <trans-unit id="Bitness64"> <source>64-bit</source> <target state="translated">64 bit</target> <note /> </trans-unit> <trans-unit id="Build_plus_live_analysis_NuGet_package"> <source>Build + live analysis (NuGet package)</source> <target state="translated">Derleme ve canlı analiz (NuGet paketi)</target> <note /> </trans-unit> <trans-unit id="CSharp_Visual_Basic_Diagnostics_Language_Client"> <source>C#/Visual Basic Diagnostics Language Client</source> <target state="translated">C#/Visual Basic Tanılama Dili İstemcisi</target> <note /> </trans-unit> <trans-unit id="Calculating"> <source>Calculating...</source> <target state="new">Calculating...</target> <note>Used in UI to represent progress in the context of loading items. </note> </trans-unit> <trans-unit id="Calculating_dependents"> <source>Calculating dependents...</source> <target state="translated">Bağımlılar hesaplanıyor...</target> <note /> </trans-unit> <trans-unit id="Call_site_value"> <source>Call site value:</source> <target state="translated">Çağrı konumu değeri:</target> <note /> </trans-unit> <trans-unit id="Callsite"> <source>Call site</source> <target state="translated">Çağrı konumu</target> <note /> </trans-unit> <trans-unit id="Carriage_Return_Newline_rn"> <source>Carriage Return + Newline (\r\n)</source> <target state="translated">Satır Başı + Yeni Satır (\r\n)</target> <note /> </trans-unit> <trans-unit id="Carriage_Return_r"> <source>Carriage Return (\r)</source> <target state="translated">Satır başı (\r)</target> <note /> </trans-unit> <trans-unit id="Category"> <source>Category</source> <target state="translated">Kategori</target> <note /> </trans-unit> <trans-unit id="Choose_which_action_you_would_like_to_perform_on_the_unused_references"> <source>Choose which action you would like to perform on the unused references.</source> <target state="translated">Kullanılmayan başvurularda hangi eylemi gerçekleştirmek istediğinizi seçin.</target> <note /> </trans-unit> <trans-unit id="Code_Style"> <source>Code Style</source> <target state="translated">Kod Stili</target> <note /> </trans-unit> <trans-unit id="Code_analysis_completed_for_0"> <source>Code analysis completed for '{0}'.</source> <target state="translated">'{0}' için kod analizi tamamlandı.</target> <note /> </trans-unit> <trans-unit id="Code_analysis_completed_for_Solution"> <source>Code analysis completed for Solution.</source> <target state="translated">Çözüm için kod analizi tamamlandı.</target> <note /> </trans-unit> <trans-unit id="Code_analysis_terminated_before_completion_for_0"> <source>Code analysis terminated before completion for '{0}'.</source> <target state="translated">Kod analizi, '{0}' için tamamlanmadan önce sonlandırıldı.</target> <note /> </trans-unit> <trans-unit id="Code_analysis_terminated_before_completion_for_Solution"> <source>Code analysis terminated before completion for Solution.</source> <target state="translated">Kod analizi, Çözüm için tamamlanmadan önce sonlandırıldı.</target> <note /> </trans-unit> <trans-unit id="Color_hints"> <source>Color hints</source> <target state="translated">Renk ipuçları</target> <note /> </trans-unit> <trans-unit id="Colorize_regular_expressions"> <source>Colorize regular expressions</source> <target state="translated">Normal ifadeleri renklendir</target> <note /> </trans-unit> <trans-unit id="Comments"> <source>Comments</source> <target state="translated">Açıklamalar</target> <note /> </trans-unit> <trans-unit id="Containing_member"> <source>Containing Member</source> <target state="translated">Kapsayan Üye</target> <note /> </trans-unit> <trans-unit id="Containing_type"> <source>Containing Type</source> <target state="translated">Kapsayan Tür</target> <note /> </trans-unit> <trans-unit id="Current_document"> <source>Current document</source> <target state="translated">Geçerli belge</target> <note /> </trans-unit> <trans-unit id="Current_parameter"> <source>Current parameter</source> <target state="translated">Geçerli parametre</target> <note /> </trans-unit> <trans-unit id="Derived_types"> <source>Derived types</source> <target state="new">Derived types</target> <note /> </trans-unit> <trans-unit id="Disabled"> <source>Disabled</source> <target state="translated">Devre dışı</target> <note /> </trans-unit> <trans-unit id="Display_all_hints_while_pressing_Alt_F1"> <source>Display all hints while pressing Alt+F1</source> <target state="translated">Alt+F1 tuşlarına basılırken tüm ipuçlarını görüntüle</target> <note /> </trans-unit> <trans-unit id="Display_inline_parameter_name_hints"> <source>Disp_lay inline parameter name hints</source> <target state="translated">Satır içi parametre adı ipuç_larını göster</target> <note /> </trans-unit> <trans-unit id="Display_inline_type_hints"> <source>Display inline type hints</source> <target state="translated">Satır içi tür ipuçlarını göster</target> <note /> </trans-unit> <trans-unit id="Edit"> <source>_Edit</source> <target state="translated">_Düzenle</target> <note /> </trans-unit> <trans-unit id="Edit_0"> <source>Edit {0}</source> <target state="translated">{0} öğesini düzenle</target> <note>{0} is a parameter description</note> </trans-unit> <trans-unit id="Editor_Color_Scheme"> <source>Editor Color Scheme</source> <target state="translated">Düzenleyici Renk Düzeni</target> <note /> </trans-unit> <trans-unit id="Editor_color_scheme_options_are_only_available_when_using_a_color_theme_bundled_with_Visual_Studio_The_color_theme_can_be_configured_from_the_Environment_General_options_page"> <source>Editor color scheme options are only available when using a color theme bundled with Visual Studio. The color theme can be configured from the Environment &gt; General options page.</source> <target state="translated">Düzenleyici renk düzeni seçenekleri yalnızca Visual Studio ile paketlenmiş bir renk teması ile birlikte kullanılabilir. Renk teması, Ortam &gt; Genel seçenekler sayfasından yapılandırılabilir.</target> <note /> </trans-unit> <trans-unit id="Element_is_not_valid"> <source>Element is not valid.</source> <target state="translated">Öğe geçerli değil.</target> <note /> </trans-unit> <trans-unit id="Enable_Razor_pull_diagnostics_experimental_requires_restart"> <source>Enable Razor 'pull' diagnostics (experimental, requires restart)</source> <target state="translated">Razor 'pull' tanılamasını etkinleştir (deneysel, yeniden başlatma gerekir)</target> <note /> </trans-unit> <trans-unit id="Enable_all_features_in_opened_files_from_source_generators_experimental"> <source>Enable all features in opened files from source generators (experimental)</source> <target state="translated">Kaynak oluşturuculardan alınan açık sayfalarda tüm özellikleri etkinleştir (deneysel)</target> <note /> </trans-unit> <trans-unit id="Enable_file_logging_for_diagnostics"> <source>Enable file logging for diagnostics (logged in '%Temp%\Roslyn' folder)</source> <target state="translated">Tanılama için dosya günlüğünü etkinleştir (oturum açan '%Temp%\Roslyn' klasörü)</target> <note /> </trans-unit> <trans-unit id="Enable_pull_diagnostics_experimental_requires_restart"> <source>Enable 'pull' diagnostics (experimental, requires restart)</source> <target state="translated">'Pull' tanılamasını etkinleştir (deneysel, yeniden başlatma gerekir)</target> <note /> </trans-unit> <trans-unit id="Enabled"> <source>Enabled</source> <target state="translated">Etkin</target> <note /> </trans-unit> <trans-unit id="Enter_a_call_site_value_or_choose_a_different_value_injection_kind"> <source>Enter a call site value or choose a different value injection kind</source> <target state="translated">Bir çağrı sitesi değeri girin veya farklı bir değer yerleştirme tipi seçin</target> <note /> </trans-unit> <trans-unit id="Entire_repository"> <source>Entire repository</source> <target state="translated">Tüm depo</target> <note /> </trans-unit> <trans-unit id="Entire_solution"> <source>Entire solution</source> <target state="translated">Tüm çözüm</target> <note /> </trans-unit> <trans-unit id="Error"> <source>Error</source> <target state="translated">Hata</target> <note /> </trans-unit> <trans-unit id="Error_updating_suppressions_0"> <source>Error updating suppressions: {0}</source> <target state="translated">Gizlemeler güncellenirken hata oluştu: {0}</target> <note /> </trans-unit> <trans-unit id="Evaluating_0_tasks_in_queue"> <source>Evaluating ({0} tasks in queue)</source> <target state="translated">Değerlendiriliyor (kuyrukta {0} görev var)</target> <note /> </trans-unit> <trans-unit id="Extract_Base_Class"> <source>Extract Base Class</source> <target state="translated">Temel Sınıfı Ayıkla</target> <note /> </trans-unit> <trans-unit id="Finish"> <source>Finish</source> <target state="translated">Son</target> <note /> </trans-unit> <trans-unit id="Format_document"> <source>Format document</source> <target state="translated">Belgeyi biçimlendir</target> <note /> </trans-unit> <trans-unit id="Generate_dot_editorconfig_file_from_settings"> <source>Generate .editorconfig file from settings</source> <target state="translated">Ayarlardan .editorconfig dosyası oluştur</target> <note /> </trans-unit> <trans-unit id="Highlight_related_components_under_cursor"> <source>Highlight related components under cursor</source> <target state="translated">İmlecin altında ilgili bileşenleri vurgula</target> <note /> </trans-unit> <trans-unit id="Id"> <source>Id</source> <target state="translated">Kimlik</target> <note /> </trans-unit> <trans-unit id="Implemented_interfaces"> <source>Implemented interfaces</source> <target state="new">Implemented interfaces</target> <note /> </trans-unit> <trans-unit id="Implemented_members"> <source>Implemented members</source> <target state="translated">Uygulanan üyeler</target> <note /> </trans-unit> <trans-unit id="Implementing_members"> <source>Implementing members</source> <target state="translated">Üyeleri uygulama</target> <note /> </trans-unit> <trans-unit id="Implementing_types"> <source>Implementing types</source> <target state="new">Implementing types</target> <note /> </trans-unit> <trans-unit id="In_other_operators"> <source>In other operators</source> <target state="translated">Diğer işleçlerde</target> <note /> </trans-unit> <trans-unit id="Index"> <source>Index</source> <target state="translated">Dizin</target> <note>Index of parameter in original signature</note> </trans-unit> <trans-unit id="Infer_from_context"> <source>Infer from context</source> <target state="translated">Bağlamdan çıkarsa</target> <note /> </trans-unit> <trans-unit id="Indexed_in_organization"> <source>Indexed in organization</source> <target state="translated">Kuruluş içinde dizini oluşturulmuş</target> <note /> </trans-unit> <trans-unit id="Indexed_in_repo"> <source>Indexed in repo</source> <target state="translated">Depo içinde dizini oluşturulmuş</target> <note /> </trans-unit> <trans-unit id="Inheritance_Margin_experimental"> <source>Inheritance Margin (experimental)</source> <target state="translated">Devralma Marjı (deneysel)</target> <note /> </trans-unit> <trans-unit id="Inherited_interfaces"> <source>Inherited interfaces</source> <target state="new">Inherited interfaces</target> <note /> </trans-unit> <trans-unit id="Inline_Hints_experimental"> <source>Inline Hints (experimental)</source> <target state="translated">Satır İçi İpuçları (deneysel)</target> <note /> </trans-unit> <trans-unit id="Inserting_call_site_value_0"> <source>Inserting call site value '{0}'</source> <target state="translated">Çağırma yeri değeri '{0}' ekleniyor</target> <note /> </trans-unit> <trans-unit id="Install_Microsoft_recommended_Roslyn_analyzers_which_provide_additional_diagnostics_and_fixes_for_common_API_design_security_performance_and_reliability_issues"> <source>Install Microsoft-recommended Roslyn analyzers, which provide additional diagnostics and fixes for common API design, security, performance, and reliability issues</source> <target state="translated">Microsoft'un önerdiği, genel API tasarımı, güvenlik, performans ve güvenilirlik sorunları için ek tanılama ve düzeltmeler sağlayan Roslyn çözümleyicilerini yükleyin</target> <note /> </trans-unit> <trans-unit id="Interface_cannot_have_field"> <source>Interface cannot have field.</source> <target state="translated">Arabirimde alan olamaz.</target> <note /> </trans-unit> <trans-unit id="IntroduceUndefinedTodoVariables"> <source>Introduce undefined TODO variables</source> <target state="translated">Tanımsız TODO değişkenlerini tanıtın</target> <note>"TODO" is an indicator that more work should be done at the location where the TODO is inserted</note> </trans-unit> <trans-unit id="Item_origin"> <source>Item origin</source> <target state="translated">Öğe çıkış noktası</target> <note /> </trans-unit> <trans-unit id="Keep"> <source>Keep</source> <target state="translated">Koru</target> <note /> </trans-unit> <trans-unit id="Keep_all_parentheses_in_colon"> <source>Keep all parentheses in:</source> <target state="translated">Şunun içindeki tüm parantezleri tut:</target> <note /> </trans-unit> <trans-unit id="Kind"> <source>Kind</source> <target state="translated">Tür</target> <note /> </trans-unit> <trans-unit id="Live_analysis_VSIX_extension"> <source>Live analysis (VSIX extension)</source> <target state="translated">Canlı analiz (VSIX uzantısı)</target> <note /> </trans-unit> <trans-unit id="Loaded_items"> <source>Loaded items</source> <target state="translated">Öğeler yüklendi</target> <note /> </trans-unit> <trans-unit id="Loaded_solution"> <source>Loaded solution</source> <target state="translated">Çözüm yüklendi</target> <note /> </trans-unit> <trans-unit id="Local"> <source>Local</source> <target state="translated">Yerel</target> <note /> </trans-unit> <trans-unit id="Local_metadata"> <source>Local metadata</source> <target state="translated">Yerel meta veriler</target> <note /> </trans-unit> <trans-unit id="Location"> <source>Location</source> <target state="new">Location</target> <note /> </trans-unit> <trans-unit id="Make_0_abstract"> <source>Make '{0}' abstract</source> <target state="translated">'{0}' değerini soyut yap</target> <note /> </trans-unit> <trans-unit id="Make_abstract"> <source>Make abstract</source> <target state="translated">Soyut yap</target> <note /> </trans-unit> <trans-unit id="Members"> <source>Members</source> <target state="translated">Üyeler</target> <note /> </trans-unit> <trans-unit id="Modifier_preferences_colon"> <source>Modifier preferences:</source> <target state="translated">Değiştirici tercihleri:</target> <note /> </trans-unit> <trans-unit id="Move_to_namespace"> <source>Move to Namespace</source> <target state="translated">Ad Alanına Taşı</target> <note /> </trans-unit> <trans-unit id="Multiple_members_are_inherited"> <source>Multiple members are inherited</source> <target state="translated">Birden fazla üye devralındı</target> <note /> </trans-unit> <trans-unit id="Multiple_members_are_inherited_on_line_0"> <source>Multiple members are inherited on line {0}</source> <target state="translated">{0}. satırda birden fazla üye devralındı</target> <note>Line number info is needed for accessibility purpose.</note> </trans-unit> <trans-unit id="Name_conflicts_with_an_existing_type_name"> <source>Name conflicts with an existing type name.</source> <target state="translated">Ad, mevcut bir tür adıyla çakışıyor.</target> <note /> </trans-unit> <trans-unit id="Name_is_not_a_valid_0_identifier"> <source>Name is not a valid {0} identifier.</source> <target state="translated">Ad geçerli bir {0} tanımlayıcısı değil.</target> <note /> </trans-unit> <trans-unit id="Namespace"> <source>Namespace</source> <target state="translated">Ad alanı</target> <note /> </trans-unit> <trans-unit id="Namespace_0"> <source>Namespace: '{0}'</source> <target state="translated">Ad alanı: '{0}'</target> <note /> </trans-unit> <trans-unit id="Namespace_declarations"> <source>Namespace declarations</source> <target state="new">Namespace declarations</target> <note /> </trans-unit> <trans-unit id="NamingSpecification_CSharp_Class"> <source>class</source> <target state="new">class</target> <note>{Locked} This string can be found under "Tools | Options | Text Editor | C# | Code Style | Naming | Manage Specifications | + | Symbol kinds". All of the "NamingSpecification_CSharp_*" strings represent language constructs, and some of them are also actual keywords (including this one).</note> </trans-unit> <trans-unit id="NamingSpecification_CSharp_Delegate"> <source>delegate</source> <target state="new">delegate</target> <note>{Locked} This string can be found under "Tools | Options | Text Editor | C# | Code Style | Naming | Manage Specifications | + | Symbol kinds". All of the "NamingSpecification_CSharp_*" strings represent language constructs, and some of them are also actual keywords (including this one).</note> </trans-unit> <trans-unit id="NamingSpecification_CSharp_Enum"> <source>enum</source> <target state="new">enum</target> <note>{Locked} This string can be found under "Tools | Options | Text Editor | C# | Code Style | Naming | Manage Specifications | + | Symbol kinds". All of the "NamingSpecification_CSharp_*" strings represent language constructs, and some of them are also actual keywords (including this one).</note> </trans-unit> <trans-unit id="NamingSpecification_CSharp_Event"> <source>event</source> <target state="new">event</target> <note>{Locked} This string can be found under "Tools | Options | Text Editor | C# | Code Style | Naming | Manage Specifications | + | Symbol kinds". All of the "NamingSpecification_CSharp_*" strings represent language constructs, and some of them are also actual keywords (including this one).</note> </trans-unit> <trans-unit id="NamingSpecification_CSharp_Field"> <source>field</source> <target state="translated">alan</target> <note>This string can be found under "Tools | Options | Text Editor | C# | Code Style | Naming | Manage Specifications | + | Symbol kinds". All of the "NamingSpecification_CSharp_*" strings represent language constructs, and some of them are also actual keywords (NOT this one). Refers to the C# programming language concept of a "field" (which stores data).</note> </trans-unit> <trans-unit id="NamingSpecification_CSharp_Interface"> <source>interface</source> <target state="new">interface</target> <note>{Locked} This string can be found under "Tools | Options | Text Editor | C# | Code Style | Naming | Manage Specifications | + | Symbol kinds". All of the "NamingSpecification_CSharp_*" strings represent language constructs, and some of them are also actual keywords (including this one).</note> </trans-unit> <trans-unit id="NamingSpecification_CSharp_Local"> <source>local</source> <target state="translated">yerel</target> <note>This string can be found under "Tools | Options | Text Editor | C# | Code Style | Naming | Manage Specifications | + | Symbol kinds". All of the "NamingSpecification_CSharp_*" strings represent language constructs, and some of them are also actual keywords (NOT this one). Refers to the C# language concept of a "local variable".</note> </trans-unit> <trans-unit id="NamingSpecification_CSharp_LocalFunction"> <source>local function</source> <target state="translated">yerel işlev</target> <note>This string can be found under "Tools | Options | Text Editor | C# | Code Style | Naming | Manage Specifications | + | Symbol kinds". All of the "NamingSpecification_CSharp_*" strings represent language constructs, and some of them are also actual keywords (NOT this one). Refers to the C# language concept of a "local function" that exists locally within another function.</note> </trans-unit> <trans-unit id="NamingSpecification_CSharp_Method"> <source>method</source> <target state="translated">yöntem</target> <note>This string can be found under "Tools | Options | Text Editor | C# | Code Style | Naming | Manage Specifications | + | Symbol kinds". All of the "NamingSpecification_CSharp_*" strings represent language constructs, and some of them are also actual keywords (NOT this one). Refers to the C# language concept of a "method" that can be called by other code.</note> </trans-unit> <trans-unit id="NamingSpecification_CSharp_Namespace"> <source>namespace</source> <target state="new">namespace</target> <note>{Locked} This string can be found under "Tools | Options | Text Editor | C# | Code Style | Naming | Manage Specifications | + | Symbol kinds". All of the "NamingSpecification_CSharp_*" strings represent language constructs, and some of them are also actual keywords (including this one).</note> </trans-unit> <trans-unit id="NamingSpecification_CSharp_Parameter"> <source>parameter</source> <target state="translated">parametre</target> <note>This string can be found under "Tools | Options | Text Editor | C# | Code Style | Naming | Manage Specifications | + | Symbol kinds". All of the "NamingSpecification_CSharp_*" strings represent language constructs, and some of them are also actual keywords (NOT this one). Refers to the C# language concept of a "parameter" being passed to a method.</note> </trans-unit> <trans-unit id="NamingSpecification_CSharp_Property"> <source>property</source> <target state="translated">özellik</target> <note>This string can be found under "Tools | Options | Text Editor | C# | Code Style | Naming | Manage Specifications | + | Symbol kinds". All of the "NamingSpecification_CSharp_*" strings represent language constructs, and some of them are also actual keywords (NOT this one). Refers to the C# language concept of a "property" (which allows for the retrieval of data).</note> </trans-unit> <trans-unit id="NamingSpecification_CSharp_Struct"> <source>struct</source> <target state="new">struct</target> <note>{Locked} This string can be found under "Tools | Options | Text Editor | C# | Code Style | Naming | Manage Specifications | + | Symbol kinds". All of the "NamingSpecification_CSharp_*" strings represent language constructs, and some of them are also actual keywords (including this one).</note> </trans-unit> <trans-unit id="NamingSpecification_CSharp_TypeParameter"> <source>type parameter</source> <target state="translated">tür parametresi</target> <note>This string can be found under "Tools | Options | Text Editor | C# | Code Style | Naming | Manage Specifications | + | Symbol kinds". All of the "NamingSpecification_CSharp_*" strings represent language constructs, and some of them are also actual keywords (NOT this one). Refers to the C# language concept of a "type parameter".</note> </trans-unit> <trans-unit id="NamingSpecification_VisualBasic_Class"> <source>Class</source> <target state="new">Class</target> <note>{Locked} This string can be found under "Tools | Options | Text Editor | Basic | Code Style | Naming | Manage Specifications | + | Symbol kinds". All of the "NamingSpecification_VisualBasic_*" strings represent language constructs, and some of them are also actual keywords (including this one).</note> </trans-unit> <trans-unit id="NamingSpecification_VisualBasic_Delegate"> <source>Delegate</source> <target state="new">Delegate</target> <note>{Locked} This string can be found under "Tools | Options | Text Editor | Basic | Code Style | Naming | Manage Specifications | + | Symbol kinds". All of the "NamingSpecification_VisualBasic_*" strings represent language constructs, and some of them are also actual keywords (including this one).</note> </trans-unit> <trans-unit id="NamingSpecification_VisualBasic_Enum"> <source>Enum</source> <target state="new">Enum</target> <note>{Locked} This string can be found under "Tools | Options | Text Editor | Basic | Code Style | Naming | Manage Specifications | + | Symbol kinds". All of the "NamingSpecification_VisualBasic_*" strings represent language constructs, and some of them are also actual keywords (including this one).</note> </trans-unit> <trans-unit id="NamingSpecification_VisualBasic_Event"> <source>Event</source> <target state="new">Event</target> <note>{Locked} This string can be found under "Tools | Options | Text Editor | Basic | Code Style | Naming | Manage Specifications | + | Symbol kinds". All of the "NamingSpecification_VisualBasic_*" strings represent language constructs, and some of them are also actual keywords (including this one).</note> </trans-unit> <trans-unit id="NamingSpecification_VisualBasic_Field"> <source>Field</source> <target state="translated">Alan</target> <note>This string can be found under "Tools | Options | Text Editor | Basic | Code Style | Naming | Manage Specifications | + | Symbol kinds". All of the "NamingSpecification_VisualBasic_*" strings represent language constructs, and some of them are also actual keywords (NOT this one). Refers to the Visual Basic language concept of a "field" (which stores data).</note> </trans-unit> <trans-unit id="NamingSpecification_VisualBasic_Interface"> <source>Interface</source> <target state="new">Interface</target> <note>{Locked} This string can be found under "Tools | Options | Text Editor | Basic | Code Style | Naming | Manage Specifications | + | Symbol kinds". All of the "NamingSpecification_VisualBasic_*" strings represent language constructs, and some of them are also actual keywords (including this one).</note> </trans-unit> <trans-unit id="NamingSpecification_VisualBasic_Local"> <source>Local</source> <target state="translated">Yerel</target> <note>This string can be found under "Tools | Options | Text Editor | Basic | Code Style | Naming | Manage Specifications | + | Symbol kinds". All of the "NamingSpecification_VisualBasic_*" strings represent language constructs, and some of them are also actual keywords (NOT this one). Refers to the Visual Basic language concept of a "local variable".</note> </trans-unit> <trans-unit id="NamingSpecification_VisualBasic_Method"> <source>Method</source> <target state="translated">yöntem</target> <note>This string can be found under "Tools | Options | Text Editor | Basic | Code Style | Naming | Manage Specifications | + | Symbol kinds". All of the "NamingSpecification_VisualBasic_*" strings represent language constructs, and some of them are also actual keywords (NOT this one). Refers to the Visual Basic language concept of a "method".</note> </trans-unit> <trans-unit id="NamingSpecification_VisualBasic_Module"> <source>Module</source> <target state="new">Module</target> <note>{Locked} This string can be found under "Tools | Options | Text Editor | Basic | Code Style | Naming | Manage Specifications | + | Symbol kinds". All of the "NamingSpecification_VisualBasic_*" strings represent language constructs, and some of them are also actual keywords (including this one).</note> </trans-unit> <trans-unit id="NamingSpecification_VisualBasic_Namespace"> <source>Namespace</source> <target state="new">Namespace</target> <note>{Locked} This string can be found under "Tools | Options | Text Editor | Basic | Code Style | Naming | Manage Specifications | + | Symbol kinds". All of the "NamingSpecification_VisualBasic_*" strings represent language constructs, and some of them are also actual keywords (including this one).</note> </trans-unit> <trans-unit id="NamingSpecification_VisualBasic_Parameter"> <source>Parameter</source> <target state="translated">Parametre</target> <note>This string can be found under "Tools | Options | Text Editor | Basic | Code Style | Naming | Manage Specifications | + | Symbol kinds". All of the "NamingSpecification_VisualBasic_*" strings represent language constructs, and some of them are also actual keywords (NOT this one). Refers to the Visual Basic language concept of a "parameter" which can be passed to a method.</note> </trans-unit> <trans-unit id="NamingSpecification_VisualBasic_Property"> <source>Property</source> <target state="new">Property</target> <note>{Locked} This string can be found under "Tools | Options | Text Editor | Basic | Code Style | Naming | Manage Specifications | + | Symbol kinds". All of the "NamingSpecification_VisualBasic_*" strings represent language constructs, and some of them are also actual keywords (including this one).</note> </trans-unit> <trans-unit id="NamingSpecification_VisualBasic_Structure"> <source>Structure</source> <target state="new">Structure</target> <note>{Locked} This string can be found under "Tools | Options | Text Editor | Basic | Code Style | Naming | Manage Specifications | + | Symbol kinds". All of the "NamingSpecification_VisualBasic_*" strings represent language constructs, and some of them are also actual keywords (including this one).</note> </trans-unit> <trans-unit id="NamingSpecification_VisualBasic_TypeParameter"> <source>Type Parameter</source> <target state="translated">Tür Parametresi</target> <note>This string can be found under "Tools | Options | Text Editor | Basic | Code Style | Naming | Manage Specifications | + | Symbol kinds". All of the "NamingSpecification_VisualBasic_*" strings represent language constructs, and some of them are also actual keywords (NOT this one). Refers to the Visual Basic language concept of a "type parameter".</note> </trans-unit> <trans-unit id="Naming_rules"> <source>Naming rules</source> <target state="translated">Adlandırma kuralları</target> <note /> </trans-unit> <trans-unit id="Navigate_to_0"> <source>Navigate to '{0}'</source> <target state="translated">'{0}' öğesine git</target> <note /> </trans-unit> <trans-unit id="Never_if_unnecessary"> <source>Never if unnecessary</source> <target state="translated">Gereksizse hiçbir zaman</target> <note /> </trans-unit> <trans-unit id="New_Type_Name_colon"> <source>New Type Name:</source> <target state="translated">Yeni Tür Adı:</target> <note /> </trans-unit> <trans-unit id="New_line_preferences_experimental_colon"> <source>New line preferences (experimental):</source> <target state="translated">Yeni satır tercihleri (deneysel):</target> <note /> </trans-unit> <trans-unit id="Newline_n"> <source>Newline (\\n)</source> <target state="translated">Yeni Satır (\\n)</target> <note /> </trans-unit> <trans-unit id="No_unused_references_were_found"> <source>No unused references were found.</source> <target state="translated">Kullanılmayan başvuru bulunamadı.</target> <note /> </trans-unit> <trans-unit id="Non_public_methods"> <source>Non-public methods</source> <target state="translated">Ortak olmayan yöntemler</target> <note /> </trans-unit> <trans-unit id="None"> <source>None</source> <target state="translated">yok</target> <note /> </trans-unit> <trans-unit id="Omit_only_for_optional_parameters"> <source>Omit (only for optional parameters)</source> <target state="translated">Atla (yalnızca isteğe bağlı parametreler için)</target> <note /> </trans-unit> <trans-unit id="Open_documents"> <source>Open documents</source> <target state="translated">Açık belgeler</target> <note /> </trans-unit> <trans-unit id="Optional_parameters_must_provide_a_default_value"> <source>Optional parameters must provide a default value</source> <target state="translated">İsteğe bağlı parametrelerde varsayılan değer sağlanmalıdır</target> <note /> </trans-unit> <trans-unit id="Optional_with_default_value_colon"> <source>Optional with default value:</source> <target state="translated">Varsayılan değerle isteğe bağlı:</target> <note /> </trans-unit> <trans-unit id="Other"> <source>Others</source> <target state="translated">Diğer</target> <note /> </trans-unit> <trans-unit id="Overridden_members"> <source>Overridden members</source> <target state="translated">Geçersiz kılınan üyeler</target> <note /> </trans-unit> <trans-unit id="Overriding_members"> <source>Overriding members</source> <target state="translated">Üyeleri geçersiz kılma</target> <note /> </trans-unit> <trans-unit id="Packages"> <source>Packages</source> <target state="translated">Paketler</target> <note /> </trans-unit> <trans-unit id="Parameter_Details"> <source>Parameter Details</source> <target state="translated">Parametre Ayrıntıları</target> <note /> </trans-unit> <trans-unit id="Parameter_Name"> <source>Parameter name:</source> <target state="translated">Parametre adı:</target> <note /> </trans-unit> <trans-unit id="Parameter_information"> <source>Parameter information</source> <target state="translated">Parametre bilgileri</target> <note /> </trans-unit> <trans-unit id="Parameter_kind"> <source>Parameter kind</source> <target state="translated">Parametre tipi</target> <note /> </trans-unit> <trans-unit id="Parameter_name_contains_invalid_characters"> <source>Parameter name contains invalid character(s).</source> <target state="translated">Parametre adı geçersiz karakterler içeriyor.</target> <note /> </trans-unit> <trans-unit id="Parameter_preferences_colon"> <source>Parameter preferences:</source> <target state="translated">Parametre tercihleri:</target> <note /> </trans-unit> <trans-unit id="Parameter_type_contains_invalid_characters"> <source>Parameter type contains invalid character(s).</source> <target state="translated">Parametre türü geçersiz karakterler içeriyor.</target> <note /> </trans-unit> <trans-unit id="Parentheses_preferences_colon"> <source>Parentheses preferences:</source> <target state="translated">Parantez tercihleri:</target> <note /> </trans-unit> <trans-unit id="Paused_0_tasks_in_queue"> <source>Paused ({0} tasks in queue)</source> <target state="translated">Duraklatıldı (kuyrukta {0} görev var)</target> <note /> </trans-unit> <trans-unit id="Please_enter_a_type_name"> <source>Please enter a type name</source> <target state="translated">Lütfen bir tür adı yazın</target> <note>"Type" is the programming language concept</note> </trans-unit> <trans-unit id="Prefer_System_HashCode_in_GetHashCode"> <source>Prefer 'System.HashCode' in 'GetHashCode'</source> <target state="translated">'GetHashCode' içinde 'System.HashCode' tercih et</target> <note /> </trans-unit> <trans-unit id="Prefer_compound_assignments"> <source>Prefer compound assignments</source> <target state="translated">Bileşik atamaları tercih et</target> <note /> </trans-unit> <trans-unit id="Prefer_index_operator"> <source>Prefer index operator</source> <target state="translated">Dizin işlecini tercih et</target> <note /> </trans-unit> <trans-unit id="Prefer_range_operator"> <source>Prefer range operator</source> <target state="translated">Aralık işlecini tercih et</target> <note /> </trans-unit> <trans-unit id="Prefer_readonly_fields"> <source>Prefer readonly fields</source> <target state="translated">Saltokunur alanları tercih et</target> <note /> </trans-unit> <trans-unit id="Prefer_simple_using_statement"> <source>Prefer simple 'using' statement</source> <target state="translated">Basit 'using' deyimini tercih et</target> <note /> </trans-unit> <trans-unit id="Prefer_simplified_boolean_expressions"> <source>Prefer simplified boolean expressions</source> <target state="translated">Basitleştirilmiş boolean ifadelerini tercih edin</target> <note /> </trans-unit> <trans-unit id="Prefer_static_local_functions"> <source>Prefer static local functions</source> <target state="translated">Statik yerel işlevleri tercih et</target> <note /> </trans-unit> <trans-unit id="Projects"> <source>Projects</source> <target state="translated">Projeler</target> <note /> </trans-unit> <trans-unit id="Pull_Members_Up"> <source>Pull Members Up</source> <target state="translated">Üyeleri Yukarı Çek</target> <note /> </trans-unit> <trans-unit id="Refactoring_Only"> <source>Refactoring Only</source> <target state="translated">Sadece Yeniden Düzenlenme</target> <note /> </trans-unit> <trans-unit id="Reference"> <source>Reference</source> <target state="translated">Başvuru</target> <note /> </trans-unit> <trans-unit id="Regular_Expressions"> <source>Regular Expressions</source> <target state="translated">Normal İfadeler</target> <note /> </trans-unit> <trans-unit id="Remove_All"> <source>Remove All</source> <target state="translated">Tümünü Kaldır</target> <note /> </trans-unit> <trans-unit id="Remove_Unused_References"> <source>Remove Unused References</source> <target state="translated">Kullanılmayan Başvuruları Kaldır</target> <note /> </trans-unit> <trans-unit id="Rename_0_to_1"> <source>Rename {0} to {1}</source> <target state="translated">{0} öğesini {1} olarak yeniden adlandır</target> <note /> </trans-unit> <trans-unit id="Report_invalid_regular_expressions"> <source>Report invalid regular expressions</source> <target state="translated">Geçersiz normal ifadeleri bildir</target> <note /> </trans-unit> <trans-unit id="Repository"> <source>Repository</source> <target state="translated">Depo</target> <note /> </trans-unit> <trans-unit id="Require_colon"> <source>Require:</source> <target state="translated">Gerektir:</target> <note /> </trans-unit> <trans-unit id="Required"> <source>Required</source> <target state="translated">Gerekli</target> <note /> </trans-unit> <trans-unit id="Requires_System_HashCode_be_present_in_project"> <source>Requires 'System.HashCode' be present in project</source> <target state="translated">Projede 'System.HashCode' bulunmasını gerektirir</target> <note /> </trans-unit> <trans-unit id="Reset_Visual_Studio_default_keymapping"> <source>Reset Visual Studio default keymapping</source> <target state="translated">Visual Studio varsayılan tuş eşlemesine sıfırla</target> <note /> </trans-unit> <trans-unit id="Review_Changes"> <source>Review Changes</source> <target state="translated">Değişiklikleri Gözden Geçir</target> <note /> </trans-unit> <trans-unit id="Run_Code_Analysis_on_0"> <source>Run Code Analysis on {0}</source> <target state="translated">{0} Öğesinde Code Analysis Çalıştır</target> <note /> </trans-unit> <trans-unit id="Running_code_analysis_for_0"> <source>Running code analysis for '{0}'...</source> <target state="translated">'{0}' için kod analizi çalıştırılıyor...</target> <note /> </trans-unit> <trans-unit id="Running_code_analysis_for_Solution"> <source>Running code analysis for Solution...</source> <target state="translated">Çözüm için kod analizi çalıştırılıyor...</target> <note /> </trans-unit> <trans-unit id="Running_low_priority_background_processes"> <source>Running low priority background processes</source> <target state="translated">Düşük öncelikli arka plan işlemleri çalıştırılıyor</target> <note /> </trans-unit> <trans-unit id="Save_dot_editorconfig_file"> <source>Save .editorconfig file</source> <target state="translated">.editorconfig dosyasını kaydet</target> <note /> </trans-unit> <trans-unit id="Search_Settings"> <source>Search Settings</source> <target state="translated">Arama Ayarları</target> <note /> </trans-unit> <trans-unit id="Select_an_appropriate_symbol_to_start_value_tracking"> <source>Select an appropriate symbol to start value tracking</source> <target state="new">Select an appropriate symbol to start value tracking</target> <note /> </trans-unit> <trans-unit id="Select_destination"> <source>Select destination</source> <target state="translated">Hedef seçin</target> <note /> </trans-unit> <trans-unit id="Select_Dependents"> <source>Select _Dependents</source> <target state="translated">_Bağımlıları Seçin</target> <note /> </trans-unit> <trans-unit id="Select_Public"> <source>Select _Public</source> <target state="translated">_Geneli Seçin</target> <note /> </trans-unit> <trans-unit id="Select_destination_and_members_to_pull_up"> <source>Select destination and members to pull up.</source> <target state="translated">Hedef ve yukarı çekilecek üyeleri seçin.</target> <note /> </trans-unit> <trans-unit id="Select_destination_colon"> <source>Select destination:</source> <target state="translated">Hedef seçin:</target> <note /> </trans-unit> <trans-unit id="Select_member"> <source>Select member</source> <target state="translated">Üye seçin</target> <note /> </trans-unit> <trans-unit id="Select_members_colon"> <source>Select members:</source> <target state="translated">Üye seçin:</target> <note /> </trans-unit> <trans-unit id="Show_Remove_Unused_References_command_in_Solution_Explorer_experimental"> <source>Show "Remove Unused References" command in Solution Explorer (experimental)</source> <target state="translated">Çözüm Gezgini'nde "Kullanılmayan Başvuruları Kaldır" komutunu göster (deneysel)</target> <note /> </trans-unit> <trans-unit id="Show_completion_list"> <source>Show completion list</source> <target state="translated">Tamamlama listesini göster</target> <note /> </trans-unit> <trans-unit id="Show_hints_for_everything_else"> <source>Show hints for everything else</source> <target state="translated">Diğer her şey için ipuçlarını göster</target> <note /> </trans-unit> <trans-unit id="Show_hints_for_implicit_object_creation"> <source>Show hints for implicit object creation</source> <target state="translated">Örtük nesne oluşturma ipuçlarını göster</target> <note /> </trans-unit> <trans-unit id="Show_hints_for_lambda_parameter_types"> <source>Show hints for lambda parameter types</source> <target state="translated">Lambda parametre türleri için ipuçlarını göster</target> <note /> </trans-unit> <trans-unit id="Show_hints_for_literals"> <source>Show hints for literals</source> <target state="translated">Sabit değerler için ipuçlarını göster</target> <note /> </trans-unit> <trans-unit id="Show_hints_for_variables_with_inferred_types"> <source>Show hints for variables with inferred types</source> <target state="translated">Çıkarsanan türlere sahip değişkenler için ipuçlarını göster</target> <note /> </trans-unit> <trans-unit id="Show_inheritance_margin"> <source>Show inheritance margin</source> <target state="translated">Devralma boşluğunu göster</target> <note /> </trans-unit> <trans-unit id="Skip_analyzers_for_implicitly_triggered_builds"> <source>Skip analyzers for implicitly triggered builds</source> <target state="new">Skip analyzers for implicitly triggered builds</target> <note /> </trans-unit> <trans-unit id="Some_color_scheme_colors_are_being_overridden_by_changes_made_in_the_Environment_Fonts_and_Colors_options_page_Choose_Use_Defaults_in_the_Fonts_and_Colors_page_to_revert_all_customizations"> <source>Some color scheme colors are being overridden by changes made in the Environment &gt; Fonts and Colors options page. Choose `Use Defaults` in the Fonts and Colors page to revert all customizations.</source> <target state="translated">Bazı renk düzeni renkleri, Ortam &gt; Yazı Tipleri ve Renkler seçenek sayfasında yapılan değişiklikler tarafından geçersiz kılınıyor. Tüm özelleştirmeleri geri döndürmek için Yazı Tipleri ve Renkler sayfasında `Varsayılanları Kullan` seçeneğini belirleyin.</target> <note /> </trans-unit> <trans-unit id="Suggestion"> <source>Suggestion</source> <target state="translated">Öneri</target> <note /> </trans-unit> <trans-unit id="Suppress_hints_when_parameter_name_matches_the_method_s_intent"> <source>Suppress hints when parameter name matches the method's intent</source> <target state="translated">Parametre adı metodun hedefi ile eşleştiğinde ipuçlarını gizle</target> <note /> </trans-unit> <trans-unit id="Suppress_hints_when_parameter_names_differ_only_by_suffix"> <source>Suppress hints when parameter names differ only by suffix</source> <target state="translated">Parametre adlarının yalnızca sonekleri farklı olduğunda ipuçlarını gizle</target> <note /> </trans-unit> <trans-unit id="Symbols_without_references"> <source>Symbols without references</source> <target state="translated">Başvuruları olmayan semboller</target> <note /> </trans-unit> <trans-unit id="Tab_twice_to_insert_arguments"> <source>Tab twice to insert arguments (experimental)</source> <target state="translated">Bağımsız değişkenleri eklemek için iki kez dokunun (deneysel)</target> <note /> </trans-unit> <trans-unit id="Target_Namespace_colon"> <source>Target Namespace:</source> <target state="translated">Hedef Ad Alanı:</target> <note /> </trans-unit> <trans-unit id="The_generator_0_that_generated_this_file_has_been_removed_from_the_project"> <source>The generator '{0}' that generated this file has been removed from the project; this file is no longer being included in your project.</source> <target state="translated">Bu dosyayı oluşturan '{0}' oluşturucusu projeden kaldırıldı; bu dosya artık projenize dahil edilmiyor.</target> <note /> </trans-unit> <trans-unit id="The_generator_0_that_generated_this_file_has_stopped_generating_this_file"> <source>The generator '{0}' that generated this file has stopped generating this file; this file is no longer being included in your project.</source> <target state="translated">Bu dosyayı oluşturan '{0}' oluşturucusu bu dosyayı oluşturmayı durdurdu; bu dosya artık projenize dahil edilmiyor.</target> <note /> </trans-unit> <trans-unit id="This_action_cannot_be_undone_Do_you_wish_to_continue"> <source>This action cannot be undone. Do you wish to continue?</source> <target state="translated">Bu işlem geri alınamaz. Devam etmek istiyor musunuz?</target> <note /> </trans-unit> <trans-unit id="This_file_is_autogenerated_by_0_and_cannot_be_edited"> <source>This file is auto-generated by the generator '{0}' and cannot be edited.</source> <target state="translated">Bu dosya, '{0}' oluşturucusu tarafından otomatik olarak oluşturuldu ve düzenlenemez.</target> <note /> </trans-unit> <trans-unit id="This_is_an_invalid_namespace"> <source>This is an invalid namespace</source> <target state="translated">Bu geçersiz bir ad alanı</target> <note /> </trans-unit> <trans-unit id="Title"> <source>Title</source> <target state="translated">Başlık</target> <note /> </trans-unit> <trans-unit id="Type_Name"> <source>Type name:</source> <target state="translated">Tür adı:</target> <note /> </trans-unit> <trans-unit id="Type_name_has_a_syntax_error"> <source>Type name has a syntax error</source> <target state="translated">Tür adında söz dizimi hatası var</target> <note>"Type" is the programming language concept</note> </trans-unit> <trans-unit id="Type_name_is_not_recognized"> <source>Type name is not recognized</source> <target state="translated">Tür adı tanınmıyor</target> <note>"Type" is the programming language concept</note> </trans-unit> <trans-unit id="Type_name_is_recognized"> <source>Type name is recognized</source> <target state="translated">Tür adı tanınıyor</target> <note>"Type" is the programming language concept</note> </trans-unit> <trans-unit id="Underline_reassigned_variables"> <source>Underline reassigned variables</source> <target state="new">Underline reassigned variables</target> <note /> </trans-unit> <trans-unit id="Unused_value_is_explicitly_assigned_to_an_unused_local"> <source>Unused value is explicitly assigned to an unused local</source> <target state="translated">Kullanılmayan değer açıkça kullanılmayan bir yerele atandı</target> <note /> </trans-unit> <trans-unit id="Unused_value_is_explicitly_assigned_to_discard"> <source>Unused value is explicitly assigned to discard</source> <target state="translated">Kullanılmayan değer açıkça atılmak üzere atandı</target> <note /> </trans-unit> <trans-unit id="Updating_project_references"> <source>Updating project references...</source> <target state="translated">Proje başvuruları güncelleştiriliyor...</target> <note /> </trans-unit> <trans-unit id="Updating_severity"> <source>Updating severity</source> <target state="translated">Önem derecesi güncelleştiriliyor</target> <note /> </trans-unit> <trans-unit id="Use_64_bit_process_for_code_analysis_requires_restart"> <source>Use 64-bit process for code analysis (requires restart)</source> <target state="translated">Kod analizi için 64 bit işlemi kullanın (yeniden başlatma gerekir)</target> <note /> </trans-unit> <trans-unit id="Use_expression_body_for_lambdas"> <source>Use expression body for lambdas</source> <target state="translated">Lambdalar için ifade gövdesi kullan</target> <note /> </trans-unit> <trans-unit id="Use_expression_body_for_local_functions"> <source>Use expression body for local functions</source> <target state="translated">Yerel işlevler için ifade gövdesi kullan</target> <note /> </trans-unit> <trans-unit id="Use_named_argument"> <source>Use named argument</source> <target state="translated">Adlandırılmış bağımsız değişken kullan</target> <note>"argument" is a programming term for a value passed to a function</note> </trans-unit> <trans-unit id="Value"> <source>Value</source> <target state="translated">Değer</target> <note /> </trans-unit> <trans-unit id="Value_Tracking"> <source>Value Tracking</source> <target state="new">Value Tracking</target> <note>Title of the "Value Tracking" tool window. "Value" is the variable/symbol and "Tracking" is the action the tool is doing to follow where the value can originate from.</note> </trans-unit> <trans-unit id="Value_assigned_here_is_never_used"> <source>Value assigned here is never used</source> <target state="translated">Burada atanan değer hiçbir zaman kullanılmadı</target> <note /> </trans-unit> <trans-unit id="Value_colon"> <source>Value:</source> <target state="translated">Değer:</target> <note /> </trans-unit> <trans-unit id="Value_returned_by_invocation_is_implicitly_ignored"> <source>Value returned by invocation is implicitly ignored</source> <target state="translated">Çağrı ile döndürülen değer örtük olarak yok sayıldı</target> <note /> </trans-unit> <trans-unit id="Value_to_inject_at_call_sites"> <source>Value to inject at call sites</source> <target state="translated">Çağrı sitelerinde eklenecek değer</target> <note /> </trans-unit> <trans-unit id="Visual_Studio_2017"> <source>Visual Studio 2017</source> <target state="translated">Visual Studio 2017</target> <note /> </trans-unit> <trans-unit id="Visual_Studio_2019"> <source>Visual Studio 2019</source> <target state="translated">Visual Studio 2019</target> <note /> </trans-unit> <trans-unit id="Visual_Studio_Settings"> <source>Visual Studio Settings</source> <target state="new">Visual Studio Settings</target> <note /> </trans-unit> <trans-unit id="Warning"> <source>Warning</source> <target state="translated">Uyarı</target> <note /> </trans-unit> <trans-unit id="Warning_colon_duplicate_parameter_name"> <source>Warning: duplicate parameter name</source> <target state="translated">Uyarı: Yinelenen parametre adı</target> <note /> </trans-unit> <trans-unit id="Warning_colon_type_does_not_bind"> <source>Warning: type does not bind</source> <target state="translated">Uyarı: Tür bağlamıyor</target> <note /> </trans-unit> <trans-unit id="We_notice_you_suspended_0_Reset_keymappings_to_continue_to_navigate_and_refactor"> <source>We notice you suspended '{0}'. Reset keymappings to continue to navigate and refactor.</source> <target state="translated">'{0}' öğesini askıya aldığınızı fark ettik. Gezintiye ve yeniden düzenlemeye devam etmek için tuş eşlemelerini sıfırlayın.</target> <note /> </trans-unit> <trans-unit id="This_workspace_does_not_support_updating_Visual_Basic_compilation_options"> <source>This workspace does not support updating Visual Basic compilation options.</source> <target state="translated">Bu çalışma alanı Visual Basic derleme seçeneklerinin güncelleştirilmesini desteklemiyor.</target> <note /> </trans-unit> <trans-unit id="Whitespace"> <source>Whitespace</source> <target state="new">Whitespace</target> <note /> </trans-unit> <trans-unit id="You_must_change_the_signature"> <source>You must change the signature</source> <target state="translated">İmzayı değiştirmelisiniz</target> <note>"signature" here means the definition of a method</note> </trans-unit> <trans-unit id="You_must_select_at_least_one_member"> <source>You must select at least one member.</source> <target state="translated">En az bir üye seçmelisiniz.</target> <note /> </trans-unit> <trans-unit id="Illegal_characters_in_path"> <source>Illegal characters in path.</source> <target state="translated">Yolda geçersiz karakterler var.</target> <note /> </trans-unit> <trans-unit id="File_name_must_have_the_0_extension"> <source>File name must have the "{0}" extension.</source> <target state="translated">Dosya adı "{0}" uzantısını içermelidir.</target> <note /> </trans-unit> <trans-unit id="Debugger"> <source>Debugger</source> <target state="translated">Hata Ayıklayıcı</target> <note /> </trans-unit> <trans-unit id="Determining_breakpoint_location"> <source>Determining breakpoint location...</source> <target state="translated">Kesme noktası konumu belirleniyor...</target> <note /> </trans-unit> <trans-unit id="Determining_autos"> <source>Determining autos...</source> <target state="translated">İfade ve değişkenler belirleniyor...</target> <note /> </trans-unit> <trans-unit id="Resolving_breakpoint_location"> <source>Resolving breakpoint location...</source> <target state="translated">Kesme noktası konumu çözümleniyor...</target> <note /> </trans-unit> <trans-unit id="Validating_breakpoint_location"> <source>Validating breakpoint location...</source> <target state="translated">Kesme noktası konumu doğrulanıyor...</target> <note /> </trans-unit> <trans-unit id="Getting_DataTip_text"> <source>Getting DataTip text...</source> <target state="translated">DataTip metni alınıyor...</target> <note /> </trans-unit> <trans-unit id="Preview_unavailable"> <source>Preview unavailable</source> <target state="translated">Önizleme kullanılamıyor</target> <note /> </trans-unit> <trans-unit id="Overrides_"> <source>Overrides</source> <target state="translated">Geçersiz Kılan</target> <note /> </trans-unit> <trans-unit id="Overridden_By"> <source>Overridden By</source> <target state="translated">Geçersiz Kılınan</target> <note /> </trans-unit> <trans-unit id="Inherits_"> <source>Inherits</source> <target state="translated">Devralınan</target> <note /> </trans-unit> <trans-unit id="Inherited_By"> <source>Inherited By</source> <target state="translated">Devralan</target> <note /> </trans-unit> <trans-unit id="Implements_"> <source>Implements</source> <target state="translated">Uygulanan</target> <note /> </trans-unit> <trans-unit id="Implemented_By"> <source>Implemented By</source> <target state="translated">Uygulayan</target> <note /> </trans-unit> <trans-unit id="Maximum_number_of_documents_are_open"> <source>Maximum number of documents are open.</source> <target state="translated">Açılabilecek en fazla belge sayısına ulaşıldı.</target> <note /> </trans-unit> <trans-unit id="Failed_to_create_document_in_miscellaneous_files_project"> <source>Failed to create document in miscellaneous files project.</source> <target state="translated">Diğer Dosyalar projesinde belge oluşturulamadı.</target> <note /> </trans-unit> <trans-unit id="Invalid_access"> <source>Invalid access.</source> <target state="translated">Geçersiz erişim.</target> <note /> </trans-unit> <trans-unit id="The_following_references_were_not_found_0_Please_locate_and_add_them_manually"> <source>The following references were not found. {0}Please locate and add them manually.</source> <target state="translated">Aşağıdaki başvurular bulunamadı. {0}Lütfen bu başvuruları el ile bulun ve ekleyin.</target> <note /> </trans-unit> <trans-unit id="End_position_must_be_start_position"> <source>End position must be &gt;= start position</source> <target state="translated">Bitiş konumu, başlangıç konumuna eşit veya bundan sonra olmalıdır</target> <note /> </trans-unit> <trans-unit id="Not_a_valid_value"> <source>Not a valid value</source> <target state="translated">Geçerli bir değer değil</target> <note /> </trans-unit> <trans-unit id="_0_is_inherited"> <source>'{0}' is inherited</source> <target state="translated">'{0}' devralındı</target> <note /> </trans-unit> <trans-unit id="_0_will_be_changed_to_abstract"> <source>'{0}' will be changed to abstract.</source> <target state="translated">'{0}' soyut olacak şekilde değiştirildi.</target> <note /> </trans-unit> <trans-unit id="_0_will_be_changed_to_non_static"> <source>'{0}' will be changed to non-static.</source> <target state="translated">'{0}' statik olmayacak şekilde değiştirildi.</target> <note /> </trans-unit> <trans-unit id="_0_will_be_changed_to_public"> <source>'{0}' will be changed to public.</source> <target state="translated">'{0}' ortak olacak şekilde değiştirildi.</target> <note /> </trans-unit> <trans-unit id="generated_by_0_suffix"> <source>[generated by {0}]</source> <target state="translated">[{0} tarafından oluşturuldu]</target> <note>{0} is the name of a generator.</note> </trans-unit> <trans-unit id="generated_suffix"> <source>[generated]</source> <target state="translated">[oluşturuldu]</target> <note /> </trans-unit> <trans-unit id="given_workspace_doesn_t_support_undo"> <source>given workspace doesn't support undo</source> <target state="translated">sağlanan çalışma alanı, geri almayı desteklemiyor</target> <note /> </trans-unit> <trans-unit id="Add_a_reference_to_0"> <source>Add a reference to '{0}'</source> <target state="translated">'{0}' öğesine başvuru ekleyin</target> <note /> </trans-unit> <trans-unit id="Event_type_is_invalid"> <source>Event type is invalid</source> <target state="translated">Olay türü geçersiz</target> <note /> </trans-unit> <trans-unit id="Can_t_find_where_to_insert_member"> <source>Can't find where to insert member</source> <target state="translated">Üyenin ekleneceği konum bulunamıyor</target> <note /> </trans-unit> <trans-unit id="Can_t_rename_other_elements"> <source>Can't rename 'other' elements</source> <target state="translated">other' öğeleri yeniden adlandırılamıyor</target> <note /> </trans-unit> <trans-unit id="Unknown_rename_type"> <source>Unknown rename type</source> <target state="translated">Bilinmeyen yeniden adlandırma türü</target> <note /> </trans-unit> <trans-unit id="IDs_are_not_supported_for_this_symbol_type"> <source>IDs are not supported for this symbol type.</source> <target state="translated">Bu sembol türü için kimlikler desteklenmiyor.</target> <note /> </trans-unit> <trans-unit id="Can_t_create_a_node_id_for_this_symbol_kind_colon_0"> <source>Can't create a node id for this symbol kind: '{0}'</source> <target state="translated">'{0}' sembol türü için düğüm kimliği oluşturulamıyor</target> <note /> </trans-unit> <trans-unit id="Project_References"> <source>Project References</source> <target state="translated">Proje Başvuruları</target> <note /> </trans-unit> <trans-unit id="Base_Types"> <source>Base Types</source> <target state="translated">Temel Türler</target> <note /> </trans-unit> <trans-unit id="Miscellaneous_Files"> <source>Miscellaneous Files</source> <target state="translated">Diğer Dosyalar</target> <note /> </trans-unit> <trans-unit id="Could_not_find_project_0"> <source>Could not find project '{0}'</source> <target state="translated">'{0}' adlı proje bulunamadı</target> <note /> </trans-unit> <trans-unit id="Could_not_find_location_of_folder_on_disk"> <source>Could not find location of folder on disk</source> <target state="translated">Diskte klasörün konumu bulunamadı</target> <note /> </trans-unit> <trans-unit id="Assembly"> <source>Assembly </source> <target state="translated">Bütünleştirilmiş Kod </target> <note /> </trans-unit> <trans-unit id="Exceptions_colon"> <source>Exceptions:</source> <target state="translated">Özel Durumlar:</target> <note /> </trans-unit> <trans-unit id="Member_of_0"> <source>Member of {0}</source> <target state="translated">{0} üyesi</target> <note /> </trans-unit> <trans-unit id="Parameters_colon1"> <source>Parameters:</source> <target state="translated">Parametreler:</target> <note /> </trans-unit> <trans-unit id="Project"> <source>Project </source> <target state="translated">Proje </target> <note /> </trans-unit> <trans-unit id="Remarks_colon"> <source>Remarks:</source> <target state="translated">Açıklamalar:</target> <note /> </trans-unit> <trans-unit id="Returns_colon"> <source>Returns:</source> <target state="translated">Döndürülenler:</target> <note /> </trans-unit> <trans-unit id="Summary_colon"> <source>Summary:</source> <target state="translated">Özet:</target> <note /> </trans-unit> <trans-unit id="Type_Parameters_colon"> <source>Type Parameters:</source> <target state="translated">Tür Parametreleri:</target> <note /> </trans-unit> <trans-unit id="File_already_exists"> <source>File already exists</source> <target state="translated">Dosya zaten var</target> <note /> </trans-unit> <trans-unit id="File_path_cannot_use_reserved_keywords"> <source>File path cannot use reserved keywords</source> <target state="translated">Dosya yolunda ayrılmış anahtar sözcükler kullanılamaz</target> <note /> </trans-unit> <trans-unit id="DocumentPath_is_illegal"> <source>DocumentPath is illegal</source> <target state="translated">DocumentPath geçersiz</target> <note /> </trans-unit> <trans-unit id="Project_Path_is_illegal"> <source>Project Path is illegal</source> <target state="translated">Proje Yolu geçersiz</target> <note /> </trans-unit> <trans-unit id="Path_cannot_have_empty_filename"> <source>Path cannot have empty filename</source> <target state="translated">Yoldaki dosya adı boş olamaz</target> <note /> </trans-unit> <trans-unit id="The_given_DocumentId_did_not_come_from_the_Visual_Studio_workspace"> <source>The given DocumentId did not come from the Visual Studio workspace.</source> <target state="translated">Sağlanan DocumentId değeri, Visual Studio çalışma alanında bulunmuyor.</target> <note /> </trans-unit> <trans-unit id="Project_colon_0_1_Use_the_dropdown_to_view_and_switch_to_other_projects_this_file_may_belong_to"> <source>Project: {0} ({1}) Use the dropdown to view and switch to other projects this file may belong to.</source> <target state="translated">Proje: {0} ({1}) Bu dosyanın ait olabileceği diğer projeleri görüntülemek ve bunlara geçiş yapmak için açılan menüyü kullanın.</target> <note /> </trans-unit> <trans-unit id="_0_Use_the_dropdown_to_view_and_navigate_to_other_items_in_this_file"> <source>{0} Use the dropdown to view and navigate to other items in this file.</source> <target state="translated">{0} Bu dosyadaki diğer öğeleri görüntülemek ve bu öğelere gitmek için açılan menüyü kullanın.</target> <note /> </trans-unit> <trans-unit id="Project_colon_0_Use_the_dropdown_to_view_and_switch_to_other_projects_this_file_may_belong_to"> <source>Project: {0} Use the dropdown to view and switch to other projects this file may belong to.</source> <target state="translated">Proje: {0} Bu dosyanın ait olabileceği diğer projeleri görüntülemek ve bunlara geçiş yapmak için açılan menüyü kullanın.</target> <note /> </trans-unit> <trans-unit id="AnalyzerChangedOnDisk"> <source>AnalyzerChangedOnDisk</source> <target state="translated">AnalyzerChangedOnDisk</target> <note /> </trans-unit> <trans-unit id="The_analyzer_assembly_0_has_changed_Diagnostics_may_be_incorrect_until_Visual_Studio_is_restarted"> <source>The analyzer assembly '{0}' has changed. Diagnostics may be incorrect until Visual Studio is restarted.</source> <target state="translated">Çözümleyici bütünleştirilmiş kodu '{0}' değiştirildi. Visual Studio yeniden başlatılmazsa tanılama yanlış olabilir.</target> <note /> </trans-unit> <trans-unit id="CSharp_VB_Diagnostics_Table_Data_Source"> <source>C#/VB Diagnostics Table Data Source</source> <target state="translated">C#/VB Tanılama Tablosu Veri Kaynağı</target> <note /> </trans-unit> <trans-unit id="CSharp_VB_Todo_List_Table_Data_Source"> <source>C#/VB Todo List Table Data Source</source> <target state="translated">C#/VB Yapılacaklar Listesi Tablosu Veri Kaynağı</target> <note /> </trans-unit> <trans-unit id="Cancel"> <source>Cancel</source> <target state="translated">İptal</target> <note /> </trans-unit> <trans-unit id="Deselect_All"> <source>_Deselect All</source> <target state="translated">_Tüm Seçimleri Kaldır</target> <note /> </trans-unit> <trans-unit id="Extract_Interface"> <source>Extract Interface</source> <target state="translated">Arabirimi Ayıkla</target> <note /> </trans-unit> <trans-unit id="Generated_name_colon"> <source>Generated name:</source> <target state="translated">Oluşturulan ad:</target> <note /> </trans-unit> <trans-unit id="New_file_name_colon"> <source>New _file name:</source> <target state="translated">Yeni _dosya adı:</target> <note /> </trans-unit> <trans-unit id="New_interface_name_colon"> <source>New _interface name:</source> <target state="translated">Yeni _arabirim adı:</target> <note /> </trans-unit> <trans-unit id="OK"> <source>OK</source> <target state="translated">Tamam</target> <note /> </trans-unit> <trans-unit id="Select_All"> <source>_Select All</source> <target state="translated">_Tümünü Seç</target> <note /> </trans-unit> <trans-unit id="Select_public_members_to_form_interface"> <source>Select public _members to form interface</source> <target state="translated">Arabirim oluşturmak için ortak _üyeleri seçin</target> <note /> </trans-unit> <trans-unit id="Access_colon"> <source>_Access:</source> <target state="translated">_Erişim:</target> <note /> </trans-unit> <trans-unit id="Add_to_existing_file"> <source>Add to _existing file</source> <target state="translated">_Mevcut dosyaya ekle</target> <note /> </trans-unit> <trans-unit id="Change_Signature"> <source>Change Signature</source> <target state="translated">İmzayı Değiştir</target> <note /> </trans-unit> <trans-unit id="Create_new_file"> <source>_Create new file</source> <target state="translated">Yeni dosya _oluştur</target> <note /> </trans-unit> <trans-unit id="Default_"> <source>Default</source> <target state="translated">Varsayılan</target> <note /> </trans-unit> <trans-unit id="File_Name_colon"> <source>File Name:</source> <target state="translated">Dosya Adı:</target> <note /> </trans-unit> <trans-unit id="Generate_Type"> <source>Generate Type</source> <target state="translated">Tür Oluştur</target> <note /> </trans-unit> <trans-unit id="Kind_colon"> <source>_Kind:</source> <target state="translated">_Tür:</target> <note /> </trans-unit> <trans-unit id="Location_colon"> <source>Location:</source> <target state="translated">Konum:</target> <note /> </trans-unit> <trans-unit id="Modifier"> <source>Modifier</source> <target state="translated">Değiştirici</target> <note /> </trans-unit> <trans-unit id="Name_colon1"> <source>Name:</source> <target state="translated">Ad:</target> <note /> </trans-unit> <trans-unit id="Parameter"> <source>Parameter</source> <target state="translated">Parametre</target> <note /> </trans-unit> <trans-unit id="Parameters_colon2"> <source>Parameters:</source> <target state="translated">Parametreler:</target> <note /> </trans-unit> <trans-unit id="Preview_method_signature_colon"> <source>Preview method signature:</source> <target state="translated">Metot imzasını önizle:</target> <note /> </trans-unit> <trans-unit id="Preview_reference_changes"> <source>Preview reference changes</source> <target state="translated">Başvuru değişikliklerini önizle</target> <note /> </trans-unit> <trans-unit id="Project_colon"> <source>_Project:</source> <target state="translated">_Proje:</target> <note /> </trans-unit> <trans-unit id="Type"> <source>Type</source> <target state="translated">Tür</target> <note /> </trans-unit> <trans-unit id="Type_Details_colon"> <source>Type Details:</source> <target state="translated">Tür Ayrıntıları:</target> <note /> </trans-unit> <trans-unit id="Re_move"> <source>Re_move</source> <target state="translated">_Kaldır</target> <note /> </trans-unit> <trans-unit id="Restore"> <source>_Restore</source> <target state="translated">_Geri yükle</target> <note /> </trans-unit> <trans-unit id="More_about_0"> <source>More about {0}</source> <target state="translated">{0} hakkında daha fazla bilgi</target> <note /> </trans-unit> <trans-unit id="Navigation_must_be_performed_on_the_foreground_thread"> <source>Navigation must be performed on the foreground thread.</source> <target state="translated">Gezintinin, ön plan iş parçacığında gerçekleştirilmesi gerekir.</target> <note /> </trans-unit> <trans-unit id="bracket_plus_bracket"> <source>[+] </source> <target state="translated">[+] </target> <note /> </trans-unit> <trans-unit id="bracket_bracket"> <source>[-] </source> <target state="translated">[-] </target> <note /> </trans-unit> <trans-unit id="Reference_to_0_in_project_1"> <source>Reference to '{0}' in project '{1}'</source> <target state="translated">'{1}' adlı projedeki '{0}' öğesine yönelik başvuru</target> <note /> </trans-unit> <trans-unit id="Unknown1"> <source>&lt;Unknown&gt;</source> <target state="translated">&lt;Bilinmiyor&gt;</target> <note /> </trans-unit> <trans-unit id="Analyzer_reference_to_0_in_project_1"> <source>Analyzer reference to '{0}' in project '{1}'</source> <target state="translated">'{1}' projesindeki '{0}' öğesine yönelik çözümleyici başvurusu</target> <note /> </trans-unit> <trans-unit id="Project_reference_to_0_in_project_1"> <source>Project reference to '{0}' in project '{1}'</source> <target state="translated">'{1}' adlı projedeki '{0}' öğesine yönelik proje başvurusu</target> <note /> </trans-unit> <trans-unit id="AnalyzerDependencyConflict"> <source>AnalyzerDependencyConflict</source> <target state="translated">AnalyzerDependencyConflict</target> <note /> </trans-unit> <trans-unit id="Analyzer_assemblies_0_and_1_both_have_identity_2_but_different_contents_Only_one_will_be_loaded_and_analyzers_using_these_assemblies_may_not_run_correctly"> <source>Analyzer assemblies '{0}' and '{1}' both have identity '{2}' but different contents. Only one will be loaded and analyzers using these assemblies may not run correctly.</source> <target state="translated">'{0}' ve '{1}' çözümleyici bütünleştirilmiş kodlarının ikisi de '{2}' kimliğine sahip, ancak içerikleri farklı. Yalnızca biri yüklenecek; bu bütünleştirilmiş kodları kullanan çözümleyiciler düzgün şekilde çalışmayabilir.</target> <note /> </trans-unit> <trans-unit id="_0_references"> <source>{0} references</source> <target state="translated">{0} başvuru</target> <note /> </trans-unit> <trans-unit id="_1_reference"> <source>1 reference</source> <target state="translated">1 başvuru</target> <note /> </trans-unit> <trans-unit id="_0_encountered_an_error_and_has_been_disabled"> <source>'{0}' encountered an error and has been disabled.</source> <target state="translated">'{0}' bir hatayla karşılaştı ve devre dışı bırakıldı.</target> <note /> </trans-unit> <trans-unit id="Enable"> <source>Enable</source> <target state="translated">Etkinleştir</target> <note /> </trans-unit> <trans-unit id="Enable_and_ignore_future_errors"> <source>Enable and ignore future errors</source> <target state="translated">Etkinleştir ve gelecekteki hataları yoksay</target> <note /> </trans-unit> <trans-unit id="No_Changes"> <source>No Changes</source> <target state="translated">Değişiklik Yok</target> <note /> </trans-unit> <trans-unit id="Current_block"> <source>Current block</source> <target state="translated">Geçerli blok</target> <note /> </trans-unit> <trans-unit id="Determining_current_block"> <source>Determining current block.</source> <target state="translated">Geçerli blok belirleniyor.</target> <note /> </trans-unit> <trans-unit id="IntelliSense"> <source>IntelliSense</source> <target state="translated">IntelliSense</target> <note /> </trans-unit> <trans-unit id="CSharp_VB_Build_Table_Data_Source"> <source>C#/VB Build Table Data Source</source> <target state="translated">C#/VB Derleme Tablosu Veri Kaynağı</target> <note /> </trans-unit> <trans-unit id="MissingAnalyzerReference"> <source>MissingAnalyzerReference</source> <target state="translated">MissingAnalyzerReference</target> <note /> </trans-unit> <trans-unit id="Analyzer_assembly_0_depends_on_1_but_it_was_not_found_Analyzers_may_not_run_correctly_unless_the_missing_assembly_is_added_as_an_analyzer_reference_as_well"> <source>Analyzer assembly '{0}' depends on '{1}' but it was not found. Analyzers may not run correctly unless the missing assembly is added as an analyzer reference as well.</source> <target state="translated">Çözümleyici bütünleştirilmiş kodu '{0}', '{1}' öğesine bağımlı ancak bu öğe bulunamadı. Eksik bütünleştirilmiş kod da çözümleyici başvurusu olarak eklenmeden, çözümleyiciler düzgün şekilde çalışmayabilir.</target> <note /> </trans-unit> <trans-unit id="Suppress_diagnostics"> <source>Suppress diagnostics</source> <target state="translated">Tanılamayı gizle</target> <note /> </trans-unit> <trans-unit id="Computing_suppressions_fix"> <source>Computing suppressions fix...</source> <target state="translated">Gizlemeler düzeltmesi hesaplanıyor...</target> <note /> </trans-unit> <trans-unit id="Applying_suppressions_fix"> <source>Applying suppressions fix...</source> <target state="translated">Gizlemeler düzeltmesi uygulanıyor...</target> <note /> </trans-unit> <trans-unit id="Remove_suppressions"> <source>Remove suppressions</source> <target state="translated">Gizlemeleri kaldır</target> <note /> </trans-unit> <trans-unit id="Computing_remove_suppressions_fix"> <source>Computing remove suppressions fix...</source> <target state="translated">Gizlemeleri kaldırma düzeltmesi hesaplanıyor...</target> <note /> </trans-unit> <trans-unit id="Applying_remove_suppressions_fix"> <source>Applying remove suppressions fix...</source> <target state="translated">Gizlemeleri kaldırma düzeltmesi uygulanıyor...</target> <note /> </trans-unit> <trans-unit id="This_workspace_only_supports_opening_documents_on_the_UI_thread"> <source>This workspace only supports opening documents on the UI thread.</source> <target state="translated">Bu çalışma alanı, belgelerin yalnızca kullanıcı arabirimi iş parçacığında açılmasını destekler.</target> <note /> </trans-unit> <trans-unit id="This_workspace_does_not_support_updating_Visual_Basic_parse_options"> <source>This workspace does not support updating Visual Basic parse options.</source> <target state="translated">Bu çalışma alanı Visual Basic ayrıştırma seçeneklerinin güncelleştirilmesini desteklemiyor.</target> <note /> </trans-unit> <trans-unit id="Synchronize_0"> <source>Synchronize {0}</source> <target state="translated">{0} ile eşitle</target> <note /> </trans-unit> <trans-unit id="Synchronizing_with_0"> <source>Synchronizing with {0}...</source> <target state="translated">{0} ile eşitleniyor...</target> <note /> </trans-unit> <trans-unit id="Visual_Studio_has_suspended_some_advanced_features_to_improve_performance"> <source>Visual Studio has suspended some advanced features to improve performance.</source> <target state="translated">Visual Studio, performansı artırmak için bazı gelişmiş özellikleri askıya aldı.</target> <note /> </trans-unit> <trans-unit id="Installing_0"> <source>Installing '{0}'</source> <target state="translated">'{0}' yükleniyor</target> <note /> </trans-unit> <trans-unit id="Installing_0_completed"> <source>Installing '{0}' completed</source> <target state="translated">'{0}' yüklendi</target> <note /> </trans-unit> <trans-unit id="Package_install_failed_colon_0"> <source>Package install failed: {0}</source> <target state="translated">Paket yüklenemedi: {0}</target> <note /> </trans-unit> <trans-unit id="Unknown2"> <source>&lt;Unknown&gt;</source> <target state="translated">&lt;Bilinmiyor&gt;</target> <note /> </trans-unit> <trans-unit id="No"> <source>No</source> <target state="translated">Hayır</target> <note /> </trans-unit> <trans-unit id="Yes"> <source>Yes</source> <target state="translated">Evet</target> <note /> </trans-unit> <trans-unit id="Choose_a_Symbol_Specification_and_a_Naming_Style"> <source>Choose a Symbol Specification and a Naming Style.</source> <target state="translated">Sembol Belirtimi ve Adlandırma Stili seçin.</target> <note /> </trans-unit> <trans-unit id="Enter_a_title_for_this_Naming_Rule"> <source>Enter a title for this Naming Rule.</source> <target state="translated">Bu Adlandırma Kuralı için bir başlık girin.</target> <note /> </trans-unit> <trans-unit id="Enter_a_title_for_this_Naming_Style"> <source>Enter a title for this Naming Style.</source> <target state="translated">Bu Adlandırma Stili için bir başlık girin.</target> <note /> </trans-unit> <trans-unit id="Enter_a_title_for_this_Symbol_Specification"> <source>Enter a title for this Symbol Specification.</source> <target state="translated">Bu Sembol Belirtimi için bir başlık girin.</target> <note /> </trans-unit> <trans-unit id="Accessibilities_can_match_any"> <source>Accessibilities (can match any)</source> <target state="translated">Erişim düzeyleri (herhangi biriyle eşleşebilir)</target> <note /> </trans-unit> <trans-unit id="Capitalization_colon"> <source>Capitalization:</source> <target state="translated">Büyük Harfe Çevirme:</target> <note /> </trans-unit> <trans-unit id="all_lower"> <source>all lower</source> <target state="translated">tümü küçük harf</target> <note /> </trans-unit> <trans-unit id="ALL_UPPER"> <source>ALL UPPER</source> <target state="translated">TÜMÜ BÜYÜK HARF</target> <note /> </trans-unit> <trans-unit id="camel_Case_Name"> <source>camel Case Name</source> <target state="translated">orta Harfleri Büyük Ad</target> <note /> </trans-unit> <trans-unit id="First_word_upper"> <source>First word upper</source> <target state="translated">İlk sözcük büyük harfle</target> <note /> </trans-unit> <trans-unit id="Pascal_Case_Name"> <source>Pascal Case Name</source> <target state="translated">Baş Harfleri Büyük Ad</target> <note /> </trans-unit> <trans-unit id="Severity_colon"> <source>Severity:</source> <target state="translated">Önem Derecesi:</target> <note /> </trans-unit> <trans-unit id="Modifiers_must_match_all"> <source>Modifiers (must match all)</source> <target state="translated">Değiştiriciler (tümüyle eşleşmelidir)</target> <note /> </trans-unit> <trans-unit id="Name_colon2"> <source>Name:</source> <target state="translated">Ad:</target> <note /> </trans-unit> <trans-unit id="Naming_Rule"> <source>Naming Rule</source> <target state="translated">Adlandırma Kuralı</target> <note /> </trans-unit> <trans-unit id="Naming_Style"> <source>Naming Style</source> <target state="translated">Adlandırma Stili</target> <note /> </trans-unit> <trans-unit id="Naming_Style_colon"> <source>Naming Style:</source> <target state="translated">Adlandırma Stili:</target> <note /> </trans-unit> <trans-unit id="Naming_Rules_allow_you_to_define_how_particular_sets_of_symbols_should_be_named_and_how_incorrectly_named_symbols_should_be_handled"> <source>Naming Rules allow you to define how particular sets of symbols should be named and how incorrectly-named symbols should be handled.</source> <target state="translated">Adlandırma Kuralları, belirli sembol kümelerinin nasıl adlandırılması gerektiğini ve yanlış adlandırılan sembollerin nasıl işlenmesi gerektiğini tanımlamanızı sağlar.</target> <note /> </trans-unit> <trans-unit id="The_first_matching_top_level_Naming_Rule_is_used_by_default_when_naming_a_symbol_while_any_special_cases_are_handled_by_a_matching_child_rule"> <source>The first matching top-level Naming Rule is used by default when naming a symbol, while any special cases are handled by a matching child rule.</source> <target state="translated">Sembol adlandırılırken varsayılan olarak, eşleşen ilk üst düzey Adlandırma Kuralı kullanılır. Özel durumlar ise eşleşen bir alt kural tarafından işlenir.</target> <note /> </trans-unit> <trans-unit id="Naming_Style_Title_colon"> <source>Naming Style Title:</source> <target state="translated">Adlandırma Stili Başlığı:</target> <note /> </trans-unit> <trans-unit id="Parent_Rule_colon"> <source>Parent Rule:</source> <target state="translated">Üst Kural:</target> <note /> </trans-unit> <trans-unit id="Required_Prefix_colon"> <source>Required Prefix:</source> <target state="translated">Gerekli Ön Ek:</target> <note /> </trans-unit> <trans-unit id="Required_Suffix_colon"> <source>Required Suffix:</source> <target state="translated">Gerekli Sonek:</target> <note /> </trans-unit> <trans-unit id="Sample_Identifier_colon"> <source>Sample Identifier:</source> <target state="translated">Örnek Tanımlayıcı:</target> <note /> </trans-unit> <trans-unit id="Symbol_Kinds_can_match_any"> <source>Symbol Kinds (can match any)</source> <target state="translated">Sembol Türleri (tümüyle eşleşebilir)</target> <note /> </trans-unit> <trans-unit id="Symbol_Specification"> <source>Symbol Specification</source> <target state="translated">Sembol Belirtimi</target> <note /> </trans-unit> <trans-unit id="Symbol_Specification_colon"> <source>Symbol Specification:</source> <target state="translated">Sembol Belirtimi:</target> <note /> </trans-unit> <trans-unit id="Symbol_Specification_Title_colon"> <source>Symbol Specification Title:</source> <target state="translated">Sembol Belirtimi Başlığı:</target> <note /> </trans-unit> <trans-unit id="Word_Separator_colon"> <source>Word Separator:</source> <target state="translated">Sözcük Ayırıcı:</target> <note /> </trans-unit> <trans-unit id="example"> <source>example</source> <target state="translated">örnek</target> <note>IdentifierWord_Example and IdentifierWord_Identifier are combined (with prefixes, suffixes, and word separators) into an example identifier name in the NamingStyle UI.</note> </trans-unit> <trans-unit id="identifier"> <source>identifier</source> <target state="translated">tanımlayıcı</target> <note>IdentifierWord_Example and IdentifierWord_Identifier are combined (with prefixes, suffixes, and word separators) into an example identifier name in the NamingStyle UI.</note> </trans-unit> <trans-unit id="Install_0"> <source>Install '{0}'</source> <target state="translated">'{0}' öğesini yükle</target> <note /> </trans-unit> <trans-unit id="Uninstalling_0"> <source>Uninstalling '{0}'</source> <target state="translated">'{0}' kaldırılıyor</target> <note /> </trans-unit> <trans-unit id="Uninstalling_0_completed"> <source>Uninstalling '{0}' completed</source> <target state="translated">'{0}' kaldırıldı</target> <note /> </trans-unit> <trans-unit id="Uninstall_0"> <source>Uninstall '{0}'</source> <target state="translated">'{0}' öğesini kaldır</target> <note /> </trans-unit> <trans-unit id="Package_uninstall_failed_colon_0"> <source>Package uninstall failed: {0}</source> <target state="translated">Paket kaldırılamadı: {0}</target> <note /> </trans-unit> <trans-unit id="Error_encountered_while_loading_the_project_Some_project_features_such_as_full_solution_analysis_for_the_failed_project_and_projects_that_depend_on_it_have_been_disabled"> <source>Error encountered while loading the project. Some project features, such as full solution analysis for the failed project and projects that depend on it, have been disabled.</source> <target state="translated">Proje yüklenirken hatayla karşılaşıldı. Başarısız olan proje ve buna bağımlı projeler için, tam çözüm denetimi gibi bazı proje özellikleri devre dışı bırakıldı.</target> <note /> </trans-unit> <trans-unit id="Project_loading_failed"> <source>Project loading failed.</source> <target state="translated">Proje yüklenemedi.</target> <note /> </trans-unit> <trans-unit id="To_see_what_caused_the_issue_please_try_below_1_Close_Visual_Studio_long_paragraph_follows"> <source>To see what caused the issue, please try below. 1. Close Visual Studio 2. Open a Visual Studio Developer Command Prompt 3. Set environment variable “TraceDesignTime” to true (set TraceDesignTime=true) 4. Delete .vs directory/.suo file 5. Restart VS from the command prompt you set the environment variable (devenv) 6. Open the solution 7. Check '{0}' and look for the failed tasks (FAILED)</source> <target state="translated">Sorunun neden kaynaklandığını görmek için lütfen aşağıdaki çözümleri deneyin. 1. Visual Studio'yu kapatın 2. Visual Studio Geliştirici Komut İstemi'ni açın 3. “TraceDesignTime” ortam değişkenini true olarak ayarlayın (set TraceDesignTime=true) 4. .vs dizini/.suo dosyasını silin 5. Visual Studio'yu, ortam değişkenini ayarladığınız komut isteminden yeniden başlatın (devenv) 6. Çözümü açın 7. '{0}' konumuna giderek başarısız olan görevlere bakın (FAILED)</target> <note /> </trans-unit> <trans-unit id="Additional_information_colon"> <source>Additional information:</source> <target state="translated">Ek bilgi:</target> <note /> </trans-unit> <trans-unit id="Installing_0_failed_Additional_information_colon_1"> <source>Installing '{0}' failed. Additional information: {1}</source> <target state="translated">'{0}' yüklenemedi. Ek bilgiler: {1}</target> <note /> </trans-unit> <trans-unit id="Uninstalling_0_failed_Additional_information_colon_1"> <source>Uninstalling '{0}' failed. Additional information: {1}</source> <target state="translated">'{0}' kaldırılamadı. Ek bilgiler: {1}</target> <note /> </trans-unit> <trans-unit id="Move_0_below_1"> <source>Move {0} below {1}</source> <target state="translated">{0} öğesini {1} öğesinin altına taşı</target> <note>{0} and {1} are parameter descriptions</note> </trans-unit> <trans-unit id="Move_0_above_1"> <source>Move {0} above {1}</source> <target state="translated">{0} öğesini {1} öğesinin üstüne taşı</target> <note>{0} and {1} are parameter descriptions</note> </trans-unit> <trans-unit id="Remove_0"> <source>Remove {0}</source> <target state="translated">{0} öğesini kaldır</target> <note>{0} is a parameter description</note> </trans-unit> <trans-unit id="Restore_0"> <source>Restore {0}</source> <target state="translated">{0} öğesini geri yükle</target> <note>{0} is a parameter description</note> </trans-unit> <trans-unit id="Re_enable"> <source>Re-enable</source> <target state="translated">Yeniden etkinleştir</target> <note /> </trans-unit> <trans-unit id="Learn_more"> <source>Learn more</source> <target state="translated">Daha fazla bilgi</target> <note /> </trans-unit> <trans-unit id="Prefer_framework_type"> <source>Prefer framework type</source> <target state="translated">Çerçeve türünü tercih et</target> <note /> </trans-unit> <trans-unit id="Prefer_predefined_type"> <source>Prefer predefined type</source> <target state="translated">Önceden tanımlanmış türü tercih et</target> <note /> </trans-unit> <trans-unit id="Copy_to_Clipboard"> <source>Copy to Clipboard</source> <target state="translated">Panoya Kopyala</target> <note /> </trans-unit> <trans-unit id="Close"> <source>Close</source> <target state="translated">Kapat</target> <note /> </trans-unit> <trans-unit id="Unknown_parameters"> <source>&lt;Unknown Parameters&gt;</source> <target state="translated">&lt;Bilinmeyen Parametreler&gt;</target> <note /> </trans-unit> <trans-unit id="End_of_inner_exception_stack"> <source>--- End of inner exception stack trace ---</source> <target state="translated">--- İç özel durum yığın izlemesi sonu ---</target> <note /> </trans-unit> <trans-unit id="For_locals_parameters_and_members"> <source>For locals, parameters and members</source> <target state="translated">Yerel öğeler, parametreler ve üyeler için</target> <note /> </trans-unit> <trans-unit id="For_member_access_expressions"> <source>For member access expressions</source> <target state="translated">Üye erişimi ifadeleri için</target> <note /> </trans-unit> <trans-unit id="Prefer_object_initializer"> <source>Prefer object initializer</source> <target state="translated">Nesne başlatıcısını tercih et</target> <note /> </trans-unit> <trans-unit id="Expression_preferences_colon"> <source>Expression preferences:</source> <target state="translated">İfade tercihleri:</target> <note /> </trans-unit> <trans-unit id="Block_Structure_Guides"> <source>Block Structure Guides</source> <target state="translated">Blok Yapısı Kılavuzları</target> <note /> </trans-unit> <trans-unit id="Outlining"> <source>Outlining</source> <target state="translated">Ana Hat</target> <note /> </trans-unit> <trans-unit id="Show_guides_for_code_level_constructs"> <source>Show guides for code level constructs</source> <target state="translated">Kod düzeyinde yapılar için kılavuzları göster</target> <note /> </trans-unit> <trans-unit id="Show_guides_for_comments_and_preprocessor_regions"> <source>Show guides for comments and preprocessor regions</source> <target state="translated">Açıklamalar ve ön işlemci bölgeleri için kılavuzları göster</target> <note /> </trans-unit> <trans-unit id="Show_guides_for_declaration_level_constructs"> <source>Show guides for declaration level constructs</source> <target state="translated">Bildirim düzeyinde yapılar için kılavuzları göster</target> <note /> </trans-unit> <trans-unit id="Show_outlining_for_code_level_constructs"> <source>Show outlining for code level constructs</source> <target state="translated">Kod düzeyinde yapılar için ana hattı göster</target> <note /> </trans-unit> <trans-unit id="Show_outlining_for_comments_and_preprocessor_regions"> <source>Show outlining for comments and preprocessor regions</source> <target state="translated">Açıklamalar ve ön işlemci bölgeleri için ana hattı göster</target> <note /> </trans-unit> <trans-unit id="Show_outlining_for_declaration_level_constructs"> <source>Show outlining for declaration level constructs</source> <target state="translated">Bildirim düzeyinde yapılar için ana hattı göster</target> <note /> </trans-unit> <trans-unit id="Variable_preferences_colon"> <source>Variable preferences:</source> <target state="translated">Değişken tercihleri:</target> <note /> </trans-unit> <trans-unit id="Prefer_inlined_variable_declaration"> <source>Prefer inlined variable declaration</source> <target state="translated">Satır içine alınmış değişken bildirimini tercih et</target> <note /> </trans-unit> <trans-unit id="Use_expression_body_for_methods"> <source>Use expression body for methods</source> <target state="translated">Metotlar için ifade gövdesi kullan</target> <note /> </trans-unit> <trans-unit id="Code_block_preferences_colon"> <source>Code block preferences:</source> <target state="translated">Kod bloğu tercihleri:</target> <note /> </trans-unit> <trans-unit id="Use_expression_body_for_accessors"> <source>Use expression body for accessors</source> <target state="translated">Erişimciler için ifade gövdesi kullan</target> <note /> </trans-unit> <trans-unit id="Use_expression_body_for_constructors"> <source>Use expression body for constructors</source> <target state="translated">Oluşturucular için ifade gövdesi kullan</target> <note /> </trans-unit> <trans-unit id="Use_expression_body_for_indexers"> <source>Use expression body for indexers</source> <target state="translated">Dizin oluşturucular için ifade gövdesi kullan</target> <note /> </trans-unit> <trans-unit id="Use_expression_body_for_operators"> <source>Use expression body for operators</source> <target state="translated">İşleçler için ifade gövdesi kullan</target> <note /> </trans-unit> <trans-unit id="Use_expression_body_for_properties"> <source>Use expression body for properties</source> <target state="translated">Özellikler için ifade gövdesi kullan</target> <note /> </trans-unit> <trans-unit id="Some_naming_rules_are_incomplete_Please_complete_or_remove_them"> <source>Some naming rules are incomplete. Please complete or remove them.</source> <target state="translated">Bazı adlandırma kuralları eksik. Lütfen bunları tamamlayın veya kaldırın.</target> <note /> </trans-unit> <trans-unit id="Manage_specifications"> <source>Manage specifications</source> <target state="translated">Belirtimleri yönet</target> <note /> </trans-unit> <trans-unit id="Reorder"> <source>Reorder</source> <target state="translated">Yeniden sırala</target> <note /> </trans-unit> <trans-unit id="Severity"> <source>Severity</source> <target state="translated">Önem Derecesi</target> <note /> </trans-unit> <trans-unit id="Specification"> <source>Specification</source> <target state="translated">Belirtim</target> <note /> </trans-unit> <trans-unit id="Required_Style"> <source>Required Style</source> <target state="translated">Gerekli Stil</target> <note /> </trans-unit> <trans-unit id="This_item_cannot_be_deleted_because_it_is_used_by_an_existing_Naming_Rule"> <source>This item cannot be deleted because it is used by an existing Naming Rule.</source> <target state="translated">Öğe, mevcut bir Adlandırma Kuralı tarafından kullanıldığından silinemiyor.</target> <note /> </trans-unit> <trans-unit id="Prefer_collection_initializer"> <source>Prefer collection initializer</source> <target state="translated">Koleksiyon başlatıcısını tercih et</target> <note /> </trans-unit> <trans-unit id="Prefer_coalesce_expression"> <source>Prefer coalesce expression</source> <target state="translated">Birleştirme ifadesini tercih et</target> <note /> </trans-unit> <trans-unit id="Collapse_regions_when_collapsing_to_definitions"> <source>Collapse #regions when collapsing to definitions</source> <target state="translated">Tanımlara daraltırken #region öğelerini daralt</target> <note /> </trans-unit> <trans-unit id="Prefer_null_propagation"> <source>Prefer null propagation</source> <target state="translated">Null yaymayı tercih et</target> <note /> </trans-unit> <trans-unit id="Prefer_explicit_tuple_name"> <source>Prefer explicit tuple name</source> <target state="translated">Açık demet adını tercih et</target> <note /> </trans-unit> <trans-unit id="Description"> <source>Description</source> <target state="translated">Açıklama</target> <note /> </trans-unit> <trans-unit id="Preference"> <source>Preference</source> <target state="translated">Tercih</target> <note /> </trans-unit> <trans-unit id="Implement_Interface_or_Abstract_Class"> <source>Implement Interface or Abstract Class</source> <target state="translated">Interface veya Abstract Sınıfı Uygula</target> <note /> </trans-unit> <trans-unit id="For_a_given_symbol_only_the_topmost_rule_with_a_matching_Specification_will_be_applied_Violation_of_that_rules_Required_Style_will_be_reported_at_the_chosen_Severity_level"> <source>For a given symbol, only the topmost rule with a matching 'Specification' will be applied. Violation of that rule's 'Required Style' will be reported at the chosen 'Severity' level.</source> <target state="translated">Sağlanan bir sembolde yalnızca, eşleşen bir 'Belirtim' içeren kurallardan en üstte bulunanı uygulanır. Bu kural için 'Gerekli Stil' ihlal edilirse, bu durum seçilen 'Önem Derecesi' düzeyinde bildirilir.</target> <note /> </trans-unit> <trans-unit id="at_the_end"> <source>at the end</source> <target state="translated">sonda</target> <note /> </trans-unit> <trans-unit id="When_inserting_properties_events_and_methods_place_them"> <source>When inserting properties, events and methods, place them:</source> <target state="translated">Özellik, olay ve metot eklerken, bunları şuraya yerleştir:</target> <note /> </trans-unit> <trans-unit id="with_other_members_of_the_same_kind"> <source>with other members of the same kind</source> <target state="translated">aynı türden başka üyelerle birlikte</target> <note /> </trans-unit> <trans-unit id="Prefer_braces"> <source>Prefer braces</source> <target state="translated">Küme ayraçlarını tercih et</target> <note /> </trans-unit> <trans-unit id="Over_colon"> <source>Over:</source> <target state="translated">Bunun yerine:</target> <note /> </trans-unit> <trans-unit id="Prefer_colon"> <source>Prefer:</source> <target state="translated">Tercih edilen:</target> <note /> </trans-unit> <trans-unit id="or"> <source>or</source> <target state="translated">veya</target> <note /> </trans-unit> <trans-unit id="built_in_types"> <source>built-in types</source> <target state="translated">yerleşik türler</target> <note /> </trans-unit> <trans-unit id="everywhere_else"> <source>everywhere else</source> <target state="translated">diğer yerlerde</target> <note /> </trans-unit> <trans-unit id="type_is_apparent_from_assignment_expression"> <source>type is apparent from assignment expression</source> <target state="translated">tür, atama ifadesinden görünür</target> <note /> </trans-unit> <trans-unit id="Move_down"> <source>Move down</source> <target state="translated">Aşağı taşı</target> <note /> </trans-unit> <trans-unit id="Move_up"> <source>Move up</source> <target state="translated">Yukarı taşı</target> <note /> </trans-unit> <trans-unit id="Remove"> <source>Remove</source> <target state="translated">Kaldır</target> <note /> </trans-unit> <trans-unit id="Pick_members"> <source>Pick members</source> <target state="translated">Üyeleri seçin</target> <note /> </trans-unit> <trans-unit id="Unfortunately_a_process_used_by_Visual_Studio_has_encountered_an_unrecoverable_error_We_recommend_saving_your_work_and_then_closing_and_restarting_Visual_Studio"> <source>Unfortunately, a process used by Visual Studio has encountered an unrecoverable error. We recommend saving your work, and then closing and restarting Visual Studio.</source> <target state="translated">Visual Studio tarafından kullanılan bir işlemde, kurtarılamayan bir hatayla karşılaşıldı. Çalışmanızı kaydettikten sonra Visual Studio'yu kapatıp yeniden başlatmanız önerilir.</target> <note /> </trans-unit> <trans-unit id="Add_a_symbol_specification"> <source>Add a symbol specification</source> <target state="translated">Sembol belirtimi ekle</target> <note /> </trans-unit> <trans-unit id="Remove_symbol_specification"> <source>Remove symbol specification</source> <target state="translated">Sembol belirtimini kaldır</target> <note /> </trans-unit> <trans-unit id="Add_item"> <source>Add item</source> <target state="translated">Öğe ekle</target> <note /> </trans-unit> <trans-unit id="Edit_item"> <source>Edit item</source> <target state="translated">Öğeyi düzenle</target> <note /> </trans-unit> <trans-unit id="Remove_item"> <source>Remove item</source> <target state="translated">Öğeyi kaldır</target> <note /> </trans-unit> <trans-unit id="Add_a_naming_rule"> <source>Add a naming rule</source> <target state="translated">Adlandırma kuralı ekle</target> <note /> </trans-unit> <trans-unit id="Remove_naming_rule"> <source>Remove naming rule</source> <target state="translated">Adlandırma kuralını kaldır</target> <note /> </trans-unit> <trans-unit id="VisualStudioWorkspace_TryApplyChanges_cannot_be_called_from_a_background_thread"> <source>VisualStudioWorkspace.TryApplyChanges cannot be called from a background thread.</source> <target state="translated">VisualStudioWorkspace.TryApplyChanges bir arka plan iş parçacığından çağırılamaz.</target> <note /> </trans-unit> <trans-unit id="prefer_throwing_properties"> <source>prefer throwing properties</source> <target state="translated">özel durum oluşturan özellikleri tercih et</target> <note /> </trans-unit> <trans-unit id="When_generating_properties"> <source>When generating properties:</source> <target state="translated">Özellikler oluşturulurken:</target> <note /> </trans-unit> <trans-unit id="Options"> <source>Options</source> <target state="translated">Seçenekler</target> <note /> </trans-unit> <trans-unit id="Never_show_this_again"> <source>Never show this again</source> <target state="translated">Bunu bir daha gösterme</target> <note /> </trans-unit> <trans-unit id="Prefer_simple_default_expression"> <source>Prefer simple 'default' expression</source> <target state="translated">Basit 'default' ifadesini tercih et</target> <note /> </trans-unit> <trans-unit id="Prefer_inferred_tuple_names"> <source>Prefer inferred tuple element names</source> <target state="translated">Gösterilen demet öğesi adlarını tercih et</target> <note /> </trans-unit> <trans-unit id="Prefer_inferred_anonymous_type_member_names"> <source>Prefer inferred anonymous type member names</source> <target state="translated">Gösterilen anonim tip üye adlarını tercih et</target> <note /> </trans-unit> <trans-unit id="Preview_pane"> <source>Preview pane</source> <target state="translated">Önizleme bölmesi</target> <note /> </trans-unit> <trans-unit id="Analysis"> <source>Analysis</source> <target state="translated">Analiz</target> <note /> </trans-unit> <trans-unit id="Fade_out_unreachable_code"> <source>Fade out unreachable code</source> <target state="translated">Erişilemeyen kodu soluklaştır</target> <note /> </trans-unit> <trans-unit id="Fading"> <source>Fading</source> <target state="translated">Soluklaştırılıyor</target> <note /> </trans-unit> <trans-unit id="Prefer_local_function_over_anonymous_function"> <source>Prefer local function over anonymous function</source> <target state="translated">Anonim işlevler yerine yerel işlevleri tercih et</target> <note /> </trans-unit> <trans-unit id="Prefer_deconstructed_variable_declaration"> <source>Prefer deconstructed variable declaration</source> <target state="translated">Ayrıştırılmış değişken bildirimini tercih et</target> <note /> </trans-unit> <trans-unit id="External_reference_found"> <source>External reference found</source> <target state="translated">Dış başvuru bulundu</target> <note /> </trans-unit> <trans-unit id="No_references_found_to_0"> <source>No references found to '{0}'</source> <target state="translated">'{0}' için başvuru bulunamadı</target> <note /> </trans-unit> <trans-unit id="Search_found_no_results"> <source>Search found no results</source> <target state="translated">Aramada sonuç bulunamadı</target> <note /> </trans-unit> <trans-unit id="analyzer_Prefer_auto_properties"> <source>Prefer auto properties</source> <target state="translated">Otomatik özellikleri tercih et</target> <note /> </trans-unit> <trans-unit id="codegen_prefer_auto_properties"> <source>prefer auto properties</source> <target state="translated">otomatik özellikleri tercih et</target> <note /> </trans-unit> <trans-unit id="ModuleHasBeenUnloaded"> <source>Module has been unloaded.</source> <target state="translated">Modül kaldırıldı.</target> <note /> </trans-unit> <trans-unit id="Enable_navigation_to_decompiled_sources"> <source>Enable navigation to decompiled sources</source> <target state="needs-review-translation">Derlemesi ayrılan kaynaklar için gezintiyi etkinleştirme (deneysel)</target> <note /> </trans-unit> <trans-unit id="Code_style_header_use_editor_config"> <source>Your .editorconfig file might override the local settings configured on this page which only apply to your machine. To configure these settings to travel with your solution use EditorConfig files. More info</source> <target state="translated">.editorconfig dosyanız, bu sayfada yapılandırılan ve yalnızca makinenizde uygulanan yerel ayarları geçersiz kılabilir. Bu ayarları çözümünüzle birlikte hareket etmek üzere yapılandırmak için EditorConfig dosyalarını kullanın. Daha fazla bilgi</target> <note /> </trans-unit> <trans-unit id="Sync_Class_View"> <source>Sync Class View</source> <target state="translated">Sınıf Görünümünü Eşitle</target> <note /> </trans-unit> <trans-unit id="Analyzing_0"> <source>Analyzing '{0}'</source> <target state="translated">'{0}' Analiz Ediliyor</target> <note /> </trans-unit> <trans-unit id="Manage_naming_styles"> <source>Manage naming styles</source> <target state="translated">Adlandırma stillerini yönetme</target> <note /> </trans-unit> <trans-unit id="Prefer_conditional_expression_over_if_with_assignments"> <source>Prefer conditional expression over 'if' with assignments</source> <target state="translated">Atamalarda 'if' yerine koşullu deyim tercih et</target> <note /> </trans-unit> <trans-unit id="Prefer_conditional_expression_over_if_with_returns"> <source>Prefer conditional expression over 'if' with returns</source> <target state="translated">Dönüşlerde 'if' yerine koşullu deyim tercih et</target> <note /> </trans-unit> </body> </file> </xliff>
-1
dotnet/roslyn
55,430
Fix LSP semantic tokens algorithm
This PR primarily accomplishes two tasks: 1) Overhauls the existing LSP semantic tokens edits processing algorithm to align with [Razor's](https://github.com/dotnet/aspnetcore-tooling/blob/main/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/Semantic/Services/SemanticTokensEditsDiffer.cs) (shoutout to Ryan and the rest of the Razor team for writing the original 😄). The main change here is going from calculating edits per token (i.e. five ints) to per int. The updated algorithm is much more efficient than our previous algorithm, and returns less edits back to the LSP client. 2) The interpretation of Roslyn's LongestCommonSubstring algorithm, which we use to calculate raw edits, was missing a critical piece. Namely, for insertions, we need to keep track of _where_ we should be inserting into the original token set. We don't keep track of this in the existing implementation, resulting in bugs such as #54671. Resolves #54671
allisonchou
2021-08-05T06:06:43Z
2021-08-06T23:44:44Z
b9200d03a76c74d404040d44b9bbe12b1d0a8ef2
f300a818940ea1acef66c946cfa83756729d5e59
Fix LSP semantic tokens algorithm. This PR primarily accomplishes two tasks: 1) Overhauls the existing LSP semantic tokens edits processing algorithm to align with [Razor's](https://github.com/dotnet/aspnetcore-tooling/blob/main/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/Semantic/Services/SemanticTokensEditsDiffer.cs) (shoutout to Ryan and the rest of the Razor team for writing the original 😄). The main change here is going from calculating edits per token (i.e. five ints) to per int. The updated algorithm is much more efficient than our previous algorithm, and returns less edits back to the LSP client. 2) The interpretation of Roslyn's LongestCommonSubstring algorithm, which we use to calculate raw edits, was missing a critical piece. Namely, for insertions, we need to keep track of _where_ we should be inserting into the original token set. We don't keep track of this in the existing implementation, resulting in bugs such as #54671. Resolves #54671
./src/VisualStudio/Core/Def/Implementation/TableDataSource/AbstractTableEntriesSource.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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; using Microsoft.VisualStudio.Text; namespace Microsoft.VisualStudio.LanguageServices.Implementation.TableDataSource { /// <summary> /// Provide information to create a ITableEntriesSnapshot /// /// This works on data that belong to logically same source of items such as one particular analyzer or todo list analyzer. /// </summary> internal abstract class AbstractTableEntriesSource<TItem> where TItem : TableItem { public abstract object Key { get; } public abstract ImmutableArray<TItem> GetItems(); public abstract ImmutableArray<ITrackingPoint> GetTrackingPoints(ImmutableArray<TItem> items); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Immutable; using Microsoft.CodeAnalysis; using Microsoft.VisualStudio.Text; namespace Microsoft.VisualStudio.LanguageServices.Implementation.TableDataSource { /// <summary> /// Provide information to create a ITableEntriesSnapshot /// /// This works on data that belong to logically same source of items such as one particular analyzer or todo list analyzer. /// </summary> internal abstract class AbstractTableEntriesSource<TItem> where TItem : TableItem { public abstract object Key { get; } public abstract ImmutableArray<TItem> GetItems(); public abstract ImmutableArray<ITrackingPoint> GetTrackingPoints(ImmutableArray<TItem> items); } }
-1
dotnet/roslyn
55,430
Fix LSP semantic tokens algorithm
This PR primarily accomplishes two tasks: 1) Overhauls the existing LSP semantic tokens edits processing algorithm to align with [Razor's](https://github.com/dotnet/aspnetcore-tooling/blob/main/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/Semantic/Services/SemanticTokensEditsDiffer.cs) (shoutout to Ryan and the rest of the Razor team for writing the original 😄). The main change here is going from calculating edits per token (i.e. five ints) to per int. The updated algorithm is much more efficient than our previous algorithm, and returns less edits back to the LSP client. 2) The interpretation of Roslyn's LongestCommonSubstring algorithm, which we use to calculate raw edits, was missing a critical piece. Namely, for insertions, we need to keep track of _where_ we should be inserting into the original token set. We don't keep track of this in the existing implementation, resulting in bugs such as #54671. Resolves #54671
allisonchou
2021-08-05T06:06:43Z
2021-08-06T23:44:44Z
b9200d03a76c74d404040d44b9bbe12b1d0a8ef2
f300a818940ea1acef66c946cfa83756729d5e59
Fix LSP semantic tokens algorithm. This PR primarily accomplishes two tasks: 1) Overhauls the existing LSP semantic tokens edits processing algorithm to align with [Razor's](https://github.com/dotnet/aspnetcore-tooling/blob/main/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/Semantic/Services/SemanticTokensEditsDiffer.cs) (shoutout to Ryan and the rest of the Razor team for writing the original 😄). The main change here is going from calculating edits per token (i.e. five ints) to per int. The updated algorithm is much more efficient than our previous algorithm, and returns less edits back to the LSP client. 2) The interpretation of Roslyn's LongestCommonSubstring algorithm, which we use to calculate raw edits, was missing a critical piece. Namely, for insertions, we need to keep track of _where_ we should be inserting into the original token set. We don't keep track of this in the existing implementation, resulting in bugs such as #54671. Resolves #54671
./src/Compilers/CSharp/Portable/Emitter/Model/GenericNestedTypeInstanceReference.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.Emit; namespace Microsoft.CodeAnalysis.CSharp.Emit { /// <summary> /// Represents a reference to a generic type instantiation that is nested in a non-generic type. /// e.g. A.B{int} /// </summary> internal sealed class GenericNestedTypeInstanceReference : GenericTypeInstanceReference, Cci.INestedTypeReference { public GenericNestedTypeInstanceReference(NamedTypeSymbol underlyingNamedType) : base(underlyingNamedType) { } Cci.ITypeReference Cci.ITypeMemberReference.GetContainingType(EmitContext context) { return ((PEModuleBuilder)context.Module).Translate(UnderlyingNamedType.ContainingType, syntaxNodeOpt: (CSharpSyntaxNode)context.SyntaxNode, diagnostics: context.Diagnostics); } public override Cci.IGenericTypeInstanceReference AsGenericTypeInstanceReference { get { return this; } } public override Cci.INamespaceTypeReference AsNamespaceTypeReference { get { return null; } } public override Cci.INestedTypeReference AsNestedTypeReference { get { return this; } } public override Cci.ISpecializedNestedTypeReference AsSpecializedNestedTypeReference { 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 Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.Emit; namespace Microsoft.CodeAnalysis.CSharp.Emit { /// <summary> /// Represents a reference to a generic type instantiation that is nested in a non-generic type. /// e.g. A.B{int} /// </summary> internal sealed class GenericNestedTypeInstanceReference : GenericTypeInstanceReference, Cci.INestedTypeReference { public GenericNestedTypeInstanceReference(NamedTypeSymbol underlyingNamedType) : base(underlyingNamedType) { } Cci.ITypeReference Cci.ITypeMemberReference.GetContainingType(EmitContext context) { return ((PEModuleBuilder)context.Module).Translate(UnderlyingNamedType.ContainingType, syntaxNodeOpt: (CSharpSyntaxNode)context.SyntaxNode, diagnostics: context.Diagnostics); } public override Cci.IGenericTypeInstanceReference AsGenericTypeInstanceReference { get { return this; } } public override Cci.INamespaceTypeReference AsNamespaceTypeReference { get { return null; } } public override Cci.INestedTypeReference AsNestedTypeReference { get { return this; } } public override Cci.ISpecializedNestedTypeReference AsSpecializedNestedTypeReference { get { return null; } } } }
-1
dotnet/roslyn
55,428
Test adding nested namespaces
Fixes https://github.com/dotnet/roslyn/issues/54939 The "workaround" that's already implemented is actually the correct behavior.
tmat
2021-08-05T01:19:03Z
2021-08-11T18:38:54Z
bc874ebc5111a2a33221409f895953b1536f6612
1cbbd423e17b186a8f1de89febb4db9a386d180d
Test adding nested namespaces. Fixes https://github.com/dotnet/roslyn/issues/54939 The "workaround" that's already implemented is actually the correct behavior.
./src/Compilers/CSharp/Portable/Emitter/EditAndContinue/CSharpSymbolMatcher.cs
// Licensed to the .NET Foundation under one or more agreements. // 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; using Microsoft.CodeAnalysis.Emit; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis.CSharp.Symbols.Metadata.PE; using Microsoft.CodeAnalysis.Symbols; using System.Diagnostics.CodeAnalysis; namespace Microsoft.CodeAnalysis.CSharp.Emit { internal sealed class CSharpSymbolMatcher : SymbolMatcher { private readonly MatchDefs _defs; private readonly MatchSymbols _symbols; public CSharpSymbolMatcher( IReadOnlyDictionary<AnonymousTypeKey, AnonymousTypeValue> anonymousTypeMap, SourceAssemblySymbol sourceAssembly, EmitContext sourceContext, SourceAssemblySymbol otherAssembly, EmitContext otherContext, ImmutableDictionary<ISymbolInternal, ImmutableArray<ISymbolInternal>> otherSynthesizedMembersOpt) { _defs = new MatchDefsToSource(sourceContext, otherContext); _symbols = new MatchSymbols(anonymousTypeMap, sourceAssembly, otherAssembly, otherSynthesizedMembersOpt, new DeepTranslator(otherAssembly.GetSpecialType(SpecialType.System_Object))); } public CSharpSymbolMatcher( IReadOnlyDictionary<AnonymousTypeKey, AnonymousTypeValue> anonymousTypeMap, SourceAssemblySymbol sourceAssembly, EmitContext sourceContext, PEAssemblySymbol otherAssembly) { _defs = new MatchDefsToMetadata(sourceContext, otherAssembly); _symbols = new MatchSymbols( anonymousTypeMap, sourceAssembly, otherAssembly, otherSynthesizedMembers: null, deepTranslator: null); } public override Cci.IDefinition? MapDefinition(Cci.IDefinition definition) { if (definition.GetInternalSymbol() is Symbol symbol) { return (Cci.IDefinition?)_symbols.Visit(symbol)?.GetCciAdapter(); } // TODO: this appears to be dead code, remove (https://github.com/dotnet/roslyn/issues/51595) return _defs.VisitDef(definition); } public override Cci.INamespace? MapNamespace(Cci.INamespace @namespace) { if (@namespace.GetInternalSymbol() is NamespaceSymbol symbol) { return (Cci.INamespace?)_symbols.Visit(symbol)?.GetCciAdapter(); } return null; } public override Cci.ITypeReference? MapReference(Cci.ITypeReference reference) { if (reference.GetInternalSymbol() is Symbol symbol) { return (Cci.ITypeReference?)_symbols.Visit(symbol)?.GetCciAdapter(); } return null; } internal bool TryGetAnonymousTypeName(AnonymousTypeManager.AnonymousTypeTemplateSymbol template, [NotNullWhen(true)] out string? name, out int index) => _symbols.TryGetAnonymousTypeName(template, out name, out index); private abstract class MatchDefs { private readonly EmitContext _sourceContext; private readonly ConcurrentDictionary<Cci.IDefinition, Cci.IDefinition?> _matches = new(ReferenceEqualityComparer.Instance); private IReadOnlyDictionary<string, Cci.INamespaceTypeDefinition>? _lazyTopLevelTypes; public MatchDefs(EmitContext sourceContext) { _sourceContext = sourceContext; } public Cci.IDefinition? VisitDef(Cci.IDefinition def) => _matches.GetOrAdd(def, VisitDefInternal); private Cci.IDefinition? VisitDefInternal(Cci.IDefinition def) { if (def is Cci.ITypeDefinition type) { var namespaceType = type.AsNamespaceTypeDefinition(_sourceContext); if (namespaceType != null) { return VisitNamespaceType(namespaceType); } var nestedType = type.AsNestedTypeDefinition(_sourceContext); Debug.Assert(nestedType != null); var otherContainer = (Cci.ITypeDefinition?)VisitDef(nestedType.ContainingTypeDefinition); if (otherContainer == null) { return null; } return VisitTypeMembers(otherContainer, nestedType, GetNestedTypes, (a, b) => StringOrdinalComparer.Equals(a.Name, b.Name)); } if (def is Cci.ITypeDefinitionMember member) { var otherContainer = (Cci.ITypeDefinition?)VisitDef(member.ContainingTypeDefinition); if (otherContainer == null) { return null; } if (def is Cci.IFieldDefinition field) { return VisitTypeMembers(otherContainer, field, GetFields, (a, b) => StringOrdinalComparer.Equals(a.Name, b.Name)); } } // We are only expecting types and fields currently. throw ExceptionUtilities.UnexpectedValue(def); } protected abstract IEnumerable<Cci.INamespaceTypeDefinition> GetTopLevelTypes(); protected abstract IEnumerable<Cci.INestedTypeDefinition> GetNestedTypes(Cci.ITypeDefinition def); protected abstract IEnumerable<Cci.IFieldDefinition> GetFields(Cci.ITypeDefinition def); private Cci.INamespaceTypeDefinition? VisitNamespaceType(Cci.INamespaceTypeDefinition def) { // All generated top-level types are assumed to be in the global namespace. // However, this may be an embedded NoPIA type within a namespace. // Since we do not support edits that include references to NoPIA types // (see #855640), it's reasonable to simply drop such cases. if (!string.IsNullOrEmpty(def.NamespaceName)) { return null; } RoslynDebug.AssertNotNull(def.Name); var topLevelTypes = GetTopLevelTypesByName(); topLevelTypes.TryGetValue(def.Name, out var otherDef); return otherDef; } private IReadOnlyDictionary<string, Cci.INamespaceTypeDefinition> GetTopLevelTypesByName() { if (_lazyTopLevelTypes == null) { var typesByName = new Dictionary<string, Cci.INamespaceTypeDefinition>(StringOrdinalComparer.Instance); foreach (var type in GetTopLevelTypes()) { // All generated top-level types are assumed to be in the global namespace. if (string.IsNullOrEmpty(type.NamespaceName)) { RoslynDebug.AssertNotNull(type.Name); typesByName.Add(type.Name, type); } } Interlocked.CompareExchange(ref _lazyTopLevelTypes, typesByName, null); } return _lazyTopLevelTypes; } private static T VisitTypeMembers<T>( Cci.ITypeDefinition otherContainer, T member, Func<Cci.ITypeDefinition, IEnumerable<T>> getMembers, Func<T, T, bool> predicate) where T : class, Cci.ITypeDefinitionMember { // We could cache the members by name (see Matcher.VisitNamedTypeMembers) // but the assumption is this class is only used for types with few members // so caching is not necessary and linear search is acceptable. return getMembers(otherContainer).FirstOrDefault(otherMember => predicate(member, otherMember)); } } private sealed class MatchDefsToMetadata : MatchDefs { private readonly PEAssemblySymbol _otherAssembly; public MatchDefsToMetadata(EmitContext sourceContext, PEAssemblySymbol otherAssembly) : base(sourceContext) { _otherAssembly = otherAssembly; } protected override IEnumerable<Cci.INamespaceTypeDefinition> GetTopLevelTypes() { var builder = ArrayBuilder<Cci.INamespaceTypeDefinition>.GetInstance(); GetTopLevelTypes(builder, _otherAssembly.GlobalNamespace); return builder.ToArrayAndFree(); } protected override IEnumerable<Cci.INestedTypeDefinition> GetNestedTypes(Cci.ITypeDefinition def) { var type = (PENamedTypeSymbol)def; return type.GetTypeMembers().Cast<Cci.INestedTypeDefinition>(); } protected override IEnumerable<Cci.IFieldDefinition> GetFields(Cci.ITypeDefinition def) { var type = (PENamedTypeSymbol)def; return type.GetFieldsToEmit().Cast<Cci.IFieldDefinition>(); } private static void GetTopLevelTypes(ArrayBuilder<Cci.INamespaceTypeDefinition> builder, NamespaceSymbol @namespace) { foreach (var member in @namespace.GetMembers()) { if (member.Kind == SymbolKind.Namespace) { GetTopLevelTypes(builder, (NamespaceSymbol)member); } else { builder.Add((Cci.INamespaceTypeDefinition)member.GetCciAdapter()); } } } } private sealed class MatchDefsToSource : MatchDefs { private readonly EmitContext _otherContext; public MatchDefsToSource( EmitContext sourceContext, EmitContext otherContext) : base(sourceContext) { _otherContext = otherContext; } protected override IEnumerable<Cci.INamespaceTypeDefinition> GetTopLevelTypes() { return _otherContext.Module.GetTopLevelTypeDefinitions(_otherContext); } protected override IEnumerable<Cci.INestedTypeDefinition> GetNestedTypes(Cci.ITypeDefinition def) { return def.GetNestedTypes(_otherContext); } protected override IEnumerable<Cci.IFieldDefinition> GetFields(Cci.ITypeDefinition def) { return def.GetFields(_otherContext); } } private sealed class MatchSymbols : CSharpSymbolVisitor<Symbol?> { private readonly IReadOnlyDictionary<AnonymousTypeKey, AnonymousTypeValue> _anonymousTypeMap; private readonly SourceAssemblySymbol _sourceAssembly; // metadata or source assembly: private readonly AssemblySymbol _otherAssembly; /// <summary> /// Members that are not listed directly on their containing type or namespace symbol as they were synthesized in a lowering phase, /// after the symbol has been created. /// </summary> private readonly ImmutableDictionary<ISymbolInternal, ImmutableArray<ISymbolInternal>>? _otherSynthesizedMembers; private readonly SymbolComparer _comparer; private readonly ConcurrentDictionary<Symbol, Symbol?> _matches = new(ReferenceEqualityComparer.Instance); /// <summary> /// A cache of members per type, populated when the first member for a given /// type is needed. Within each type, members are indexed by name. The reason /// for caching, and indexing by name, is to avoid searching sequentially /// through all members of a given kind each time a member is matched. /// </summary> private readonly ConcurrentDictionary<ISymbolInternal, IReadOnlyDictionary<string, ImmutableArray<ISymbolInternal>>> _otherMembers = new(ReferenceEqualityComparer.Instance); public MatchSymbols( IReadOnlyDictionary<AnonymousTypeKey, AnonymousTypeValue> anonymousTypeMap, SourceAssemblySymbol sourceAssembly, AssemblySymbol otherAssembly, ImmutableDictionary<ISymbolInternal, ImmutableArray<ISymbolInternal>>? otherSynthesizedMembers, DeepTranslator? deepTranslator) { _anonymousTypeMap = anonymousTypeMap; _sourceAssembly = sourceAssembly; _otherAssembly = otherAssembly; _otherSynthesizedMembers = otherSynthesizedMembers; _comparer = new SymbolComparer(this, deepTranslator); } internal bool TryGetAnonymousTypeName(AnonymousTypeManager.AnonymousTypeTemplateSymbol type, [NotNullWhen(true)] out string? name, out int index) { if (TryFindAnonymousType(type, out var otherType)) { name = otherType.Name; index = otherType.UniqueIndex; return true; } name = null; index = -1; return false; } public override Symbol DefaultVisit(Symbol symbol) { // Symbol should have been handled elsewhere. throw ExceptionUtilities.Unreachable; } public override Symbol? Visit(Symbol symbol) { Debug.Assert((object)symbol.ContainingAssembly != (object)_otherAssembly); // Add an entry for the match, even if there is no match, to avoid // matching the same symbol unsuccessfully multiple times. return _matches.GetOrAdd(symbol, base.Visit); } public override Symbol? VisitArrayType(ArrayTypeSymbol symbol) { var otherElementType = (TypeSymbol?)Visit(symbol.ElementType); if (otherElementType is null) { // For a newly added type, there is no match in the previous generation, so it could be null. return null; } var otherModifiers = VisitCustomModifiers(symbol.ElementTypeWithAnnotations.CustomModifiers); if (symbol.IsSZArray) { return ArrayTypeSymbol.CreateSZArray(_otherAssembly, symbol.ElementTypeWithAnnotations.WithTypeAndModifiers(otherElementType, otherModifiers)); } return ArrayTypeSymbol.CreateMDArray(_otherAssembly, symbol.ElementTypeWithAnnotations.WithTypeAndModifiers(otherElementType, otherModifiers), symbol.Rank, symbol.Sizes, symbol.LowerBounds); } public override Symbol? VisitEvent(EventSymbol symbol) => VisitNamedTypeMember(symbol, AreEventsEqual); public override Symbol? VisitField(FieldSymbol symbol) => VisitNamedTypeMember(symbol, AreFieldsEqual); public override Symbol? VisitMethod(MethodSymbol symbol) { // Not expecting constructed method. Debug.Assert(symbol.IsDefinition); return VisitNamedTypeMember(symbol, AreMethodsEqual); } public override Symbol? VisitModule(ModuleSymbol module) { var otherAssembly = (AssemblySymbol?)Visit(module.ContainingAssembly); if (otherAssembly is null) { return null; } // manifest module: if (module.Ordinal == 0) { return otherAssembly.Modules[0]; } // match non-manifest module by name: for (int i = 1; i < otherAssembly.Modules.Length; i++) { var otherModule = otherAssembly.Modules[i]; // use case sensitive comparison -- modules whose names differ in casing are considered distinct: if (StringComparer.Ordinal.Equals(otherModule.Name, module.Name)) { return otherModule; } } return null; } public override Symbol? VisitAssembly(AssemblySymbol assembly) { if (assembly.IsLinked) { return assembly; } // When we map synthesized symbols from previous generations to the latest compilation // we might encounter a symbol that is defined in arbitrary preceding generation, // not just the immediately preceding generation. If the source assembly uses time-based // versioning assemblies of preceding generations might differ in their version number. if (IdentityEqualIgnoringVersionWildcard(assembly, _sourceAssembly)) { return _otherAssembly; } // find a referenced assembly with the same source identity (modulo assembly version patterns): foreach (var otherReferencedAssembly in _otherAssembly.Modules[0].ReferencedAssemblySymbols) { if (IdentityEqualIgnoringVersionWildcard(assembly, otherReferencedAssembly)) { return otherReferencedAssembly; } } return null; } private static bool IdentityEqualIgnoringVersionWildcard(AssemblySymbol left, AssemblySymbol right) { var leftIdentity = left.Identity; var rightIdentity = right.Identity; return AssemblyIdentityComparer.SimpleNameComparer.Equals(leftIdentity.Name, rightIdentity.Name) && (left.AssemblyVersionPattern ?? leftIdentity.Version).Equals(right.AssemblyVersionPattern ?? rightIdentity.Version) && AssemblyIdentity.EqualIgnoringNameAndVersion(leftIdentity, rightIdentity); } public override Symbol? VisitNamespace(NamespaceSymbol @namespace) { var otherContainer = Visit(@namespace.ContainingSymbol); // TODO: Workaround for https://github.com/dotnet/roslyn/issues/54939. // We should fail if the container can't be mapped. // Currently this only occurs when determining reloadable type name for a type added to a new namespace, // which is a rude edit. // RoslynDebug.AssertNotNull(otherContainer); if (otherContainer is null) { return null; } switch (otherContainer.Kind) { case SymbolKind.NetModule: Debug.Assert(@namespace.IsGlobalNamespace); return ((ModuleSymbol)otherContainer).GlobalNamespace; case SymbolKind.Namespace: return FindMatchingMember(otherContainer, @namespace, AreNamespacesEqual); default: throw ExceptionUtilities.UnexpectedValue(otherContainer.Kind); } } public override Symbol VisitDynamicType(DynamicTypeSymbol symbol) { return _otherAssembly.GetSpecialType(SpecialType.System_Object); } public override Symbol? VisitNamedType(NamedTypeSymbol sourceType) { var originalDef = sourceType.OriginalDefinition; if ((object)originalDef != (object)sourceType) { var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded; var typeArguments = sourceType.GetAllTypeArguments(ref discardedUseSiteInfo); var otherDef = (NamedTypeSymbol?)Visit(originalDef); if (otherDef is null) { return null; } var otherTypeParameters = otherDef.GetAllTypeParameters(); bool translationFailed = false; var otherTypeArguments = typeArguments.SelectAsArray((t, v) => { var newType = (TypeSymbol?)v.Visit(t.Type); if (newType is null) { // For a newly added type, there is no match in the previous generation, so it could be null. translationFailed = true; newType = t.Type; } return t.WithTypeAndModifiers(newType, v.VisitCustomModifiers(t.CustomModifiers)); }, this); if (translationFailed) { // For a newly added type, there is no match in the previous generation, so it could be null. return null; } // TODO: LambdaFrame has alpha renamed type parameters, should we rather fix that? var typeMap = new TypeMap(otherTypeParameters, otherTypeArguments, allowAlpha: true); return typeMap.SubstituteNamedType(otherDef); } Debug.Assert(sourceType.IsDefinition); var otherContainer = this.Visit(sourceType.ContainingSymbol); // Containing type will be missing from other assembly // if the type was added in the (newer) source assembly. if (otherContainer is null) { return null; } switch (otherContainer.Kind) { case SymbolKind.Namespace: if (sourceType is AnonymousTypeManager.AnonymousTypeTemplateSymbol template) { Debug.Assert((object)otherContainer == (object)_otherAssembly.GlobalNamespace); TryFindAnonymousType(template, out var value); return (NamedTypeSymbol?)value.Type?.GetInternalSymbol(); } if (sourceType.IsAnonymousType) { return Visit(AnonymousTypeManager.TranslateAnonymousTypeSymbol(sourceType)); } return FindMatchingMember(otherContainer, sourceType, AreNamedTypesEqual); case SymbolKind.NamedType: return FindMatchingMember(otherContainer, sourceType, AreNamedTypesEqual); default: throw ExceptionUtilities.UnexpectedValue(otherContainer.Kind); } } public override Symbol VisitParameter(ParameterSymbol parameter) { // Should never reach here. Should be matched as a result of matching the container. throw ExceptionUtilities.Unreachable; } public override Symbol? VisitPointerType(PointerTypeSymbol symbol) { var otherPointedAtType = (TypeSymbol?)Visit(symbol.PointedAtType); if (otherPointedAtType is null) { // For a newly added type, there is no match in the previous generation, so it could be null. return null; } var otherModifiers = VisitCustomModifiers(symbol.PointedAtTypeWithAnnotations.CustomModifiers); return new PointerTypeSymbol(symbol.PointedAtTypeWithAnnotations.WithTypeAndModifiers(otherPointedAtType, otherModifiers)); } public override Symbol? VisitFunctionPointerType(FunctionPointerTypeSymbol symbol) { var sig = symbol.Signature; var otherReturnType = (TypeSymbol?)Visit(sig.ReturnType); if (otherReturnType is null) { return null; } var otherRefCustomModifiers = VisitCustomModifiers(sig.RefCustomModifiers); var otherReturnTypeWithAnnotations = sig.ReturnTypeWithAnnotations.WithTypeAndModifiers(otherReturnType, VisitCustomModifiers(sig.ReturnTypeWithAnnotations.CustomModifiers)); var otherParameterTypes = ImmutableArray<TypeWithAnnotations>.Empty; ImmutableArray<ImmutableArray<CustomModifier>> otherParamRefCustomModifiers = default; if (sig.ParameterCount > 0) { var otherParamsBuilder = ArrayBuilder<TypeWithAnnotations>.GetInstance(sig.ParameterCount); var otherParamRefCustomModifiersBuilder = ArrayBuilder<ImmutableArray<CustomModifier>>.GetInstance(sig.ParameterCount); foreach (var param in sig.Parameters) { var otherType = (TypeSymbol?)Visit(param.Type); if (otherType is null) { otherParamsBuilder.Free(); otherParamRefCustomModifiersBuilder.Free(); return null; } otherParamRefCustomModifiersBuilder.Add(VisitCustomModifiers(param.RefCustomModifiers)); otherParamsBuilder.Add(param.TypeWithAnnotations.WithTypeAndModifiers(otherType, VisitCustomModifiers(param.TypeWithAnnotations.CustomModifiers))); } otherParameterTypes = otherParamsBuilder.ToImmutableAndFree(); otherParamRefCustomModifiers = otherParamRefCustomModifiersBuilder.ToImmutableAndFree(); } return symbol.SubstituteTypeSymbol(otherReturnTypeWithAnnotations, otherParameterTypes, otherRefCustomModifiers, otherParamRefCustomModifiers); } public override Symbol? VisitProperty(PropertySymbol symbol) => VisitNamedTypeMember(symbol, ArePropertiesEqual); public override Symbol VisitTypeParameter(TypeParameterSymbol symbol) { if (symbol is IndexedTypeParameterSymbol indexed) { return indexed; } var otherContainer = Visit(symbol.ContainingSymbol); RoslynDebug.AssertNotNull(otherContainer); var otherTypeParameters = otherContainer.Kind switch { SymbolKind.NamedType or SymbolKind.ErrorType => ((NamedTypeSymbol)otherContainer).TypeParameters, SymbolKind.Method => ((MethodSymbol)otherContainer).TypeParameters, _ => throw ExceptionUtilities.UnexpectedValue(otherContainer.Kind), }; return otherTypeParameters[symbol.Ordinal]; } private ImmutableArray<CustomModifier> VisitCustomModifiers(ImmutableArray<CustomModifier> modifiers) { return modifiers.SelectAsArray(VisitCustomModifier); } private CustomModifier VisitCustomModifier(CustomModifier modifier) { var type = (NamedTypeSymbol?)Visit(((CSharpCustomModifier)modifier).ModifierSymbol); RoslynDebug.AssertNotNull(type); return modifier.IsOptional ? CSharpCustomModifier.CreateOptional(type) : CSharpCustomModifier.CreateRequired(type); } internal bool TryFindAnonymousType(AnonymousTypeManager.AnonymousTypeTemplateSymbol type, out AnonymousTypeValue otherType) { Debug.Assert((object)type.ContainingSymbol == (object)_sourceAssembly.GlobalNamespace); return _anonymousTypeMap.TryGetValue(type.GetAnonymousTypeKey(), out otherType); } private Symbol? VisitNamedTypeMember<T>(T member, Func<T, T, bool> predicate) where T : Symbol { var otherType = (NamedTypeSymbol?)Visit(member.ContainingType); // Containing type may be null for synthesized // types such as iterators. if (otherType is null) { return null; } return FindMatchingMember(otherType, member, predicate); } private T? FindMatchingMember<T>(ISymbolInternal otherTypeOrNamespace, T sourceMember, Func<T, T, bool> predicate) where T : Symbol { Debug.Assert(!string.IsNullOrEmpty(sourceMember.MetadataName)); var otherMembersByName = _otherMembers.GetOrAdd(otherTypeOrNamespace, GetAllEmittedMembers); if (otherMembersByName.TryGetValue(sourceMember.MetadataName, out var otherMembers)) { foreach (var otherMember in otherMembers) { if (otherMember is T other && predicate(sourceMember, other)) { return other; } } } return null; } private bool AreArrayTypesEqual(ArrayTypeSymbol type, ArrayTypeSymbol other) { // TODO: Test with overloads (from PE base class?) that have modifiers. Debug.Assert(type.ElementTypeWithAnnotations.CustomModifiers.IsEmpty); Debug.Assert(other.ElementTypeWithAnnotations.CustomModifiers.IsEmpty); return type.HasSameShapeAs(other) && AreTypesEqual(type.ElementType, other.ElementType); } private bool AreEventsEqual(EventSymbol @event, EventSymbol other) { Debug.Assert(StringOrdinalComparer.Equals(@event.Name, other.Name)); return _comparer.Equals(@event.Type, other.Type); } private bool AreFieldsEqual(FieldSymbol field, FieldSymbol other) { Debug.Assert(StringOrdinalComparer.Equals(field.Name, other.Name)); return _comparer.Equals(field.Type, other.Type); } private bool AreMethodsEqual(MethodSymbol method, MethodSymbol other) { Debug.Assert(StringOrdinalComparer.Equals(method.Name, other.Name)); Debug.Assert(method.IsDefinition); Debug.Assert(other.IsDefinition); method = SubstituteTypeParameters(method); other = SubstituteTypeParameters(other); return _comparer.Equals(method.ReturnType, other.ReturnType) && method.RefKind.Equals(other.RefKind) && method.Parameters.SequenceEqual(other.Parameters, AreParametersEqual) && method.TypeParameters.SequenceEqual(other.TypeParameters, AreTypesEqual); } private static MethodSymbol SubstituteTypeParameters(MethodSymbol method) { Debug.Assert(method.IsDefinition); var typeParameters = method.TypeParameters; int n = typeParameters.Length; if (n == 0) { return method; } return method.Construct(IndexedTypeParameterSymbol.Take(n)); } private bool AreNamedTypesEqual(NamedTypeSymbol type, NamedTypeSymbol other) { Debug.Assert(StringOrdinalComparer.Equals(type.MetadataName, other.MetadataName)); // TODO: Test with overloads (from PE base class?) that have modifiers. Debug.Assert(type.TypeArgumentsWithAnnotationsNoUseSiteDiagnostics.All(t => t.CustomModifiers.IsEmpty)); Debug.Assert(other.TypeArgumentsWithAnnotationsNoUseSiteDiagnostics.All(t => t.CustomModifiers.IsEmpty)); return type.TypeArgumentsWithAnnotationsNoUseSiteDiagnostics.SequenceEqual(other.TypeArgumentsWithAnnotationsNoUseSiteDiagnostics, AreTypesEqual); } private bool AreNamespacesEqual(NamespaceSymbol @namespace, NamespaceSymbol other) { Debug.Assert(StringOrdinalComparer.Equals(@namespace.MetadataName, other.MetadataName)); return true; } private bool AreParametersEqual(ParameterSymbol parameter, ParameterSymbol other) { Debug.Assert(parameter.Ordinal == other.Ordinal); return (parameter.RefKind == other.RefKind) && _comparer.Equals(parameter.Type, other.Type); } private bool ArePointerTypesEqual(PointerTypeSymbol type, PointerTypeSymbol other) { // TODO: Test with overloads (from PE base class?) that have modifiers. Debug.Assert(type.PointedAtTypeWithAnnotations.CustomModifiers.IsEmpty); Debug.Assert(other.PointedAtTypeWithAnnotations.CustomModifiers.IsEmpty); return AreTypesEqual(type.PointedAtType, other.PointedAtType); } private bool AreFunctionPointerTypesEqual(FunctionPointerTypeSymbol type, FunctionPointerTypeSymbol other) { var sig = type.Signature; var otherSig = other.Signature; ValidateFunctionPointerParamOrReturn(sig.ReturnTypeWithAnnotations, sig.RefKind, sig.RefCustomModifiers, allowOut: false); ValidateFunctionPointerParamOrReturn(otherSig.ReturnTypeWithAnnotations, otherSig.RefKind, otherSig.RefCustomModifiers, allowOut: false); if (sig.RefKind != otherSig.RefKind || !AreTypesEqual(sig.ReturnTypeWithAnnotations, otherSig.ReturnTypeWithAnnotations)) { return false; } return sig.Parameters.SequenceEqual(otherSig.Parameters, AreFunctionPointerParametersEqual); } private bool AreFunctionPointerParametersEqual(ParameterSymbol param, ParameterSymbol otherParam) { ValidateFunctionPointerParamOrReturn(param.TypeWithAnnotations, param.RefKind, param.RefCustomModifiers, allowOut: true); ValidateFunctionPointerParamOrReturn(otherParam.TypeWithAnnotations, otherParam.RefKind, otherParam.RefCustomModifiers, allowOut: true); return param.RefKind == otherParam.RefKind && AreTypesEqual(param.TypeWithAnnotations, otherParam.TypeWithAnnotations); } [Conditional("DEBUG")] private static void ValidateFunctionPointerParamOrReturn(TypeWithAnnotations type, RefKind refKind, ImmutableArray<CustomModifier> refCustomModifiers, bool allowOut) { Debug.Assert(type.CustomModifiers.IsEmpty); Debug.Assert(verifyRefModifiers(refCustomModifiers, refKind, allowOut)); static bool verifyRefModifiers(ImmutableArray<CustomModifier> modifiers, RefKind refKind, bool allowOut) { Debug.Assert(RefKind.RefReadOnly == RefKind.In); switch (refKind) { case RefKind.RefReadOnly: case RefKind.Out when allowOut: return modifiers.Length == 1; default: return modifiers.IsEmpty; } } } private bool ArePropertiesEqual(PropertySymbol property, PropertySymbol other) { Debug.Assert(StringOrdinalComparer.Equals(property.MetadataName, other.MetadataName)); return _comparer.Equals(property.Type, other.Type) && property.RefKind.Equals(other.RefKind) && property.Parameters.SequenceEqual(other.Parameters, AreParametersEqual); } private static bool AreTypeParametersEqual(TypeParameterSymbol type, TypeParameterSymbol other) { Debug.Assert(type.Ordinal == other.Ordinal); Debug.Assert(StringOrdinalComparer.Equals(type.Name, other.Name)); // Comparing constraints is unnecessary: two methods cannot differ by // constraints alone and changing the signature of a method is a rude // edit. Furthermore, comparing constraint types might lead to a cycle. Debug.Assert(type.HasConstructorConstraint == other.HasConstructorConstraint); Debug.Assert(type.HasValueTypeConstraint == other.HasValueTypeConstraint); Debug.Assert(type.HasUnmanagedTypeConstraint == other.HasUnmanagedTypeConstraint); Debug.Assert(type.HasReferenceTypeConstraint == other.HasReferenceTypeConstraint); Debug.Assert(type.ConstraintTypesNoUseSiteDiagnostics.Length == other.ConstraintTypesNoUseSiteDiagnostics.Length); return true; } private bool AreTypesEqual(TypeWithAnnotations type, TypeWithAnnotations other) { Debug.Assert(type.CustomModifiers.IsDefaultOrEmpty); Debug.Assert(other.CustomModifiers.IsDefaultOrEmpty); return AreTypesEqual(type.Type, other.Type); } private bool AreTypesEqual(TypeSymbol type, TypeSymbol other) { if (type.Kind != other.Kind) { return false; } switch (type.Kind) { case SymbolKind.ArrayType: return AreArrayTypesEqual((ArrayTypeSymbol)type, (ArrayTypeSymbol)other); case SymbolKind.PointerType: return ArePointerTypesEqual((PointerTypeSymbol)type, (PointerTypeSymbol)other); case SymbolKind.FunctionPointerType: return AreFunctionPointerTypesEqual((FunctionPointerTypeSymbol)type, (FunctionPointerTypeSymbol)other); case SymbolKind.NamedType: case SymbolKind.ErrorType: return AreNamedTypesEqual((NamedTypeSymbol)type, (NamedTypeSymbol)other); case SymbolKind.TypeParameter: return AreTypeParametersEqual((TypeParameterSymbol)type, (TypeParameterSymbol)other); default: throw ExceptionUtilities.UnexpectedValue(type.Kind); } } private IReadOnlyDictionary<string, ImmutableArray<ISymbolInternal>> GetAllEmittedMembers(ISymbolInternal symbol) { var members = ArrayBuilder<ISymbolInternal>.GetInstance(); if (symbol.Kind == SymbolKind.NamedType) { var type = (NamedTypeSymbol)symbol; members.AddRange(type.GetEventsToEmit()); members.AddRange(type.GetFieldsToEmit()); members.AddRange(type.GetMethodsToEmit()); members.AddRange(type.GetTypeMembers()); members.AddRange(type.GetPropertiesToEmit()); } else { members.AddRange(((NamespaceSymbol)symbol).GetMembers()); } if (_otherSynthesizedMembers != null && _otherSynthesizedMembers.TryGetValue(symbol, out var synthesizedMembers)) { members.AddRange(synthesizedMembers); } var result = members.ToDictionary(s => s.MetadataName, StringOrdinalComparer.Instance); members.Free(); return result; } private sealed class SymbolComparer { private readonly MatchSymbols _matcher; private readonly DeepTranslator? _deepTranslator; public SymbolComparer(MatchSymbols matcher, DeepTranslator? deepTranslator) { Debug.Assert(matcher != null); _matcher = matcher; _deepTranslator = deepTranslator; } public bool Equals(TypeSymbol source, TypeSymbol other) { var visitedSource = (TypeSymbol?)_matcher.Visit(source); var visitedOther = (_deepTranslator != null) ? (TypeSymbol)_deepTranslator.Visit(other) : other; return visitedSource?.Equals(visitedOther, TypeCompareKind.IgnoreDynamicAndTupleNames | TypeCompareKind.IgnoreNullableModifiersForReferenceTypes) == true; } } } internal sealed class DeepTranslator : CSharpSymbolVisitor<Symbol> { private readonly ConcurrentDictionary<Symbol, Symbol> _matches; private readonly NamedTypeSymbol _systemObject; public DeepTranslator(NamedTypeSymbol systemObject) { _matches = new ConcurrentDictionary<Symbol, Symbol>(ReferenceEqualityComparer.Instance); _systemObject = systemObject; } public override Symbol DefaultVisit(Symbol symbol) { // Symbol should have been handled elsewhere. throw ExceptionUtilities.Unreachable; } public override Symbol Visit(Symbol symbol) { return _matches.GetOrAdd(symbol, base.Visit(symbol)); } public override Symbol VisitArrayType(ArrayTypeSymbol symbol) { var translatedElementType = (TypeSymbol)this.Visit(symbol.ElementType); var translatedModifiers = VisitCustomModifiers(symbol.ElementTypeWithAnnotations.CustomModifiers); if (symbol.IsSZArray) { return ArrayTypeSymbol.CreateSZArray(symbol.BaseTypeNoUseSiteDiagnostics.ContainingAssembly, symbol.ElementTypeWithAnnotations.WithTypeAndModifiers(translatedElementType, translatedModifiers)); } return ArrayTypeSymbol.CreateMDArray(symbol.BaseTypeNoUseSiteDiagnostics.ContainingAssembly, symbol.ElementTypeWithAnnotations.WithTypeAndModifiers(translatedElementType, translatedModifiers), symbol.Rank, symbol.Sizes, symbol.LowerBounds); } public override Symbol VisitDynamicType(DynamicTypeSymbol symbol) { return _systemObject; } public override Symbol VisitNamedType(NamedTypeSymbol type) { var originalDef = type.OriginalDefinition; if ((object)originalDef != type) { var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded; var translatedTypeArguments = type.GetAllTypeArguments(ref discardedUseSiteInfo).SelectAsArray((t, v) => t.WithTypeAndModifiers((TypeSymbol)v.Visit(t.Type), v.VisitCustomModifiers(t.CustomModifiers)), this); var translatedOriginalDef = (NamedTypeSymbol)this.Visit(originalDef); var typeMap = new TypeMap(translatedOriginalDef.GetAllTypeParameters(), translatedTypeArguments, allowAlpha: true); return typeMap.SubstituteNamedType(translatedOriginalDef); } Debug.Assert(type.IsDefinition); if (type.IsAnonymousType) { return this.Visit(AnonymousTypeManager.TranslateAnonymousTypeSymbol(type)); } return type; } public override Symbol VisitPointerType(PointerTypeSymbol symbol) { var translatedPointedAtType = (TypeSymbol)this.Visit(symbol.PointedAtType); var translatedModifiers = VisitCustomModifiers(symbol.PointedAtTypeWithAnnotations.CustomModifiers); return new PointerTypeSymbol(symbol.PointedAtTypeWithAnnotations.WithTypeAndModifiers(translatedPointedAtType, translatedModifiers)); } public override Symbol VisitFunctionPointerType(FunctionPointerTypeSymbol symbol) { var sig = symbol.Signature; var translatedReturnType = (TypeSymbol)Visit(sig.ReturnType); var translatedReturnTypeWithAnnotations = sig.ReturnTypeWithAnnotations.WithTypeAndModifiers(translatedReturnType, VisitCustomModifiers(sig.ReturnTypeWithAnnotations.CustomModifiers)); var translatedRefCustomModifiers = VisitCustomModifiers(sig.RefCustomModifiers); var translatedParameterTypes = ImmutableArray<TypeWithAnnotations>.Empty; ImmutableArray<ImmutableArray<CustomModifier>> translatedParamRefCustomModifiers = default; if (sig.ParameterCount > 0) { var translatedParamsBuilder = ArrayBuilder<TypeWithAnnotations>.GetInstance(sig.ParameterCount); var translatedParamRefCustomModifiersBuilder = ArrayBuilder<ImmutableArray<CustomModifier>>.GetInstance(sig.ParameterCount); foreach (var param in sig.Parameters) { var translatedParamType = (TypeSymbol)Visit(param.Type); translatedParamsBuilder.Add(param.TypeWithAnnotations.WithTypeAndModifiers(translatedParamType, VisitCustomModifiers(param.TypeWithAnnotations.CustomModifiers))); translatedParamRefCustomModifiersBuilder.Add(VisitCustomModifiers(param.RefCustomModifiers)); } translatedParameterTypes = translatedParamsBuilder.ToImmutableAndFree(); translatedParamRefCustomModifiers = translatedParamRefCustomModifiersBuilder.ToImmutableAndFree(); } return symbol.SubstituteTypeSymbol(translatedReturnTypeWithAnnotations, translatedParameterTypes, translatedRefCustomModifiers, translatedParamRefCustomModifiers); } public override Symbol VisitTypeParameter(TypeParameterSymbol symbol) { return symbol; } private ImmutableArray<CustomModifier> VisitCustomModifiers(ImmutableArray<CustomModifier> modifiers) { return modifiers.SelectAsArray(VisitCustomModifier); } private CustomModifier VisitCustomModifier(CustomModifier modifier) { var translatedType = (NamedTypeSymbol)this.Visit(((CSharpCustomModifier)modifier).ModifierSymbol); Debug.Assert((object)translatedType != null); return modifier.IsOptional ? CSharpCustomModifier.CreateOptional(translatedType) : CSharpCustomModifier.CreateRequired(translatedType); } } } }
// Licensed to the .NET Foundation under one or more agreements. // 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; using Microsoft.CodeAnalysis.Emit; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis.CSharp.Symbols.Metadata.PE; using Microsoft.CodeAnalysis.Symbols; using System.Diagnostics.CodeAnalysis; namespace Microsoft.CodeAnalysis.CSharp.Emit { internal sealed class CSharpSymbolMatcher : SymbolMatcher { private readonly MatchDefs _defs; private readonly MatchSymbols _symbols; public CSharpSymbolMatcher( IReadOnlyDictionary<AnonymousTypeKey, AnonymousTypeValue> anonymousTypeMap, SourceAssemblySymbol sourceAssembly, EmitContext sourceContext, SourceAssemblySymbol otherAssembly, EmitContext otherContext, ImmutableDictionary<ISymbolInternal, ImmutableArray<ISymbolInternal>> otherSynthesizedMembersOpt) { _defs = new MatchDefsToSource(sourceContext, otherContext); _symbols = new MatchSymbols(anonymousTypeMap, sourceAssembly, otherAssembly, otherSynthesizedMembersOpt, new DeepTranslator(otherAssembly.GetSpecialType(SpecialType.System_Object))); } public CSharpSymbolMatcher( IReadOnlyDictionary<AnonymousTypeKey, AnonymousTypeValue> anonymousTypeMap, SourceAssemblySymbol sourceAssembly, EmitContext sourceContext, PEAssemblySymbol otherAssembly) { _defs = new MatchDefsToMetadata(sourceContext, otherAssembly); _symbols = new MatchSymbols( anonymousTypeMap, sourceAssembly, otherAssembly, otherSynthesizedMembers: null, deepTranslator: null); } public override Cci.IDefinition? MapDefinition(Cci.IDefinition definition) { if (definition.GetInternalSymbol() is Symbol symbol) { return (Cci.IDefinition?)_symbols.Visit(symbol)?.GetCciAdapter(); } // TODO: this appears to be dead code, remove (https://github.com/dotnet/roslyn/issues/51595) return _defs.VisitDef(definition); } public override Cci.INamespace? MapNamespace(Cci.INamespace @namespace) { if (@namespace.GetInternalSymbol() is NamespaceSymbol symbol) { return (Cci.INamespace?)_symbols.Visit(symbol)?.GetCciAdapter(); } return null; } public override Cci.ITypeReference? MapReference(Cci.ITypeReference reference) { if (reference.GetInternalSymbol() is Symbol symbol) { return (Cci.ITypeReference?)_symbols.Visit(symbol)?.GetCciAdapter(); } return null; } internal bool TryGetAnonymousTypeName(AnonymousTypeManager.AnonymousTypeTemplateSymbol template, [NotNullWhen(true)] out string? name, out int index) => _symbols.TryGetAnonymousTypeName(template, out name, out index); private abstract class MatchDefs { private readonly EmitContext _sourceContext; private readonly ConcurrentDictionary<Cci.IDefinition, Cci.IDefinition?> _matches = new(ReferenceEqualityComparer.Instance); private IReadOnlyDictionary<string, Cci.INamespaceTypeDefinition>? _lazyTopLevelTypes; public MatchDefs(EmitContext sourceContext) { _sourceContext = sourceContext; } public Cci.IDefinition? VisitDef(Cci.IDefinition def) => _matches.GetOrAdd(def, VisitDefInternal); private Cci.IDefinition? VisitDefInternal(Cci.IDefinition def) { if (def is Cci.ITypeDefinition type) { var namespaceType = type.AsNamespaceTypeDefinition(_sourceContext); if (namespaceType != null) { return VisitNamespaceType(namespaceType); } var nestedType = type.AsNestedTypeDefinition(_sourceContext); Debug.Assert(nestedType != null); var otherContainer = (Cci.ITypeDefinition?)VisitDef(nestedType.ContainingTypeDefinition); if (otherContainer == null) { return null; } return VisitTypeMembers(otherContainer, nestedType, GetNestedTypes, (a, b) => StringOrdinalComparer.Equals(a.Name, b.Name)); } if (def is Cci.ITypeDefinitionMember member) { var otherContainer = (Cci.ITypeDefinition?)VisitDef(member.ContainingTypeDefinition); if (otherContainer == null) { return null; } if (def is Cci.IFieldDefinition field) { return VisitTypeMembers(otherContainer, field, GetFields, (a, b) => StringOrdinalComparer.Equals(a.Name, b.Name)); } } // We are only expecting types and fields currently. throw ExceptionUtilities.UnexpectedValue(def); } protected abstract IEnumerable<Cci.INamespaceTypeDefinition> GetTopLevelTypes(); protected abstract IEnumerable<Cci.INestedTypeDefinition> GetNestedTypes(Cci.ITypeDefinition def); protected abstract IEnumerable<Cci.IFieldDefinition> GetFields(Cci.ITypeDefinition def); private Cci.INamespaceTypeDefinition? VisitNamespaceType(Cci.INamespaceTypeDefinition def) { // All generated top-level types are assumed to be in the global namespace. // However, this may be an embedded NoPIA type within a namespace. // Since we do not support edits that include references to NoPIA types // (see #855640), it's reasonable to simply drop such cases. if (!string.IsNullOrEmpty(def.NamespaceName)) { return null; } RoslynDebug.AssertNotNull(def.Name); var topLevelTypes = GetTopLevelTypesByName(); topLevelTypes.TryGetValue(def.Name, out var otherDef); return otherDef; } private IReadOnlyDictionary<string, Cci.INamespaceTypeDefinition> GetTopLevelTypesByName() { if (_lazyTopLevelTypes == null) { var typesByName = new Dictionary<string, Cci.INamespaceTypeDefinition>(StringOrdinalComparer.Instance); foreach (var type in GetTopLevelTypes()) { // All generated top-level types are assumed to be in the global namespace. if (string.IsNullOrEmpty(type.NamespaceName)) { RoslynDebug.AssertNotNull(type.Name); typesByName.Add(type.Name, type); } } Interlocked.CompareExchange(ref _lazyTopLevelTypes, typesByName, null); } return _lazyTopLevelTypes; } private static T VisitTypeMembers<T>( Cci.ITypeDefinition otherContainer, T member, Func<Cci.ITypeDefinition, IEnumerable<T>> getMembers, Func<T, T, bool> predicate) where T : class, Cci.ITypeDefinitionMember { // We could cache the members by name (see Matcher.VisitNamedTypeMembers) // but the assumption is this class is only used for types with few members // so caching is not necessary and linear search is acceptable. return getMembers(otherContainer).FirstOrDefault(otherMember => predicate(member, otherMember)); } } private sealed class MatchDefsToMetadata : MatchDefs { private readonly PEAssemblySymbol _otherAssembly; public MatchDefsToMetadata(EmitContext sourceContext, PEAssemblySymbol otherAssembly) : base(sourceContext) { _otherAssembly = otherAssembly; } protected override IEnumerable<Cci.INamespaceTypeDefinition> GetTopLevelTypes() { var builder = ArrayBuilder<Cci.INamespaceTypeDefinition>.GetInstance(); GetTopLevelTypes(builder, _otherAssembly.GlobalNamespace); return builder.ToArrayAndFree(); } protected override IEnumerable<Cci.INestedTypeDefinition> GetNestedTypes(Cci.ITypeDefinition def) { var type = (PENamedTypeSymbol)def; return type.GetTypeMembers().Cast<Cci.INestedTypeDefinition>(); } protected override IEnumerable<Cci.IFieldDefinition> GetFields(Cci.ITypeDefinition def) { var type = (PENamedTypeSymbol)def; return type.GetFieldsToEmit().Cast<Cci.IFieldDefinition>(); } private static void GetTopLevelTypes(ArrayBuilder<Cci.INamespaceTypeDefinition> builder, NamespaceSymbol @namespace) { foreach (var member in @namespace.GetMembers()) { if (member.Kind == SymbolKind.Namespace) { GetTopLevelTypes(builder, (NamespaceSymbol)member); } else { builder.Add((Cci.INamespaceTypeDefinition)member.GetCciAdapter()); } } } } private sealed class MatchDefsToSource : MatchDefs { private readonly EmitContext _otherContext; public MatchDefsToSource( EmitContext sourceContext, EmitContext otherContext) : base(sourceContext) { _otherContext = otherContext; } protected override IEnumerable<Cci.INamespaceTypeDefinition> GetTopLevelTypes() { return _otherContext.Module.GetTopLevelTypeDefinitions(_otherContext); } protected override IEnumerable<Cci.INestedTypeDefinition> GetNestedTypes(Cci.ITypeDefinition def) { return def.GetNestedTypes(_otherContext); } protected override IEnumerable<Cci.IFieldDefinition> GetFields(Cci.ITypeDefinition def) { return def.GetFields(_otherContext); } } private sealed class MatchSymbols : CSharpSymbolVisitor<Symbol?> { private readonly IReadOnlyDictionary<AnonymousTypeKey, AnonymousTypeValue> _anonymousTypeMap; private readonly SourceAssemblySymbol _sourceAssembly; // metadata or source assembly: private readonly AssemblySymbol _otherAssembly; /// <summary> /// Members that are not listed directly on their containing type or namespace symbol as they were synthesized in a lowering phase, /// after the symbol has been created. /// </summary> private readonly ImmutableDictionary<ISymbolInternal, ImmutableArray<ISymbolInternal>>? _otherSynthesizedMembers; private readonly SymbolComparer _comparer; private readonly ConcurrentDictionary<Symbol, Symbol?> _matches = new(ReferenceEqualityComparer.Instance); /// <summary> /// A cache of members per type, populated when the first member for a given /// type is needed. Within each type, members are indexed by name. The reason /// for caching, and indexing by name, is to avoid searching sequentially /// through all members of a given kind each time a member is matched. /// </summary> private readonly ConcurrentDictionary<ISymbolInternal, IReadOnlyDictionary<string, ImmutableArray<ISymbolInternal>>> _otherMembers = new(ReferenceEqualityComparer.Instance); public MatchSymbols( IReadOnlyDictionary<AnonymousTypeKey, AnonymousTypeValue> anonymousTypeMap, SourceAssemblySymbol sourceAssembly, AssemblySymbol otherAssembly, ImmutableDictionary<ISymbolInternal, ImmutableArray<ISymbolInternal>>? otherSynthesizedMembers, DeepTranslator? deepTranslator) { _anonymousTypeMap = anonymousTypeMap; _sourceAssembly = sourceAssembly; _otherAssembly = otherAssembly; _otherSynthesizedMembers = otherSynthesizedMembers; _comparer = new SymbolComparer(this, deepTranslator); } internal bool TryGetAnonymousTypeName(AnonymousTypeManager.AnonymousTypeTemplateSymbol type, [NotNullWhen(true)] out string? name, out int index) { if (TryFindAnonymousType(type, out var otherType)) { name = otherType.Name; index = otherType.UniqueIndex; return true; } name = null; index = -1; return false; } public override Symbol DefaultVisit(Symbol symbol) { // Symbol should have been handled elsewhere. throw ExceptionUtilities.Unreachable; } public override Symbol? Visit(Symbol symbol) { Debug.Assert((object)symbol.ContainingAssembly != (object)_otherAssembly); // Add an entry for the match, even if there is no match, to avoid // matching the same symbol unsuccessfully multiple times. return _matches.GetOrAdd(symbol, base.Visit); } public override Symbol? VisitArrayType(ArrayTypeSymbol symbol) { var otherElementType = (TypeSymbol?)Visit(symbol.ElementType); if (otherElementType is null) { // For a newly added type, there is no match in the previous generation, so it could be null. return null; } var otherModifiers = VisitCustomModifiers(symbol.ElementTypeWithAnnotations.CustomModifiers); if (symbol.IsSZArray) { return ArrayTypeSymbol.CreateSZArray(_otherAssembly, symbol.ElementTypeWithAnnotations.WithTypeAndModifiers(otherElementType, otherModifiers)); } return ArrayTypeSymbol.CreateMDArray(_otherAssembly, symbol.ElementTypeWithAnnotations.WithTypeAndModifiers(otherElementType, otherModifiers), symbol.Rank, symbol.Sizes, symbol.LowerBounds); } public override Symbol? VisitEvent(EventSymbol symbol) => VisitNamedTypeMember(symbol, AreEventsEqual); public override Symbol? VisitField(FieldSymbol symbol) => VisitNamedTypeMember(symbol, AreFieldsEqual); public override Symbol? VisitMethod(MethodSymbol symbol) { // Not expecting constructed method. Debug.Assert(symbol.IsDefinition); return VisitNamedTypeMember(symbol, AreMethodsEqual); } public override Symbol? VisitModule(ModuleSymbol module) { var otherAssembly = (AssemblySymbol?)Visit(module.ContainingAssembly); if (otherAssembly is null) { return null; } // manifest module: if (module.Ordinal == 0) { return otherAssembly.Modules[0]; } // match non-manifest module by name: for (int i = 1; i < otherAssembly.Modules.Length; i++) { var otherModule = otherAssembly.Modules[i]; // use case sensitive comparison -- modules whose names differ in casing are considered distinct: if (StringComparer.Ordinal.Equals(otherModule.Name, module.Name)) { return otherModule; } } return null; } public override Symbol? VisitAssembly(AssemblySymbol assembly) { if (assembly.IsLinked) { return assembly; } // When we map synthesized symbols from previous generations to the latest compilation // we might encounter a symbol that is defined in arbitrary preceding generation, // not just the immediately preceding generation. If the source assembly uses time-based // versioning assemblies of preceding generations might differ in their version number. if (IdentityEqualIgnoringVersionWildcard(assembly, _sourceAssembly)) { return _otherAssembly; } // find a referenced assembly with the same source identity (modulo assembly version patterns): foreach (var otherReferencedAssembly in _otherAssembly.Modules[0].ReferencedAssemblySymbols) { if (IdentityEqualIgnoringVersionWildcard(assembly, otherReferencedAssembly)) { return otherReferencedAssembly; } } return null; } private static bool IdentityEqualIgnoringVersionWildcard(AssemblySymbol left, AssemblySymbol right) { var leftIdentity = left.Identity; var rightIdentity = right.Identity; return AssemblyIdentityComparer.SimpleNameComparer.Equals(leftIdentity.Name, rightIdentity.Name) && (left.AssemblyVersionPattern ?? leftIdentity.Version).Equals(right.AssemblyVersionPattern ?? rightIdentity.Version) && AssemblyIdentity.EqualIgnoringNameAndVersion(leftIdentity, rightIdentity); } public override Symbol? VisitNamespace(NamespaceSymbol @namespace) { var otherContainer = Visit(@namespace.ContainingSymbol); // Containing namespace will be missing from other assembly // if its was added in the (newer) source assembly. if (otherContainer is null) { return null; } switch (otherContainer.Kind) { case SymbolKind.NetModule: Debug.Assert(@namespace.IsGlobalNamespace); return ((ModuleSymbol)otherContainer).GlobalNamespace; case SymbolKind.Namespace: return FindMatchingMember(otherContainer, @namespace, AreNamespacesEqual); default: throw ExceptionUtilities.UnexpectedValue(otherContainer.Kind); } } public override Symbol VisitDynamicType(DynamicTypeSymbol symbol) { return _otherAssembly.GetSpecialType(SpecialType.System_Object); } public override Symbol? VisitNamedType(NamedTypeSymbol sourceType) { var originalDef = sourceType.OriginalDefinition; if ((object)originalDef != (object)sourceType) { var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded; var typeArguments = sourceType.GetAllTypeArguments(ref discardedUseSiteInfo); var otherDef = (NamedTypeSymbol?)Visit(originalDef); if (otherDef is null) { return null; } var otherTypeParameters = otherDef.GetAllTypeParameters(); bool translationFailed = false; var otherTypeArguments = typeArguments.SelectAsArray((t, v) => { var newType = (TypeSymbol?)v.Visit(t.Type); if (newType is null) { // For a newly added type, there is no match in the previous generation, so it could be null. translationFailed = true; newType = t.Type; } return t.WithTypeAndModifiers(newType, v.VisitCustomModifiers(t.CustomModifiers)); }, this); if (translationFailed) { // For a newly added type, there is no match in the previous generation, so it could be null. return null; } // TODO: LambdaFrame has alpha renamed type parameters, should we rather fix that? var typeMap = new TypeMap(otherTypeParameters, otherTypeArguments, allowAlpha: true); return typeMap.SubstituteNamedType(otherDef); } Debug.Assert(sourceType.IsDefinition); var otherContainer = this.Visit(sourceType.ContainingSymbol); // Containing type will be missing from other assembly // if the type was added in the (newer) source assembly. if (otherContainer is null) { return null; } switch (otherContainer.Kind) { case SymbolKind.Namespace: if (sourceType is AnonymousTypeManager.AnonymousTypeTemplateSymbol template) { Debug.Assert((object)otherContainer == (object)_otherAssembly.GlobalNamespace); TryFindAnonymousType(template, out var value); return (NamedTypeSymbol?)value.Type?.GetInternalSymbol(); } if (sourceType.IsAnonymousType) { return Visit(AnonymousTypeManager.TranslateAnonymousTypeSymbol(sourceType)); } return FindMatchingMember(otherContainer, sourceType, AreNamedTypesEqual); case SymbolKind.NamedType: return FindMatchingMember(otherContainer, sourceType, AreNamedTypesEqual); default: throw ExceptionUtilities.UnexpectedValue(otherContainer.Kind); } } public override Symbol VisitParameter(ParameterSymbol parameter) { // Should never reach here. Should be matched as a result of matching the container. throw ExceptionUtilities.Unreachable; } public override Symbol? VisitPointerType(PointerTypeSymbol symbol) { var otherPointedAtType = (TypeSymbol?)Visit(symbol.PointedAtType); if (otherPointedAtType is null) { // For a newly added type, there is no match in the previous generation, so it could be null. return null; } var otherModifiers = VisitCustomModifiers(symbol.PointedAtTypeWithAnnotations.CustomModifiers); return new PointerTypeSymbol(symbol.PointedAtTypeWithAnnotations.WithTypeAndModifiers(otherPointedAtType, otherModifiers)); } public override Symbol? VisitFunctionPointerType(FunctionPointerTypeSymbol symbol) { var sig = symbol.Signature; var otherReturnType = (TypeSymbol?)Visit(sig.ReturnType); if (otherReturnType is null) { return null; } var otherRefCustomModifiers = VisitCustomModifiers(sig.RefCustomModifiers); var otherReturnTypeWithAnnotations = sig.ReturnTypeWithAnnotations.WithTypeAndModifiers(otherReturnType, VisitCustomModifiers(sig.ReturnTypeWithAnnotations.CustomModifiers)); var otherParameterTypes = ImmutableArray<TypeWithAnnotations>.Empty; ImmutableArray<ImmutableArray<CustomModifier>> otherParamRefCustomModifiers = default; if (sig.ParameterCount > 0) { var otherParamsBuilder = ArrayBuilder<TypeWithAnnotations>.GetInstance(sig.ParameterCount); var otherParamRefCustomModifiersBuilder = ArrayBuilder<ImmutableArray<CustomModifier>>.GetInstance(sig.ParameterCount); foreach (var param in sig.Parameters) { var otherType = (TypeSymbol?)Visit(param.Type); if (otherType is null) { otherParamsBuilder.Free(); otherParamRefCustomModifiersBuilder.Free(); return null; } otherParamRefCustomModifiersBuilder.Add(VisitCustomModifiers(param.RefCustomModifiers)); otherParamsBuilder.Add(param.TypeWithAnnotations.WithTypeAndModifiers(otherType, VisitCustomModifiers(param.TypeWithAnnotations.CustomModifiers))); } otherParameterTypes = otherParamsBuilder.ToImmutableAndFree(); otherParamRefCustomModifiers = otherParamRefCustomModifiersBuilder.ToImmutableAndFree(); } return symbol.SubstituteTypeSymbol(otherReturnTypeWithAnnotations, otherParameterTypes, otherRefCustomModifiers, otherParamRefCustomModifiers); } public override Symbol? VisitProperty(PropertySymbol symbol) => VisitNamedTypeMember(symbol, ArePropertiesEqual); public override Symbol VisitTypeParameter(TypeParameterSymbol symbol) { if (symbol is IndexedTypeParameterSymbol indexed) { return indexed; } var otherContainer = Visit(symbol.ContainingSymbol); RoslynDebug.AssertNotNull(otherContainer); var otherTypeParameters = otherContainer.Kind switch { SymbolKind.NamedType or SymbolKind.ErrorType => ((NamedTypeSymbol)otherContainer).TypeParameters, SymbolKind.Method => ((MethodSymbol)otherContainer).TypeParameters, _ => throw ExceptionUtilities.UnexpectedValue(otherContainer.Kind), }; return otherTypeParameters[symbol.Ordinal]; } private ImmutableArray<CustomModifier> VisitCustomModifiers(ImmutableArray<CustomModifier> modifiers) { return modifiers.SelectAsArray(VisitCustomModifier); } private CustomModifier VisitCustomModifier(CustomModifier modifier) { var type = (NamedTypeSymbol?)Visit(((CSharpCustomModifier)modifier).ModifierSymbol); RoslynDebug.AssertNotNull(type); return modifier.IsOptional ? CSharpCustomModifier.CreateOptional(type) : CSharpCustomModifier.CreateRequired(type); } internal bool TryFindAnonymousType(AnonymousTypeManager.AnonymousTypeTemplateSymbol type, out AnonymousTypeValue otherType) { Debug.Assert((object)type.ContainingSymbol == (object)_sourceAssembly.GlobalNamespace); return _anonymousTypeMap.TryGetValue(type.GetAnonymousTypeKey(), out otherType); } private Symbol? VisitNamedTypeMember<T>(T member, Func<T, T, bool> predicate) where T : Symbol { var otherType = (NamedTypeSymbol?)Visit(member.ContainingType); // Containing type may be null for synthesized // types such as iterators. if (otherType is null) { return null; } return FindMatchingMember(otherType, member, predicate); } private T? FindMatchingMember<T>(ISymbolInternal otherTypeOrNamespace, T sourceMember, Func<T, T, bool> predicate) where T : Symbol { Debug.Assert(!string.IsNullOrEmpty(sourceMember.MetadataName)); var otherMembersByName = _otherMembers.GetOrAdd(otherTypeOrNamespace, GetAllEmittedMembers); if (otherMembersByName.TryGetValue(sourceMember.MetadataName, out var otherMembers)) { foreach (var otherMember in otherMembers) { if (otherMember is T other && predicate(sourceMember, other)) { return other; } } } return null; } private bool AreArrayTypesEqual(ArrayTypeSymbol type, ArrayTypeSymbol other) { // TODO: Test with overloads (from PE base class?) that have modifiers. Debug.Assert(type.ElementTypeWithAnnotations.CustomModifiers.IsEmpty); Debug.Assert(other.ElementTypeWithAnnotations.CustomModifiers.IsEmpty); return type.HasSameShapeAs(other) && AreTypesEqual(type.ElementType, other.ElementType); } private bool AreEventsEqual(EventSymbol @event, EventSymbol other) { Debug.Assert(StringOrdinalComparer.Equals(@event.Name, other.Name)); return _comparer.Equals(@event.Type, other.Type); } private bool AreFieldsEqual(FieldSymbol field, FieldSymbol other) { Debug.Assert(StringOrdinalComparer.Equals(field.Name, other.Name)); return _comparer.Equals(field.Type, other.Type); } private bool AreMethodsEqual(MethodSymbol method, MethodSymbol other) { Debug.Assert(StringOrdinalComparer.Equals(method.Name, other.Name)); Debug.Assert(method.IsDefinition); Debug.Assert(other.IsDefinition); method = SubstituteTypeParameters(method); other = SubstituteTypeParameters(other); return _comparer.Equals(method.ReturnType, other.ReturnType) && method.RefKind.Equals(other.RefKind) && method.Parameters.SequenceEqual(other.Parameters, AreParametersEqual) && method.TypeParameters.SequenceEqual(other.TypeParameters, AreTypesEqual); } private static MethodSymbol SubstituteTypeParameters(MethodSymbol method) { Debug.Assert(method.IsDefinition); var typeParameters = method.TypeParameters; int n = typeParameters.Length; if (n == 0) { return method; } return method.Construct(IndexedTypeParameterSymbol.Take(n)); } private bool AreNamedTypesEqual(NamedTypeSymbol type, NamedTypeSymbol other) { Debug.Assert(StringOrdinalComparer.Equals(type.MetadataName, other.MetadataName)); // TODO: Test with overloads (from PE base class?) that have modifiers. Debug.Assert(type.TypeArgumentsWithAnnotationsNoUseSiteDiagnostics.All(t => t.CustomModifiers.IsEmpty)); Debug.Assert(other.TypeArgumentsWithAnnotationsNoUseSiteDiagnostics.All(t => t.CustomModifiers.IsEmpty)); return type.TypeArgumentsWithAnnotationsNoUseSiteDiagnostics.SequenceEqual(other.TypeArgumentsWithAnnotationsNoUseSiteDiagnostics, AreTypesEqual); } private bool AreNamespacesEqual(NamespaceSymbol @namespace, NamespaceSymbol other) { Debug.Assert(StringOrdinalComparer.Equals(@namespace.MetadataName, other.MetadataName)); return true; } private bool AreParametersEqual(ParameterSymbol parameter, ParameterSymbol other) { Debug.Assert(parameter.Ordinal == other.Ordinal); return (parameter.RefKind == other.RefKind) && _comparer.Equals(parameter.Type, other.Type); } private bool ArePointerTypesEqual(PointerTypeSymbol type, PointerTypeSymbol other) { // TODO: Test with overloads (from PE base class?) that have modifiers. Debug.Assert(type.PointedAtTypeWithAnnotations.CustomModifiers.IsEmpty); Debug.Assert(other.PointedAtTypeWithAnnotations.CustomModifiers.IsEmpty); return AreTypesEqual(type.PointedAtType, other.PointedAtType); } private bool AreFunctionPointerTypesEqual(FunctionPointerTypeSymbol type, FunctionPointerTypeSymbol other) { var sig = type.Signature; var otherSig = other.Signature; ValidateFunctionPointerParamOrReturn(sig.ReturnTypeWithAnnotations, sig.RefKind, sig.RefCustomModifiers, allowOut: false); ValidateFunctionPointerParamOrReturn(otherSig.ReturnTypeWithAnnotations, otherSig.RefKind, otherSig.RefCustomModifiers, allowOut: false); if (sig.RefKind != otherSig.RefKind || !AreTypesEqual(sig.ReturnTypeWithAnnotations, otherSig.ReturnTypeWithAnnotations)) { return false; } return sig.Parameters.SequenceEqual(otherSig.Parameters, AreFunctionPointerParametersEqual); } private bool AreFunctionPointerParametersEqual(ParameterSymbol param, ParameterSymbol otherParam) { ValidateFunctionPointerParamOrReturn(param.TypeWithAnnotations, param.RefKind, param.RefCustomModifiers, allowOut: true); ValidateFunctionPointerParamOrReturn(otherParam.TypeWithAnnotations, otherParam.RefKind, otherParam.RefCustomModifiers, allowOut: true); return param.RefKind == otherParam.RefKind && AreTypesEqual(param.TypeWithAnnotations, otherParam.TypeWithAnnotations); } [Conditional("DEBUG")] private static void ValidateFunctionPointerParamOrReturn(TypeWithAnnotations type, RefKind refKind, ImmutableArray<CustomModifier> refCustomModifiers, bool allowOut) { Debug.Assert(type.CustomModifiers.IsEmpty); Debug.Assert(verifyRefModifiers(refCustomModifiers, refKind, allowOut)); static bool verifyRefModifiers(ImmutableArray<CustomModifier> modifiers, RefKind refKind, bool allowOut) { Debug.Assert(RefKind.RefReadOnly == RefKind.In); switch (refKind) { case RefKind.RefReadOnly: case RefKind.Out when allowOut: return modifiers.Length == 1; default: return modifiers.IsEmpty; } } } private bool ArePropertiesEqual(PropertySymbol property, PropertySymbol other) { Debug.Assert(StringOrdinalComparer.Equals(property.MetadataName, other.MetadataName)); return _comparer.Equals(property.Type, other.Type) && property.RefKind.Equals(other.RefKind) && property.Parameters.SequenceEqual(other.Parameters, AreParametersEqual); } private static bool AreTypeParametersEqual(TypeParameterSymbol type, TypeParameterSymbol other) { Debug.Assert(type.Ordinal == other.Ordinal); Debug.Assert(StringOrdinalComparer.Equals(type.Name, other.Name)); // Comparing constraints is unnecessary: two methods cannot differ by // constraints alone and changing the signature of a method is a rude // edit. Furthermore, comparing constraint types might lead to a cycle. Debug.Assert(type.HasConstructorConstraint == other.HasConstructorConstraint); Debug.Assert(type.HasValueTypeConstraint == other.HasValueTypeConstraint); Debug.Assert(type.HasUnmanagedTypeConstraint == other.HasUnmanagedTypeConstraint); Debug.Assert(type.HasReferenceTypeConstraint == other.HasReferenceTypeConstraint); Debug.Assert(type.ConstraintTypesNoUseSiteDiagnostics.Length == other.ConstraintTypesNoUseSiteDiagnostics.Length); return true; } private bool AreTypesEqual(TypeWithAnnotations type, TypeWithAnnotations other) { Debug.Assert(type.CustomModifiers.IsDefaultOrEmpty); Debug.Assert(other.CustomModifiers.IsDefaultOrEmpty); return AreTypesEqual(type.Type, other.Type); } private bool AreTypesEqual(TypeSymbol type, TypeSymbol other) { if (type.Kind != other.Kind) { return false; } switch (type.Kind) { case SymbolKind.ArrayType: return AreArrayTypesEqual((ArrayTypeSymbol)type, (ArrayTypeSymbol)other); case SymbolKind.PointerType: return ArePointerTypesEqual((PointerTypeSymbol)type, (PointerTypeSymbol)other); case SymbolKind.FunctionPointerType: return AreFunctionPointerTypesEqual((FunctionPointerTypeSymbol)type, (FunctionPointerTypeSymbol)other); case SymbolKind.NamedType: case SymbolKind.ErrorType: return AreNamedTypesEqual((NamedTypeSymbol)type, (NamedTypeSymbol)other); case SymbolKind.TypeParameter: return AreTypeParametersEqual((TypeParameterSymbol)type, (TypeParameterSymbol)other); default: throw ExceptionUtilities.UnexpectedValue(type.Kind); } } private IReadOnlyDictionary<string, ImmutableArray<ISymbolInternal>> GetAllEmittedMembers(ISymbolInternal symbol) { var members = ArrayBuilder<ISymbolInternal>.GetInstance(); if (symbol.Kind == SymbolKind.NamedType) { var type = (NamedTypeSymbol)symbol; members.AddRange(type.GetEventsToEmit()); members.AddRange(type.GetFieldsToEmit()); members.AddRange(type.GetMethodsToEmit()); members.AddRange(type.GetTypeMembers()); members.AddRange(type.GetPropertiesToEmit()); } else { members.AddRange(((NamespaceSymbol)symbol).GetMembers()); } if (_otherSynthesizedMembers != null && _otherSynthesizedMembers.TryGetValue(symbol, out var synthesizedMembers)) { members.AddRange(synthesizedMembers); } var result = members.ToDictionary(s => s.MetadataName, StringOrdinalComparer.Instance); members.Free(); return result; } private sealed class SymbolComparer { private readonly MatchSymbols _matcher; private readonly DeepTranslator? _deepTranslator; public SymbolComparer(MatchSymbols matcher, DeepTranslator? deepTranslator) { Debug.Assert(matcher != null); _matcher = matcher; _deepTranslator = deepTranslator; } public bool Equals(TypeSymbol source, TypeSymbol other) { var visitedSource = (TypeSymbol?)_matcher.Visit(source); var visitedOther = (_deepTranslator != null) ? (TypeSymbol)_deepTranslator.Visit(other) : other; return visitedSource?.Equals(visitedOther, TypeCompareKind.IgnoreDynamicAndTupleNames | TypeCompareKind.IgnoreNullableModifiersForReferenceTypes) == true; } } } internal sealed class DeepTranslator : CSharpSymbolVisitor<Symbol> { private readonly ConcurrentDictionary<Symbol, Symbol> _matches; private readonly NamedTypeSymbol _systemObject; public DeepTranslator(NamedTypeSymbol systemObject) { _matches = new ConcurrentDictionary<Symbol, Symbol>(ReferenceEqualityComparer.Instance); _systemObject = systemObject; } public override Symbol DefaultVisit(Symbol symbol) { // Symbol should have been handled elsewhere. throw ExceptionUtilities.Unreachable; } public override Symbol Visit(Symbol symbol) { return _matches.GetOrAdd(symbol, base.Visit(symbol)); } public override Symbol VisitArrayType(ArrayTypeSymbol symbol) { var translatedElementType = (TypeSymbol)this.Visit(symbol.ElementType); var translatedModifiers = VisitCustomModifiers(symbol.ElementTypeWithAnnotations.CustomModifiers); if (symbol.IsSZArray) { return ArrayTypeSymbol.CreateSZArray(symbol.BaseTypeNoUseSiteDiagnostics.ContainingAssembly, symbol.ElementTypeWithAnnotations.WithTypeAndModifiers(translatedElementType, translatedModifiers)); } return ArrayTypeSymbol.CreateMDArray(symbol.BaseTypeNoUseSiteDiagnostics.ContainingAssembly, symbol.ElementTypeWithAnnotations.WithTypeAndModifiers(translatedElementType, translatedModifiers), symbol.Rank, symbol.Sizes, symbol.LowerBounds); } public override Symbol VisitDynamicType(DynamicTypeSymbol symbol) { return _systemObject; } public override Symbol VisitNamedType(NamedTypeSymbol type) { var originalDef = type.OriginalDefinition; if ((object)originalDef != type) { var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded; var translatedTypeArguments = type.GetAllTypeArguments(ref discardedUseSiteInfo).SelectAsArray((t, v) => t.WithTypeAndModifiers((TypeSymbol)v.Visit(t.Type), v.VisitCustomModifiers(t.CustomModifiers)), this); var translatedOriginalDef = (NamedTypeSymbol)this.Visit(originalDef); var typeMap = new TypeMap(translatedOriginalDef.GetAllTypeParameters(), translatedTypeArguments, allowAlpha: true); return typeMap.SubstituteNamedType(translatedOriginalDef); } Debug.Assert(type.IsDefinition); if (type.IsAnonymousType) { return this.Visit(AnonymousTypeManager.TranslateAnonymousTypeSymbol(type)); } return type; } public override Symbol VisitPointerType(PointerTypeSymbol symbol) { var translatedPointedAtType = (TypeSymbol)this.Visit(symbol.PointedAtType); var translatedModifiers = VisitCustomModifiers(symbol.PointedAtTypeWithAnnotations.CustomModifiers); return new PointerTypeSymbol(symbol.PointedAtTypeWithAnnotations.WithTypeAndModifiers(translatedPointedAtType, translatedModifiers)); } public override Symbol VisitFunctionPointerType(FunctionPointerTypeSymbol symbol) { var sig = symbol.Signature; var translatedReturnType = (TypeSymbol)Visit(sig.ReturnType); var translatedReturnTypeWithAnnotations = sig.ReturnTypeWithAnnotations.WithTypeAndModifiers(translatedReturnType, VisitCustomModifiers(sig.ReturnTypeWithAnnotations.CustomModifiers)); var translatedRefCustomModifiers = VisitCustomModifiers(sig.RefCustomModifiers); var translatedParameterTypes = ImmutableArray<TypeWithAnnotations>.Empty; ImmutableArray<ImmutableArray<CustomModifier>> translatedParamRefCustomModifiers = default; if (sig.ParameterCount > 0) { var translatedParamsBuilder = ArrayBuilder<TypeWithAnnotations>.GetInstance(sig.ParameterCount); var translatedParamRefCustomModifiersBuilder = ArrayBuilder<ImmutableArray<CustomModifier>>.GetInstance(sig.ParameterCount); foreach (var param in sig.Parameters) { var translatedParamType = (TypeSymbol)Visit(param.Type); translatedParamsBuilder.Add(param.TypeWithAnnotations.WithTypeAndModifiers(translatedParamType, VisitCustomModifiers(param.TypeWithAnnotations.CustomModifiers))); translatedParamRefCustomModifiersBuilder.Add(VisitCustomModifiers(param.RefCustomModifiers)); } translatedParameterTypes = translatedParamsBuilder.ToImmutableAndFree(); translatedParamRefCustomModifiers = translatedParamRefCustomModifiersBuilder.ToImmutableAndFree(); } return symbol.SubstituteTypeSymbol(translatedReturnTypeWithAnnotations, translatedParameterTypes, translatedRefCustomModifiers, translatedParamRefCustomModifiers); } public override Symbol VisitTypeParameter(TypeParameterSymbol symbol) { return symbol; } private ImmutableArray<CustomModifier> VisitCustomModifiers(ImmutableArray<CustomModifier> modifiers) { return modifiers.SelectAsArray(VisitCustomModifier); } private CustomModifier VisitCustomModifier(CustomModifier modifier) { var translatedType = (NamedTypeSymbol)this.Visit(((CSharpCustomModifier)modifier).ModifierSymbol); Debug.Assert((object)translatedType != null); return modifier.IsOptional ? CSharpCustomModifier.CreateOptional(translatedType) : CSharpCustomModifier.CreateRequired(translatedType); } } } }
1
dotnet/roslyn
55,428
Test adding nested namespaces
Fixes https://github.com/dotnet/roslyn/issues/54939 The "workaround" that's already implemented is actually the correct behavior.
tmat
2021-08-05T01:19:03Z
2021-08-11T18:38:54Z
bc874ebc5111a2a33221409f895953b1536f6612
1cbbd423e17b186a8f1de89febb4db9a386d180d
Test adding nested namespaces. Fixes https://github.com/dotnet/roslyn/issues/54939 The "workaround" that's already implemented is actually the correct behavior.
./src/Compilers/CSharp/Test/Emit/Emit/EditAndContinue/EditAndContinueTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.IO; using System.Linq; using System.Reflection.Metadata; using System.Reflection.Metadata.Ecma335; using Microsoft.CodeAnalysis.CodeGen; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.CSharp.UnitTests; using Microsoft.CodeAnalysis.Emit; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.EditAndContinue.UnitTests { /// <summary> /// Tip: debug EncVariableSlotAllocator.TryGetPreviousClosure or other TryGet methods to figure out missing markers in your test. /// </summary> public class EditAndContinueTests : EditAndContinueTestBase { private static IEnumerable<string> DumpTypeRefs(MetadataReader[] readers) { var currentGenerationReader = readers.Last(); foreach (var typeRefHandle in currentGenerationReader.TypeReferences) { var typeRef = currentGenerationReader.GetTypeReference(typeRefHandle); yield return $"[0x{MetadataTokens.GetToken(typeRef.ResolutionScope):x8}] {readers.GetString(typeRef.Namespace)}.{readers.GetString(typeRef.Name)}"; } } [Fact] public void DeltaHeapsStartWithEmptyItem() { var source0 = @"class C { static string F() { return null; } }"; var source1 = @"class C { static string F() { return ""a""; } }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var method0 = compilation0.GetMember<MethodSymbol>("C.F"); var method1 = compilation1.GetMember<MethodSymbol>("C.F"); var bytes0 = compilation0.EmitToArray(); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var reader0 = md0.MetadataReader; var diff1 = compilation1.EmitDifference( EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider), ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1))); using var md1 = diff1.GetMetadata(); var reader1 = md1.Reader; var s = MetadataTokens.StringHandle(0); Assert.Equal("", reader1.GetString(s)); var b = MetadataTokens.BlobHandle(0); Assert.Equal(0, reader1.GetBlobBytes(b).Length); var us = MetadataTokens.UserStringHandle(0); Assert.Equal("", reader1.GetUserString(us)); } [Fact] public void Delta_AssemblyDefTable() { var source0 = @"public class C { public static void F() { System.Console.WriteLine(1); } }"; var source1 = @"public class C { public static void F() { System.Console.WriteLine(2); } }"; var compilation0 = CreateCompilationWithMscorlib45(source0, options: ComSafeDebugDll); var compilation1 = compilation0.WithSource(source1); var f0 = compilation0.GetMember<MethodSymbol>("C.F"); var f1 = compilation1.GetMember<MethodSymbol>("C.F"); var v0 = CompileAndVerify(compilation0); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, f0, f1, preserveLocalVariables: true))); // AssemblyDef record is not emitted to delta since changes in assembly identity are not allowed: Assert.True(md0.MetadataReader.IsAssembly); Assert.False(diff1.GetMetadata().Reader.IsAssembly); } [Fact] public void SemanticErrors_MethodBody() { var source0 = MarkedSource(@" class C { static void E() { int x = 1; System.Console.WriteLine(x); } static void G() { System.Console.WriteLine(1); } }"); var source1 = MarkedSource(@" class C { static void E() { int x = Unknown(2); System.Console.WriteLine(x); } static void G() { System.Console.WriteLine(2); } }"); var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll); var compilation1 = compilation0.WithSource(source1.Tree); var e0 = compilation0.GetMember<MethodSymbol>("C.E"); var e1 = compilation1.GetMember<MethodSymbol>("C.E"); var g0 = compilation0.GetMember<MethodSymbol>("C.G"); var g1 = compilation1.GetMember<MethodSymbol>("C.G"); var v0 = CompileAndVerify(compilation0); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); // Semantic errors are reported only for the bodies of members being emitted. var diffError = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, e0, e1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true))); diffError.EmitResult.Diagnostics.Verify( // (6,17): error CS0103: The name 'Unknown' does not exist in the current context // int x = Unknown(2); Diagnostic(ErrorCode.ERR_NameNotInContext, "Unknown").WithArguments("Unknown").WithLocation(6, 17)); var diffGood = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, g0, g1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true))); diffGood.EmitResult.Diagnostics.Verify(); diffGood.VerifyIL(@"C.G", @" { // Code size 9 (0x9) .maxstack 1 IL_0000: nop IL_0001: ldc.i4.2 IL_0002: call ""void System.Console.WriteLine(int)"" IL_0007: nop IL_0008: ret } "); } [Fact] public void SemanticErrors_Declaration() { var source0 = MarkedSource(@" class C { static void G() { System.Console.WriteLine(1); } } "); var source1 = MarkedSource(@" class C { static void G() { System.Console.WriteLine(2); } } class Bad : Bad { } "); var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll); var compilation1 = compilation0.WithSource(source1.Tree); var g0 = compilation0.GetMember<MethodSymbol>("C.G"); var g1 = compilation1.GetMember<MethodSymbol>("C.G"); var v0 = CompileAndVerify(compilation0); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); var diff = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, g0, g1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true))); // All declaration errors are reported regardless of what member do we emit. diff.EmitResult.Diagnostics.Verify( // (10,7): error CS0146: Circular base type dependency involving 'Bad' and 'Bad' // class Bad : Bad Diagnostic(ErrorCode.ERR_CircularBase, "Bad").WithArguments("Bad", "Bad").WithLocation(10, 7)); } [Fact] public void ModifyMethod() { var source0 = @"class C { static void Main() { } static string F() { return null; } }"; var source1 = @"class C { static void Main() { } static string F() { return string.Empty; } }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugExe); var compilation1 = compilation0.WithSource(source1); var method0 = compilation0.GetMember<MethodSymbol>("C.F"); // Verify full metadata contains expected rows. var bytes0 = compilation0.EmitToArray(); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var reader0 = md0.MetadataReader; CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "C"); CheckNames(reader0, reader0.GetMethodDefNames(), "Main", "F", ".ctor"); CheckNames(reader0, reader0.GetMemberRefNames(), /*CompilationRelaxationsAttribute.*/".ctor", /*RuntimeCompatibilityAttribute.*/".ctor", /*Object.*/".ctor", /*DebuggableAttribute*/".ctor"); var generation0 = EmitBaseline.CreateInitialBaseline( md0, EmptyLocalsProvider); var method1 = compilation1.GetMember<MethodSymbol>("C.F"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1))); // Verify delta metadata contains expected rows. using var md1 = diff1.GetMetadata(); var reader1 = md1.Reader; var readers = new[] { reader0, reader1 }; EncValidation.VerifyModuleMvid(1, reader0, reader1); CheckNames(readers, reader1.GetTypeDefNames()); CheckNames(readers, reader1.GetMethodDefNames(), "F"); CheckNames(readers, reader1.GetMemberRefNames(), /*String.*/"Empty"); CheckEncLog(reader1, Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default), Row(5, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(6, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(7, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(2, TableIndex.StandAloneSig, EditAndContinueOperation.Default), Row(2, TableIndex.MethodDef, EditAndContinueOperation.Default)); // C.F CheckEncMap(reader1, Handle(6, TableIndex.TypeRef), Handle(7, TableIndex.TypeRef), Handle(2, TableIndex.MethodDef), Handle(5, TableIndex.MemberRef), Handle(2, TableIndex.StandAloneSig), Handle(2, TableIndex.AssemblyRef)); } [Fact] public void ModifyMethod_RenameParameter() { var source0 = @"class C { static string F(int a) { return a.ToString(); } }"; var source1 = @"class C { static string F(int x) { return x.ToString(); } }"; var source2 = @"class C { static string F(int b) { return b.ToString(); } }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var compilation2 = compilation1.WithSource(source2); var method0 = compilation0.GetMember<MethodSymbol>("C.F"); // Verify full metadata contains expected rows. var bytes0 = compilation0.EmitToArray(EmitOptions.Default.WithDebugInformationFormat(DebugInformationFormat.PortablePdb)); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var reader0 = md0.MetadataReader; CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "C"); CheckNames(reader0, reader0.GetMethodDefNames(), "F", ".ctor"); CheckNames(reader0, reader0.GetParameterDefNames(), "a"); var generation0 = EmitBaseline.CreateInitialBaseline( md0, EmptyLocalsProvider); var method1 = compilation1.GetMember<MethodSymbol>("C.F"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1))); // Verify delta metadata contains expected rows. using var md1 = diff1.GetMetadata(); var reader1 = md1.Reader; var readers = new[] { reader0, reader1 }; EncValidation.VerifyModuleMvid(1, reader0, reader1); CheckNames(readers, reader1.GetTypeDefNames()); CheckNames(readers, reader1.GetMethodDefNames(), "F"); CheckNames(readers, reader1.GetParameterDefNames(), "x"); CheckEncLogDefinitions(reader1, Row(2, TableIndex.StandAloneSig, EditAndContinueOperation.Default), Row(1, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(1, TableIndex.Param, EditAndContinueOperation.Default)); CheckEncMapDefinitions(reader1, Handle(1, TableIndex.MethodDef), Handle(1, TableIndex.Param), Handle(2, TableIndex.StandAloneSig)); var method2 = compilation2.GetMember<MethodSymbol>("C.F"); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method1, method2))); // Verify delta metadata contains expected rows. using var md2 = diff2.GetMetadata(); var reader2 = md2.Reader; readers = new[] { reader0, reader1, reader2 }; CheckNames(readers, reader2.GetTypeDefNames()); CheckNames(readers, reader2.GetMethodDefNames(), "F"); CheckNames(readers, reader2.GetMemberRefNames(), "ToString"); CheckNames(readers, reader2.GetParameterDefNames(), "b"); CheckEncLogDefinitions(reader2, Row(3, TableIndex.StandAloneSig, EditAndContinueOperation.Default), Row(1, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(1, TableIndex.Param, EditAndContinueOperation.Default)); CheckEncMapDefinitions(reader2, Handle(1, TableIndex.MethodDef), Handle(1, TableIndex.Param), Handle(3, TableIndex.StandAloneSig)); } [CompilerTrait(CompilerFeature.Tuples)] [Fact] public void ModifyMethod_WithTuples() { var source0 = @"class C { static void Main() { } static (int, int) F() { return (1, 2); } }"; var source1 = @"class C { static void Main() { } static (int, int) F() { return (2, 3); } }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugExe, targetFramework: TargetFramework.NetStandard20); var compilation1 = compilation0.WithSource(source1); var bytes0 = compilation0.EmitToArray(); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var reader0 = md0.MetadataReader; var method0 = compilation0.GetMember<MethodSymbol>("C.F"); var generation0 = EmitBaseline.CreateInitialBaseline( md0, EmptyLocalsProvider); var method1 = compilation1.GetMember<MethodSymbol>("C.F"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1))); // Verify delta metadata contains expected rows. using var md1 = diff1.GetMetadata(); var reader1 = md1.Reader; var readers = new[] { reader0, reader1 }; EncValidation.VerifyModuleMvid(1, reader0, reader1); CheckNames(readers, reader1.GetTypeDefNames()); CheckNames(readers, reader1.GetMethodDefNames(), "F"); CheckNames(readers, reader1.GetMemberRefNames(), /*System.ValueTuple.*/".ctor"); CheckEncLog(reader1, Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default), Row(6, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(7, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(8, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(2, TableIndex.TypeSpec, EditAndContinueOperation.Default), Row(2, TableIndex.StandAloneSig, EditAndContinueOperation.Default), Row(2, TableIndex.MethodDef, EditAndContinueOperation.Default)); // C.F CheckEncMap(reader1, Handle(7, TableIndex.TypeRef), Handle(8, TableIndex.TypeRef), Handle(2, TableIndex.MethodDef), Handle(6, TableIndex.MemberRef), Handle(2, TableIndex.StandAloneSig), Handle(2, TableIndex.TypeSpec), Handle(2, TableIndex.AssemblyRef)); } [Fact] public void ModifyMethod_WithAttributes1() { var source0 = @"class C { static void Main() { } [System.ComponentModel.Description(""The F method"")] static string F() { return null; } }"; var source1 = @"class C { static void Main() { } [System.ComponentModel.Description(""The F method"")] static string F() { return string.Empty; } }"; var source2 = @"[System.ComponentModel.Browsable(false)] class C { static void Main() { } [System.ComponentModel.Description(""The F method""), System.ComponentModel.Category(""Methods"")] static string F() { return string.Empty; } }"; var source3 = @"[System.ComponentModel.Browsable(false)] class C { static void Main() { } [System.ComponentModel.Browsable(false), System.ComponentModel.Description(""The F method""), System.ComponentModel.Category(""Methods"")] static string F() { return string.Empty; } }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugExe, targetFramework: TargetFramework.NetStandard20); var compilation1 = compilation0.WithSource(source1); var compilation2 = compilation1.WithSource(source2); var compilation3 = compilation2.WithSource(source3); var method0 = compilation0.GetMember<MethodSymbol>("C.F"); // Verify full metadata contains expected rows. var bytes0 = compilation0.EmitToArray(); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var reader0 = md0.MetadataReader; CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "C"); CheckNames(reader0, reader0.GetMethodDefNames(), "Main", "F", ".ctor"); CheckNames(reader0, reader0.GetMemberRefNames(), /*CompilationRelaxationsAttribute.*/".ctor", /*RuntimeCompatibilityAttribute.*/".ctor", /*Object.*/".ctor", /*DebuggableAttribute*/".ctor", /*DescriptionAttribute*/".ctor"); Assert.Equal(4, reader0.CustomAttributes.Count); var generation0 = EmitBaseline.CreateInitialBaseline( md0, EmptyLocalsProvider); var method1 = compilation1.GetMember<MethodSymbol>("C.F"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1))); // Verify delta metadata contains expected rows. using var md1 = diff1.GetMetadata(); var reader1 = md1.Reader; var readers = new[] { reader0, reader1 }; EncValidation.VerifyModuleMvid(1, reader0, reader1); CheckNames(readers, reader1.GetTypeDefNames()); CheckNames(readers, reader1.GetMethodDefNames(), "F"); CheckNames(readers, reader1.GetMemberRefNames(), /*DescriptionAttribute*/".ctor", /*String.*/"Empty"); Assert.Equal(1, reader1.CustomAttributes.Count); CheckEncLog(reader1, Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default), Row(6, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(7, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(7, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(8, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(9, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(2, TableIndex.StandAloneSig, EditAndContinueOperation.Default), Row(2, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(4, TableIndex.CustomAttribute, EditAndContinueOperation.Default)); // Row 4, so updating existing CustomAttribute CheckEncMap(reader1, Handle(7, TableIndex.TypeRef), Handle(8, TableIndex.TypeRef), Handle(9, TableIndex.TypeRef), Handle(2, TableIndex.MethodDef), Handle(6, TableIndex.MemberRef), Handle(7, TableIndex.MemberRef), Handle(4, TableIndex.CustomAttribute), Handle(2, TableIndex.StandAloneSig), Handle(2, TableIndex.AssemblyRef)); var method2 = compilation2.GetMember<MethodSymbol>("C.F"); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, compilation1.GetMember("C"), compilation2.GetMember("C")), SemanticEdit.Create(SemanticEditKind.Update, method1, method2))); // Verify delta metadata contains expected rows. using var md2 = diff2.GetMetadata(); var reader2 = md2.Reader; readers = new[] { reader0, reader1, reader2 }; CheckNames(readers, reader2.GetTypeDefNames(), "C"); CheckNames(readers, reader2.GetMethodDefNames(), "F"); CheckNames(readers, reader2.GetMemberRefNames(), /*DescriptionAttribute*/".ctor", /*BrowsableAttribute*/".ctor", /*CategoryAttribute*/".ctor", /*String.*/"Empty"); Assert.Equal(3, reader2.CustomAttributes.Count); CheckEncLog(reader2, Row(3, TableIndex.AssemblyRef, EditAndContinueOperation.Default), Row(8, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(9, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(10, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(11, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(10, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(11, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(12, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(13, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(14, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(3, TableIndex.StandAloneSig, EditAndContinueOperation.Default), Row(2, TableIndex.TypeDef, EditAndContinueOperation.Default), Row(2, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(4, TableIndex.CustomAttribute, EditAndContinueOperation.Default), // Row 4, updating the existing custom attribute Row(5, TableIndex.CustomAttribute, EditAndContinueOperation.Default), // Row 5, adding a new CustomAttribute Row(6, TableIndex.CustomAttribute, EditAndContinueOperation.Default)); // Row 6 adding a new CustomAttribute CheckEncMap(reader2, Handle(10, TableIndex.TypeRef), Handle(11, TableIndex.TypeRef), Handle(12, TableIndex.TypeRef), Handle(13, TableIndex.TypeRef), Handle(14, TableIndex.TypeRef), Handle(2, TableIndex.TypeDef), Handle(2, TableIndex.MethodDef), Handle(8, TableIndex.MemberRef), Handle(9, TableIndex.MemberRef), Handle(10, TableIndex.MemberRef), Handle(11, TableIndex.MemberRef), Handle(4, TableIndex.CustomAttribute), Handle(5, TableIndex.CustomAttribute), Handle(6, TableIndex.CustomAttribute), Handle(3, TableIndex.StandAloneSig), Handle(3, TableIndex.AssemblyRef)); var method3 = compilation3.GetMember<MethodSymbol>("C.F"); var diff3 = compilation3.EmitDifference( diff2.NextGeneration, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method2, method3))); // Verify delta metadata contains expected rows. using var md3 = diff3.GetMetadata(); var reader3 = md3.Reader; readers = new[] { reader0, reader1, reader2, reader3 }; CheckNames(readers, reader3.GetTypeDefNames()); CheckNames(readers, reader3.GetMethodDefNames(), "F"); CheckNames(readers, reader3.GetMemberRefNames(), /*BrowsableAttribute*/".ctor", /*DescriptionAttribute*/".ctor", /*CategoryAttribute*/".ctor", /*String.*/"Empty"); CheckEncLog(reader3, Row(4, TableIndex.AssemblyRef, EditAndContinueOperation.Default), Row(12, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(13, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(14, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(15, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(15, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(16, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(17, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(18, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(19, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(4, TableIndex.StandAloneSig, EditAndContinueOperation.Default), Row(2, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(4, TableIndex.CustomAttribute, EditAndContinueOperation.Default), // Row 4, updating the existing custom attribute Row(5, TableIndex.CustomAttribute, EditAndContinueOperation.Default), // Row 5, updating a row that was new in Generation 2 Row(7, TableIndex.CustomAttribute, EditAndContinueOperation.Default)); // Row 7, adding a new CustomAttribute, and skipping row 6 which is not for the method being emitted CheckEncMap(reader3, Handle(15, TableIndex.TypeRef), Handle(16, TableIndex.TypeRef), Handle(17, TableIndex.TypeRef), Handle(18, TableIndex.TypeRef), Handle(19, TableIndex.TypeRef), Handle(2, TableIndex.MethodDef), Handle(12, TableIndex.MemberRef), Handle(13, TableIndex.MemberRef), Handle(14, TableIndex.MemberRef), Handle(15, TableIndex.MemberRef), Handle(4, TableIndex.CustomAttribute), Handle(5, TableIndex.CustomAttribute), Handle(7, TableIndex.CustomAttribute), Handle(4, TableIndex.StandAloneSig), Handle(4, TableIndex.AssemblyRef)); } [Fact] public void ModifyMethod_WithAttributes2() { var source0 = @"[System.ComponentModel.Browsable(false)] class C { static void Main() { } [System.ComponentModel.Description(""The F method"")] static string F() { return null; } } [System.ComponentModel.Browsable(false)] class D { [System.ComponentModel.Description(""A"")] static string A() { return null; } } "; var source1 = @" [System.ComponentModel.Browsable(false)] class C { static void Main() { } [System.ComponentModel.Description(""The F method""), System.ComponentModel.Browsable(false), System.ComponentModel.Category(""Methods"")] static string F() { return null; } } [System.ComponentModel.Browsable(false)] class D { [System.ComponentModel.Description(""A""), System.ComponentModel.Category(""Methods"")] static string A() { return null; } } "; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugExe, targetFramework: TargetFramework.NetStandard20); var compilation1 = compilation0.WithSource(source1); var method0_1 = compilation0.GetMember<MethodSymbol>("C.F"); var method0_2 = compilation0.GetMember<MethodSymbol>("D.A"); // Verify full metadata contains expected rows. var bytes0 = compilation0.EmitToArray(); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var reader0 = md0.MetadataReader; CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "C", "D"); CheckNames(reader0, reader0.GetMethodDefNames(), "Main", "F", ".ctor", "A", ".ctor"); CheckNames(reader0, reader0.GetMemberRefNames(), /*CompilationRelaxationsAttribute.*/".ctor", /*RuntimeCompatibilityAttribute.*/".ctor", /*Object.*/".ctor", /*DebuggableAttribute*/".ctor", /*DescriptionAttribute*/".ctor", /*BrowsableAttribute*/".ctor"); CheckAttributes(reader0, new CustomAttributeRow(Handle(1, TableIndex.Assembly), Handle(1, TableIndex.MemberRef)), new CustomAttributeRow(Handle(1, TableIndex.Assembly), Handle(2, TableIndex.MemberRef)), new CustomAttributeRow(Handle(1, TableIndex.Assembly), Handle(3, TableIndex.MemberRef)), new CustomAttributeRow(Handle(2, TableIndex.MethodDef), Handle(5, TableIndex.MemberRef)), new CustomAttributeRow(Handle(2, TableIndex.TypeDef), Handle(4, TableIndex.MemberRef)), new CustomAttributeRow(Handle(3, TableIndex.TypeDef), Handle(4, TableIndex.MemberRef)), new CustomAttributeRow(Handle(4, TableIndex.MethodDef), Handle(5, TableIndex.MemberRef))); var generation0 = EmitBaseline.CreateInitialBaseline( md0, EmptyLocalsProvider); var method1_1 = compilation1.GetMember<MethodSymbol>("C.F"); var method1_2 = compilation1.GetMember<MethodSymbol>("D.A"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, method0_1, method1_1), SemanticEdit.Create(SemanticEditKind.Update, method0_2, method1_2))); // Verify delta metadata contains expected rows. using var md1 = diff1.GetMetadata(); var reader1 = md1.Reader; var readers = new[] { reader0, reader1 }; EncValidation.VerifyModuleMvid(1, reader0, reader1); CheckNames(readers, reader1.GetTypeDefNames()); CheckNames(readers, reader1.GetMethodDefNames(), "F", "A"); CheckNames(readers, reader1.GetMemberRefNames(), /*BrowsableAttribute*/".ctor", /*CategoryAttribute*/".ctor", /*DescriptionAttribute*/".ctor"); CheckAttributes(reader1, new CustomAttributeRow(Handle(2, TableIndex.MethodDef), Handle(8, TableIndex.MemberRef)), new CustomAttributeRow(Handle(2, TableIndex.MethodDef), Handle(7, TableIndex.MemberRef)), new CustomAttributeRow(Handle(2, TableIndex.MethodDef), Handle(9, TableIndex.MemberRef)), new CustomAttributeRow(Handle(4, TableIndex.MethodDef), Handle(8, TableIndex.MemberRef)), new CustomAttributeRow(Handle(4, TableIndex.MethodDef), Handle(9, TableIndex.MemberRef))); CheckEncLog(reader1, Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default), Row(7, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(8, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(9, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(8, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(9, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(10, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(11, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(2, TableIndex.StandAloneSig, EditAndContinueOperation.Default), Row(2, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(4, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(4, TableIndex.CustomAttribute, EditAndContinueOperation.Default), // update existing row Row(8, TableIndex.CustomAttribute, EditAndContinueOperation.Default), // add new row Row(9, TableIndex.CustomAttribute, EditAndContinueOperation.Default), // add new row Row(7, TableIndex.CustomAttribute, EditAndContinueOperation.Default), // update existing row Row(10, TableIndex.CustomAttribute, EditAndContinueOperation.Default)); // add new row CheckEncMap(reader1, Handle(8, TableIndex.TypeRef), Handle(9, TableIndex.TypeRef), Handle(10, TableIndex.TypeRef), Handle(11, TableIndex.TypeRef), Handle(2, TableIndex.MethodDef), Handle(4, TableIndex.MethodDef), Handle(7, TableIndex.MemberRef), Handle(8, TableIndex.MemberRef), Handle(9, TableIndex.MemberRef), Handle(4, TableIndex.CustomAttribute), Handle(7, TableIndex.CustomAttribute), Handle(8, TableIndex.CustomAttribute), Handle(9, TableIndex.CustomAttribute), Handle(10, TableIndex.CustomAttribute), Handle(2, TableIndex.StandAloneSig), Handle(2, TableIndex.AssemblyRef)); } [Fact] public void ModifyMethod_DeleteAttributes1() { var source0 = @"class C { static void Main() { } [System.ComponentModel.Description(""The F method"")] static string F() { return null; } }"; var source1 = @"class C { static void Main() { } static string F() { return string.Empty; } }"; var source2 = @"class C { static void Main() { } [System.ComponentModel.Description(""The F method"")] static string F() { return string.Empty; } }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugExe, targetFramework: TargetFramework.NetStandard20); var compilation1 = compilation0.WithSource(source1); var compilation2 = compilation1.WithSource(source2); var method0 = compilation0.GetMember<MethodSymbol>("C.F"); // Verify full metadata contains expected rows. var bytes0 = compilation0.EmitToArray(); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var reader0 = md0.MetadataReader; CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "C"); CheckNames(reader0, reader0.GetMethodDefNames(), "Main", "F", ".ctor"); CheckNames(reader0, reader0.GetMemberRefNames(), /*CompilationRelaxationsAttribute.*/".ctor", /*RuntimeCompatibilityAttribute.*/".ctor", /*Object.*/".ctor", /*DebuggableAttribute*/".ctor", /*DescriptionAttribute*/".ctor"); CheckAttributes(reader0, new CustomAttributeRow(Handle(1, TableIndex.Assembly), Handle(1, TableIndex.MemberRef)), new CustomAttributeRow(Handle(1, TableIndex.Assembly), Handle(2, TableIndex.MemberRef)), new CustomAttributeRow(Handle(1, TableIndex.Assembly), Handle(3, TableIndex.MemberRef)), new CustomAttributeRow(Handle(2, TableIndex.MethodDef), Handle(4, TableIndex.MemberRef))); var generation0 = EmitBaseline.CreateInitialBaseline( md0, EmptyLocalsProvider); var method1 = compilation1.GetMember<MethodSymbol>("C.F"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1))); // Verify delta metadata contains expected rows. using var md1 = diff1.GetMetadata(); var reader1 = md1.Reader; var readers = new[] { reader0, reader1 }; EncValidation.VerifyModuleMvid(1, reader0, reader1); CheckNames(readers, reader1.GetTypeDefNames()); CheckNames(readers, reader1.GetMethodDefNames(), "F"); CheckNames(readers, reader1.GetMemberRefNames(), /*String.*/"Empty"); CheckAttributes(reader1, new CustomAttributeRow(Handle(0, TableIndex.MethodDef), Handle(0, TableIndex.MemberRef))); // Parent row id is 0, signifying a delete CheckEncLog(reader1, Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default), Row(6, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(7, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(8, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(2, TableIndex.StandAloneSig, EditAndContinueOperation.Default), Row(2, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(4, TableIndex.CustomAttribute, EditAndContinueOperation.Default)); // Row 4, so updating existing CustomAttribute CheckEncMap(reader1, Handle(7, TableIndex.TypeRef), Handle(8, TableIndex.TypeRef), Handle(2, TableIndex.MethodDef), Handle(6, TableIndex.MemberRef), Handle(4, TableIndex.CustomAttribute), Handle(2, TableIndex.StandAloneSig), Handle(2, TableIndex.AssemblyRef)); var method2 = compilation2.GetMember<MethodSymbol>("C.F"); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method1, method2))); // Verify delta metadata contains expected rows. using var md2 = diff2.GetMetadata(); var reader2 = md2.Reader; readers = new[] { reader0, reader1, reader2 }; EncValidation.VerifyModuleMvid(2, reader1, reader2); CheckNames(readers, reader2.GetTypeDefNames()); CheckNames(readers, reader2.GetMethodDefNames(), "F"); CheckNames(readers, reader2.GetMemberRefNames(), /*DescriptionAttribute*/".ctor", /*String.*/"Empty"); CheckAttributes(reader2, new CustomAttributeRow(Handle(2, TableIndex.MethodDef), Handle(7, TableIndex.MemberRef))); CheckEncLog(reader2, Row(3, TableIndex.AssemblyRef, EditAndContinueOperation.Default), Row(7, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(8, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(9, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(10, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(11, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(3, TableIndex.StandAloneSig, EditAndContinueOperation.Default), Row(2, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(4, TableIndex.CustomAttribute, EditAndContinueOperation.Default)); // Row 4, updating the original row back to a real one CheckEncMap(reader2, Handle(9, TableIndex.TypeRef), Handle(10, TableIndex.TypeRef), Handle(11, TableIndex.TypeRef), Handle(2, TableIndex.MethodDef), Handle(7, TableIndex.MemberRef), Handle(8, TableIndex.MemberRef), Handle(4, TableIndex.CustomAttribute), Handle(3, TableIndex.StandAloneSig), Handle(3, TableIndex.AssemblyRef)); } [Fact] public void ModifyMethod_DeleteAttributes2() { var source0 = @"class C { static void Main() { } static string F() { return null; } }"; var source1 = @"class C { static void Main() { } [System.ComponentModel.Description(""The F method"")] static string F() { return string.Empty; } }"; var source2 = source0; // Remove the attribute we just added var source3 = source1; // Add the attribute back again var compilation0 = CreateCompilation(source0, options: TestOptions.DebugExe, targetFramework: TargetFramework.NetStandard20); var compilation1 = compilation0.WithSource(source1); var compilation2 = compilation1.WithSource(source2); var compilation3 = compilation1.WithSource(source3); var method0 = compilation0.GetMember<MethodSymbol>("C.F"); // Verify full metadata contains expected rows. var bytes0 = compilation0.EmitToArray(); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var reader0 = md0.MetadataReader; CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "C"); CheckNames(reader0, reader0.GetMethodDefNames(), "Main", "F", ".ctor"); CheckNames(reader0, reader0.GetMemberRefNames(), /*CompilationRelaxationsAttribute.*/".ctor", /*RuntimeCompatibilityAttribute.*/".ctor", /*Object.*/".ctor", /*DebuggableAttribute*/".ctor"); CheckAttributes(reader0, new CustomAttributeRow(Handle(1, TableIndex.Assembly), Handle(1, TableIndex.MemberRef)), new CustomAttributeRow(Handle(1, TableIndex.Assembly), Handle(2, TableIndex.MemberRef)), new CustomAttributeRow(Handle(1, TableIndex.Assembly), Handle(3, TableIndex.MemberRef))); var generation0 = EmitBaseline.CreateInitialBaseline( md0, EmptyLocalsProvider); var method1 = compilation1.GetMember<MethodSymbol>("C.F"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1))); // Verify delta metadata contains expected rows. using var md1 = diff1.GetMetadata(); var reader1 = md1.Reader; var readers = new[] { reader0, reader1 }; EncValidation.VerifyModuleMvid(1, reader0, reader1); CheckNames(readers, reader1.GetTypeDefNames()); CheckNames(readers, reader1.GetMethodDefNames(), "F"); CheckNames(readers, reader1.GetMemberRefNames(), /*DescriptionAttribute*/".ctor", /*String.*/"Empty"); CheckAttributes(reader1, new CustomAttributeRow(Handle(2, TableIndex.MethodDef), Handle(5, TableIndex.MemberRef))); CheckEncLog(reader1, Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default), Row(5, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(6, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(6, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(7, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(8, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(2, TableIndex.StandAloneSig, EditAndContinueOperation.Default), Row(2, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(4, TableIndex.CustomAttribute, EditAndContinueOperation.Default)); // Row 4, so adding a new CustomAttribute CheckEncMap(reader1, Handle(6, TableIndex.TypeRef), Handle(7, TableIndex.TypeRef), Handle(8, TableIndex.TypeRef), Handle(2, TableIndex.MethodDef), Handle(5, TableIndex.MemberRef), Handle(6, TableIndex.MemberRef), Handle(4, TableIndex.CustomAttribute), Handle(2, TableIndex.StandAloneSig), Handle(2, TableIndex.AssemblyRef)); var method2 = compilation2.GetMember<MethodSymbol>("C.F"); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, method1, method2))); // Verify delta metadata contains expected rows. using var md2 = diff2.GetMetadata(); var reader2 = md2.Reader; readers = new[] { reader0, reader1, reader2 }; CheckNames(readers, reader2.GetTypeDefNames()); CheckNames(readers, reader2.GetMethodDefNames(), "F"); CheckNames(readers, reader2.GetMemberRefNames()); CheckAttributes(reader2, new CustomAttributeRow(Handle(0, TableIndex.MethodDef), Handle(0, TableIndex.MemberRef))); // 0, delete CheckEncLog(reader2, Row(3, TableIndex.AssemblyRef, EditAndContinueOperation.Default), Row(9, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(3, TableIndex.StandAloneSig, EditAndContinueOperation.Default), Row(2, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(4, TableIndex.CustomAttribute, EditAndContinueOperation.Default)); // Row 4, so updating existing CustomAttribute CheckEncMap(reader2, Handle(9, TableIndex.TypeRef), Handle(2, TableIndex.MethodDef), Handle(4, TableIndex.CustomAttribute), Handle(3, TableIndex.StandAloneSig), Handle(3, TableIndex.AssemblyRef)); var method3 = compilation3.GetMember<MethodSymbol>("C.F"); var diff3 = compilation3.EmitDifference( diff2.NextGeneration, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, method2, method3))); // Verify delta metadata contains expected rows. using var md3 = diff3.GetMetadata(); var reader3 = md3.Reader; readers = new[] { reader0, reader1, reader2, reader3 }; CheckNames(readers, reader3.GetTypeDefNames()); CheckNames(readers, reader3.GetMethodDefNames(), "F"); CheckNames(readers, reader3.GetMemberRefNames(), /*DescriptionAttribute*/".ctor", /*String.*/"Empty"); CheckAttributes(reader3, new CustomAttributeRow(Handle(2, TableIndex.MethodDef), Handle(7, TableIndex.MemberRef))); CheckEncLog(reader3, Row(4, TableIndex.AssemblyRef, EditAndContinueOperation.Default), Row(7, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(8, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(10, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(11, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(12, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(4, TableIndex.StandAloneSig, EditAndContinueOperation.Default), Row(2, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(4, TableIndex.CustomAttribute, EditAndContinueOperation.Default)); // Row 4, update the previously deleted row CheckEncMap(reader3, Handle(10, TableIndex.TypeRef), Handle(11, TableIndex.TypeRef), Handle(12, TableIndex.TypeRef), Handle(2, TableIndex.MethodDef), Handle(7, TableIndex.MemberRef), Handle(8, TableIndex.MemberRef), Handle(4, TableIndex.CustomAttribute), Handle(4, TableIndex.StandAloneSig), Handle(4, TableIndex.AssemblyRef)); } [WorkItem(962219, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/962219")] [Fact] public void PartialMethod() { var source = @"partial class C { static partial void M1(); static partial void M2(); static partial void M3(); static partial void M1() { } static partial void M2() { } }"; var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source); var bytes0 = compilation0.EmitToArray(); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var reader0 = md0.MetadataReader; CheckNames(reader0, reader0.GetMethodDefNames(), "M1", "M2", ".ctor"); var method0 = compilation0.GetMember<MethodSymbol>("C.M2").PartialImplementationPart; var method1 = compilation1.GetMember<MethodSymbol>("C.M2").PartialImplementationPart; var generation0 = EmitBaseline.CreateInitialBaseline( md0, EmptyLocalsProvider); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1))); var methods = diff1.TestData.GetMethodsByName(); Assert.Equal(1, methods.Count); Assert.True(methods.ContainsKey("C.M2()")); using var md1 = diff1.GetMetadata(); var reader1 = md1.Reader; var readers = new[] { reader0, reader1 }; EncValidation.VerifyModuleMvid(1, reader0, reader1); CheckNames(readers, reader1.GetMethodDefNames(), "M2"); CheckEncLog(reader1, Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default), Row(6, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(2, TableIndex.MethodDef, EditAndContinueOperation.Default)); CheckEncMap(reader1, Handle(6, TableIndex.TypeRef), Handle(2, TableIndex.MethodDef), Handle(2, TableIndex.AssemblyRef)); } [Fact] public void Method_WithAttributes_Add() { var source0 = @"class C { static void Main() { } }"; var source1 = @"class C { static void Main() { } [System.ComponentModel.Description(""The F method"")] static string F() { return string.Empty; } }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugExe, targetFramework: TargetFramework.NetStandard20); var compilation1 = compilation0.WithSource(source1); // Verify full metadata contains expected rows. var bytes0 = compilation0.EmitToArray(); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var reader0 = md0.MetadataReader; CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "C"); CheckNames(reader0, reader0.GetMethodDefNames(), "Main", ".ctor"); CheckNames(reader0, reader0.GetMemberRefNames(), /*CompilationRelaxationsAttribute.*/".ctor", /*RuntimeCompatibilityAttribute.*/".ctor", /*Object.*/".ctor", /*DebuggableAttribute*/".ctor"); Assert.Equal(3, reader0.CustomAttributes.Count); var generation0 = EmitBaseline.CreateInitialBaseline( md0, EmptyLocalsProvider); var method1 = compilation1.GetMember<MethodSymbol>("C.F"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Insert, null, method1))); // Verify delta metadata contains expected rows. using var md1 = diff1.GetMetadata(); var reader1 = md1.Reader; var readers = new[] { reader0, reader1 }; EncValidation.VerifyModuleMvid(1, reader0, reader1); CheckNames(readers, reader1.GetTypeDefNames()); CheckNames(readers, reader1.GetMethodDefNames(), "F"); CheckNames(readers, reader1.GetMemberRefNames(), /*DescriptionAttribute*/".ctor", /*String.*/"Empty"); Assert.Equal(1, reader1.CustomAttributes.Count); CheckEncLog(reader1, Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default), Row(5, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(6, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(6, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(7, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(8, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(1, TableIndex.StandAloneSig, EditAndContinueOperation.Default), Row(2, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(3, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(4, TableIndex.CustomAttribute, EditAndContinueOperation.Default)); // Row 4, a new attribute CheckEncMap(reader1, Handle(6, TableIndex.TypeRef), Handle(7, TableIndex.TypeRef), Handle(8, TableIndex.TypeRef), Handle(3, TableIndex.MethodDef), Handle(5, TableIndex.MemberRef), Handle(6, TableIndex.MemberRef), Handle(4, TableIndex.CustomAttribute), Handle(1, TableIndex.StandAloneSig), Handle(2, TableIndex.AssemblyRef)); } [Fact] public void ModifyMethod_ParameterAttributes() { var source0 = @"class C { static void Main() { } static string F(string input, int a) { return input; } }"; var source1 = @"class C { static void Main() { } static string F([System.ComponentModel.Description(""input"")]string input, int a) { return input; } static void G(string input) { } }"; var source2 = @"class C { static void Main() { } static string F([System.ComponentModel.Description(""input"")]string input, int a) { return input; } static void G([System.ComponentModel.Description(""input"")]string input) { } }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugExe, targetFramework: TargetFramework.NetStandard20); var compilation1 = compilation0.WithSource(source1); var compilation2 = compilation1.WithSource(source2); var methodF0 = compilation0.GetMember<MethodSymbol>("C.F"); var methodF1 = compilation1.GetMember<MethodSymbol>("C.F"); var methodG1 = compilation1.GetMember<MethodSymbol>("C.G"); var methodG2 = compilation2.GetMember<MethodSymbol>("C.G"); // Verify full metadata contains expected rows. var bytes0 = compilation0.EmitToArray(); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var reader0 = md0.MetadataReader; CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "C"); CheckNames(reader0, reader0.GetMethodDefNames(), "Main", "F", ".ctor"); CheckNames(reader0, reader0.GetMemberRefNames(), /*CompilationRelaxationsAttribute.*/".ctor", /*RuntimeCompatibilityAttribute.*/".ctor", /*Object.*/".ctor", /*DebuggableAttribute*/".ctor"); CheckNames(reader0, reader0.GetParameterDefNames(), "input", "a"); CheckAttributes(reader0, new CustomAttributeRow(Handle(1, TableIndex.Assembly), Handle(1, TableIndex.MemberRef)), new CustomAttributeRow(Handle(1, TableIndex.Assembly), Handle(2, TableIndex.MemberRef)), new CustomAttributeRow(Handle(1, TableIndex.Assembly), Handle(3, TableIndex.MemberRef))); var generation0 = EmitBaseline.CreateInitialBaseline( md0, EmptyLocalsProvider); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, methodF0, methodF1), SemanticEdit.Create(SemanticEditKind.Insert, null, methodG1))); // Verify delta metadata contains expected rows. using var md1 = diff1.GetMetadata(); var reader1 = md1.Reader; var readers = new[] { reader0, reader1 }; EncValidation.VerifyModuleMvid(1, reader0, reader1); CheckNames(readers, reader1.GetTypeDefNames()); CheckNames(readers, reader1.GetMethodDefNames(), "F", "G"); CheckNames(readers, reader1.GetMemberRefNames(), /*DescriptionAttribute*/".ctor"); CheckNames(readers, reader1.GetParameterDefNames(), "input", "a", "input"); CheckAttributes(reader1, new CustomAttributeRow(Handle(1, TableIndex.Param), Handle(5, TableIndex.MemberRef))); CheckEncLog(reader1, Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default), Row(5, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(6, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(7, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(2, TableIndex.StandAloneSig, EditAndContinueOperation.Default), Row(2, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(2, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(4, TableIndex.MethodDef, EditAndContinueOperation.Default), // New method, G Row(1, TableIndex.Param, EditAndContinueOperation.Default), // Update existing param Row(2, TableIndex.Param, EditAndContinueOperation.Default), // Update existing param Row(4, TableIndex.MethodDef, EditAndContinueOperation.AddParameter), // New param on method, G Row(3, TableIndex.Param, EditAndContinueOperation.Default), // Support for the above Row(4, TableIndex.CustomAttribute, EditAndContinueOperation.Default)); CheckEncMap(reader1, Handle(6, TableIndex.TypeRef), Handle(7, TableIndex.TypeRef), Handle(2, TableIndex.MethodDef), Handle(4, TableIndex.MethodDef), Handle(1, TableIndex.Param), Handle(2, TableIndex.Param), Handle(3, TableIndex.Param), Handle(5, TableIndex.MemberRef), Handle(4, TableIndex.CustomAttribute), Handle(2, TableIndex.StandAloneSig), Handle(2, TableIndex.AssemblyRef)); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, methodG1, methodG2))); using var md2 = diff2.GetMetadata(); var reader2 = md2.Reader; readers = new[] { reader0, reader1, reader2 }; EncValidation.VerifyModuleMvid(2, reader1, reader2); CheckNames(readers, reader2.GetTypeDefNames()); CheckNames(readers, reader2.GetMethodDefNames(), "G"); CheckNames(readers, reader2.GetMemberRefNames(), /*DescriptionAttribute*/".ctor"); CheckNames(readers, reader2.GetParameterDefNames(), "input"); CheckAttributes(reader2, new CustomAttributeRow(Handle(3, TableIndex.Param), Handle(6, TableIndex.MemberRef))); CheckEncLog(reader2, Row(3, TableIndex.AssemblyRef, EditAndContinueOperation.Default), Row(6, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(8, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(9, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(4, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(3, TableIndex.Param, EditAndContinueOperation.Default), // Update existing param, from the first delta Row(5, TableIndex.CustomAttribute, EditAndContinueOperation.Default)); CheckEncMap(reader2, Handle(8, TableIndex.TypeRef), Handle(9, TableIndex.TypeRef), Handle(4, TableIndex.MethodDef), Handle(3, TableIndex.Param), Handle(6, TableIndex.MemberRef), Handle(5, TableIndex.CustomAttribute), Handle(3, TableIndex.AssemblyRef)); } [Fact] public void ModifyDelegateInvokeMethod_AddAttributes() { var source0 = @" class A : System.Attribute { } delegate void D(int x); "; var source1 = @" class A : System.Attribute { } delegate void D([A]int x); "; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll, targetFramework: TargetFramework.NetStandard20); var compilation1 = compilation0.WithSource(source1); var invoke0 = compilation0.GetMember<MethodSymbol>("D.Invoke"); var beginInvoke0 = compilation0.GetMember<MethodSymbol>("D.BeginInvoke"); var invoke1 = compilation1.GetMember<MethodSymbol>("D.Invoke"); var beginInvoke1 = compilation1.GetMember<MethodSymbol>("D.BeginInvoke"); // Verify full metadata contains expected rows. var bytes0 = compilation0.EmitToArray(); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var reader0 = md0.MetadataReader; var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, invoke0, invoke1), SemanticEdit.Create(SemanticEditKind.Update, beginInvoke0, beginInvoke1))); // Verify delta metadata contains expected rows. using var md1 = diff1.GetMetadata(); var reader1 = md1.Reader; var readers = new[] { reader0, reader1 }; CheckNames(readers, reader1.GetMethodDefNames(), "Invoke", "BeginInvoke"); CheckNames(readers, reader1.GetParameterDefNames(), "x", "x", "callback", "object"); CheckAttributes(reader1, new CustomAttributeRow(Handle(3, TableIndex.Param), Handle(1, TableIndex.MethodDef)), new CustomAttributeRow(Handle(4, TableIndex.Param), Handle(1, TableIndex.MethodDef))); CheckEncLog(reader1, Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default), Row(10, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(11, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(12, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(13, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(3, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(4, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(3, TableIndex.Param, EditAndContinueOperation.Default), // Updating existing parameter defs Row(4, TableIndex.Param, EditAndContinueOperation.Default), Row(5, TableIndex.Param, EditAndContinueOperation.Default), Row(6, TableIndex.Param, EditAndContinueOperation.Default), Row(4, TableIndex.CustomAttribute, EditAndContinueOperation.Default), // Adding new custom attribute rows Row(5, TableIndex.CustomAttribute, EditAndContinueOperation.Default)); CheckEncMap(reader1, Handle(10, TableIndex.TypeRef), Handle(11, TableIndex.TypeRef), Handle(12, TableIndex.TypeRef), Handle(13, TableIndex.TypeRef), Handle(3, TableIndex.MethodDef), Handle(4, TableIndex.MethodDef), Handle(3, TableIndex.Param), Handle(4, TableIndex.Param), Handle(5, TableIndex.Param), Handle(6, TableIndex.Param), Handle(4, TableIndex.CustomAttribute), Handle(5, TableIndex.CustomAttribute), Handle(2, TableIndex.AssemblyRef)); } /// <summary> /// Add a method that requires entries in the ParameterDefs table. /// Specifically, normal parameters or return types with attributes. /// Add the method in the first edit, then modify the method in the second. /// </summary> [Fact] public void Method_WithParameterAttributes_AddThenUpdate() { var source0 = @"class A : System.Attribute { } class C { }"; var source1 = @"class A : System.Attribute { } class C { [return:A]static object F(int arg = 1) => arg; }"; var source2 = @"class A : System.Attribute { } class C { [return:A]static object F(int arg = 1) => null; }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var compilation2 = compilation0.WithSource(source2); var f1 = compilation1.GetMember<MethodSymbol>("C.F"); var f2 = compilation2.GetMember<MethodSymbol>("C.F"); var bytes0 = compilation0.EmitToArray(); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var reader0 = md0.MetadataReader; CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "A", "C"); CheckNames(reader0, reader0.GetMethodDefNames(), ".ctor", ".ctor"); var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider); // gen 1 var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Insert, null, f1))); using var md1 = diff1.GetMetadata(); var reader1 = md1.Reader; var readers = new List<MetadataReader> { reader0, reader1 }; EncValidation.VerifyModuleMvid(1, reader0, reader1); CheckNames(readers, reader1.GetTypeDefNames()); CheckNames(readers, reader1.GetMethodDefNames(), "F"); CheckNames(readers, reader1.GetParameterDefNames(), "", "arg"); CheckNames(readers, diff1.EmitResult.ChangedTypes, "C"); CheckNames(readers, diff1.EmitResult.UpdatedMethods); CheckEncLogDefinitions(reader1, Row(3, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(3, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(3, TableIndex.MethodDef, EditAndContinueOperation.AddParameter), Row(1, TableIndex.Param, EditAndContinueOperation.Default), Row(3, TableIndex.MethodDef, EditAndContinueOperation.AddParameter), Row(2, TableIndex.Param, EditAndContinueOperation.Default), Row(1, TableIndex.Constant, EditAndContinueOperation.Default), Row(4, TableIndex.CustomAttribute, EditAndContinueOperation.Default)); CheckEncMapDefinitions(reader1, Handle(3, TableIndex.MethodDef), Handle(1, TableIndex.Param), Handle(2, TableIndex.Param), Handle(1, TableIndex.Constant), Handle(4, TableIndex.CustomAttribute)); // gen 2 var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, f1, f2))); using var md2 = diff2.GetMetadata(); var reader2 = md2.Reader; readers.Add(reader2); EncValidation.VerifyModuleMvid(2, reader1, reader2); CheckNames(readers, reader2.GetTypeDefNames()); CheckNames(readers, reader2.GetMethodDefNames(), "F"); CheckNames(readers, reader2.GetParameterDefNames(), "", "arg"); CheckNames(readers, diff2.EmitResult.ChangedTypes, "C"); CheckNames(readers, diff2.EmitResult.UpdatedMethods, "F"); CheckEncLogDefinitions(reader2, Row(3, TableIndex.MethodDef, EditAndContinueOperation.Default), // C.F2 Row(1, TableIndex.Param, EditAndContinueOperation.Default), Row(2, TableIndex.Param, EditAndContinueOperation.Default), Row(2, TableIndex.Constant, EditAndContinueOperation.Default), Row(4, TableIndex.CustomAttribute, EditAndContinueOperation.Default)); CheckEncMapDefinitions(reader2, Handle(3, TableIndex.MethodDef), Handle(1, TableIndex.Param), Handle(2, TableIndex.Param), Handle(2, TableIndex.Constant), Handle(4, TableIndex.CustomAttribute)); } [Fact] public void Method_WithEmbeddedAttributes_AndThenUpdate() { var source0 = @" namespace System.Runtime.CompilerServices { class X { } } namespace N { class C { static void Main() { } } } "; var source1 = @" namespace System.Runtime.CompilerServices { class X { } } namespace N { struct C { static void Main() { Id(in G()); } static ref readonly int Id(in int x) => ref x; static ref readonly int G() => ref new int[1] { 1 }[0]; } }"; var source2 = @" namespace System.Runtime.CompilerServices { class X { } } namespace N { struct C { static void Main() { Id(in G()); } static ref readonly int Id(in int x) => ref x; static ref readonly int G() => ref new int[1] { 2 }[0]; static void H(string? s) {} } }"; var source3 = @" namespace System.Runtime.CompilerServices { class X { } } namespace N { struct C { static void Main() { Id(in G()); } static ref readonly int Id(in int x) => ref x; static ref readonly int G() => ref new int[1] { 2 }[0]; static void H(string? s) {} readonly ref readonly string?[]? F() => throw null; } }"; var compilation0 = CreateCompilation(source0, options: ComSafeDebugDll); var compilation1 = compilation0.WithSource(source1); var compilation2 = compilation1.WithSource(source2); var compilation3 = compilation2.WithSource(source3); var main0 = compilation0.GetMember<MethodSymbol>("N.C.Main"); var main1 = compilation1.GetMember<MethodSymbol>("N.C.Main"); var id1 = compilation1.GetMember<MethodSymbol>("N.C.Id"); var g1 = compilation1.GetMember<MethodSymbol>("N.C.G"); var g2 = compilation2.GetMember<MethodSymbol>("N.C.G"); var h2 = compilation2.GetMember<MethodSymbol>("N.C.H"); var f3 = compilation3.GetMember<MethodSymbol>("N.C.F"); // Verify full metadata contains expected rows. using var md0 = ModuleMetadata.CreateFromImage(compilation0.EmitToArray()); var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, main0, main1), SemanticEdit.Create(SemanticEditKind.Insert, null, id1), SemanticEdit.Create(SemanticEditKind.Insert, null, g1))); diff1.VerifySynthesizedMembers( "<global namespace>: {Microsoft}", "Microsoft: {CodeAnalysis}", "Microsoft.CodeAnalysis: {EmbeddedAttribute}", "System.Runtime.CompilerServices: {IsReadOnlyAttribute}"); diff1.VerifyIL("N.C.Main", @" { // Code size 13 (0xd) .maxstack 1 IL_0000: nop IL_0001: call ""ref readonly int N.C.G()"" IL_0006: call ""ref readonly int N.C.Id(in int)"" IL_000b: pop IL_000c: ret } "); diff1.VerifyIL("N.C.Id", @" { // Code size 2 (0x2) .maxstack 1 IL_0000: ldarg.0 IL_0001: ret } "); diff1.VerifyIL("N.C.G", @" { // Code size 17 (0x11) .maxstack 4 IL_0000: ldc.i4.1 IL_0001: newarr ""int"" IL_0006: dup IL_0007: ldc.i4.0 IL_0008: ldc.i4.1 IL_0009: stelem.i4 IL_000a: ldc.i4.0 IL_000b: ldelema ""int"" IL_0010: ret } "); // Verify delta metadata contains expected rows. using var md1 = diff1.GetMetadata(); var reader0 = md0.MetadataReader; var reader1 = md1.Reader; var readers = new List<MetadataReader>() { reader0, reader1 }; CheckNames(readers, reader1.GetTypeDefFullNames(), "Microsoft.CodeAnalysis.EmbeddedAttribute", "System.Runtime.CompilerServices.IsReadOnlyAttribute"); CheckNames(readers, reader1.GetMethodDefNames(), "Main", ".ctor", ".ctor", "Id", "G"); CheckEncLog(reader1, Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default), Row(5, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(6, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(6, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(7, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(8, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(9, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(10, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(4, TableIndex.TypeDef, EditAndContinueOperation.Default), Row(5, TableIndex.TypeDef, EditAndContinueOperation.Default), Row(1, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(4, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(4, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(5, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(5, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(2, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(6, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(2, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(7, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(6, TableIndex.MethodDef, EditAndContinueOperation.AddParameter), Row(1, TableIndex.Param, EditAndContinueOperation.Default), Row(6, TableIndex.MethodDef, EditAndContinueOperation.AddParameter), Row(2, TableIndex.Param, EditAndContinueOperation.Default), Row(7, TableIndex.MethodDef, EditAndContinueOperation.AddParameter), Row(3, TableIndex.Param, EditAndContinueOperation.Default), Row(4, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(5, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(6, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(7, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(8, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(9, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(10, TableIndex.CustomAttribute, EditAndContinueOperation.Default)); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, g1, g2), SemanticEdit.Create(SemanticEditKind.Insert, null, h2))); // synthesized member for nullable annotations added: diff2.VerifySynthesizedMembers( "<global namespace>: {Microsoft}", "Microsoft: {CodeAnalysis}", "Microsoft.CodeAnalysis: {EmbeddedAttribute}", "System.Runtime.CompilerServices: {IsReadOnlyAttribute, NullableAttribute, NullableContextAttribute}"); // Verify delta metadata contains expected rows. using var md2 = diff2.GetMetadata(); var reader2 = md2.Reader; readers.Add(reader2); // note: NullableAttribute has 2 ctors, NullableContextAttribute has one CheckNames(readers, reader2.GetTypeDefFullNames(), "System.Runtime.CompilerServices.NullableAttribute", "System.Runtime.CompilerServices.NullableContextAttribute"); CheckNames(readers, reader2.GetMethodDefNames(), "G", ".ctor", ".ctor", ".ctor", "H"); // two new TypeDefs emitted for the attributes: CheckEncLog(reader2, Row(3, TableIndex.AssemblyRef, EditAndContinueOperation.Default), Row(7, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(8, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(9, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(11, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(12, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(13, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(14, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(15, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(16, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(17, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(18, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(6, TableIndex.TypeDef, EditAndContinueOperation.Default), // NullableAttribute Row(7, TableIndex.TypeDef, EditAndContinueOperation.Default), // NullableContextAttribute Row(6, TableIndex.TypeDef, EditAndContinueOperation.AddField), Row(1, TableIndex.Field, EditAndContinueOperation.Default), Row(7, TableIndex.TypeDef, EditAndContinueOperation.AddField), Row(2, TableIndex.Field, EditAndContinueOperation.Default), Row(7, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(6, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(8, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(6, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(9, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(7, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(10, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(2, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(11, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(3, TableIndex.Param, EditAndContinueOperation.Default), Row(11, TableIndex.MethodDef, EditAndContinueOperation.AddParameter), Row(4, TableIndex.Param, EditAndContinueOperation.Default), Row(6, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(11, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(12, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(13, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(14, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(15, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(16, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(17, TableIndex.CustomAttribute, EditAndContinueOperation.Default)); CheckEncMap(reader2, Handle(11, TableIndex.TypeRef), Handle(12, TableIndex.TypeRef), Handle(13, TableIndex.TypeRef), Handle(14, TableIndex.TypeRef), Handle(15, TableIndex.TypeRef), Handle(16, TableIndex.TypeRef), Handle(17, TableIndex.TypeRef), Handle(18, TableIndex.TypeRef), Handle(6, TableIndex.TypeDef), Handle(7, TableIndex.TypeDef), Handle(1, TableIndex.Field), Handle(2, TableIndex.Field), Handle(7, TableIndex.MethodDef), Handle(8, TableIndex.MethodDef), Handle(9, TableIndex.MethodDef), Handle(10, TableIndex.MethodDef), Handle(11, TableIndex.MethodDef), Handle(3, TableIndex.Param), Handle(4, TableIndex.Param), Handle(7, TableIndex.MemberRef), Handle(8, TableIndex.MemberRef), Handle(9, TableIndex.MemberRef), Handle(6, TableIndex.CustomAttribute), Handle(11, TableIndex.CustomAttribute), Handle(12, TableIndex.CustomAttribute), Handle(13, TableIndex.CustomAttribute), Handle(14, TableIndex.CustomAttribute), Handle(15, TableIndex.CustomAttribute), Handle(16, TableIndex.CustomAttribute), Handle(17, TableIndex.CustomAttribute), Handle(3, TableIndex.AssemblyRef)); var diff3 = compilation3.EmitDifference( diff2.NextGeneration, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Insert, null, f3))); // no change in synthesized members: diff3.VerifySynthesizedMembers( "<global namespace>: {Microsoft}", "Microsoft: {CodeAnalysis}", "Microsoft.CodeAnalysis: {EmbeddedAttribute}", "System.Runtime.CompilerServices: {IsReadOnlyAttribute, NullableAttribute, NullableContextAttribute}"); // Verify delta metadata contains expected rows. using var md3 = diff3.GetMetadata(); var reader3 = md3.Reader; readers.Add(reader3); // no new type defs: CheckNames(readers, reader3.GetTypeDefFullNames()); CheckNames(readers, reader3.GetMethodDefNames(), "F"); CheckEncLog(reader3, Row(4, TableIndex.AssemblyRef, EditAndContinueOperation.Default), Row(19, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(20, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(2, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(12, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(12, TableIndex.MethodDef, EditAndContinueOperation.AddParameter), Row(5, TableIndex.Param, EditAndContinueOperation.Default), Row(18, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(19, TableIndex.CustomAttribute, EditAndContinueOperation.Default)); } [Fact] public void Field_Add() { var source0 = @"class C { string F = ""F""; }"; var source1 = @"class C { string F = ""F""; string G = ""G""; }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); // Verify full metadata contains expected rows. var bytes0 = compilation0.EmitToArray(); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var reader0 = md0.MetadataReader; CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "C"); CheckNames(reader0, reader0.GetFieldDefNames(), "F"); CheckNames(reader0, reader0.GetMethodDefNames(), ".ctor"); var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider); var method0 = compilation0.GetMember<MethodSymbol>("C..ctor"); var method1 = compilation1.GetMember<MethodSymbol>("C..ctor"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Insert, null, compilation1.GetMember<FieldSymbol>("C.G")), SemanticEdit.Create(SemanticEditKind.Update, method0, method1))); // Verify delta metadata contains expected rows. using var md1 = diff1.GetMetadata(); var reader1 = md1.Reader; var readers = new[] { reader0, reader1 }; CheckNames(readers, diff1.EmitResult.ChangedTypes, "C"); CheckNames(readers, reader1.GetTypeDefNames()); CheckNames(readers, reader1.GetFieldDefNames(), "G"); CheckNames(readers, reader1.GetMethodDefNames(), ".ctor"); CheckEncLog(reader1, Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default), Row(5, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(6, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(2, TableIndex.TypeDef, EditAndContinueOperation.AddField), Row(2, TableIndex.Field, EditAndContinueOperation.Default), Row(1, TableIndex.MethodDef, EditAndContinueOperation.Default)); CheckEncMap(reader1, Handle(6, TableIndex.TypeRef), Handle(2, TableIndex.Field), Handle(1, TableIndex.MethodDef), Handle(5, TableIndex.MemberRef), Handle(2, TableIndex.AssemblyRef)); } [Fact] public void Property_Accessor_Update() { var source0 = @"class C { object P { get { return 1; } } }"; var source1 = @"class C { object P { get { return 2; } } }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var getP0 = compilation0.GetMember<MethodSymbol>("C.get_P"); var getP1 = compilation1.GetMember<MethodSymbol>("C.get_P"); var bytes0 = compilation0.EmitToArray(); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var reader0 = md0.MetadataReader; CheckNames(reader0, reader0.GetPropertyDefNames(), "P"); CheckNames(reader0, reader0.GetMethodDefNames(), "get_P", ".ctor"); var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, getP0, getP1))); using var md1 = diff1.GetMetadata(); var reader1 = md1.Reader; var readers = new[] { reader0, reader1 }; CheckNames(readers, reader1.GetPropertyDefNames(), "P"); CheckNames(readers, reader1.GetMethodDefNames(), "get_P"); CheckEncLog(reader1, Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default), Row(7, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(8, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(2, TableIndex.StandAloneSig, EditAndContinueOperation.Default), Row(1, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(1, TableIndex.Property, EditAndContinueOperation.Default), Row(2, TableIndex.MethodSemantics, EditAndContinueOperation.Default)); CheckEncMap(reader1, Handle(7, TableIndex.TypeRef), Handle(8, TableIndex.TypeRef), Handle(1, TableIndex.MethodDef), Handle(2, TableIndex.StandAloneSig), Handle(1, TableIndex.Property), Handle(2, TableIndex.MethodSemantics), Handle(2, TableIndex.AssemblyRef)); } [Fact] public void Property_Add() { var source0 = @" class C { } "; var source1 = @" class C { object R { get { return null; } } } "; var source2 = @" class C { object R { get { return null; } } object Q { get; set; } } "; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var compilation2 = compilation0.WithSource(source2); var r1 = compilation1.GetMember<PropertySymbol>("C.R"); var q2 = compilation2.GetMember<PropertySymbol>("C.Q"); var bytes0 = compilation0.EmitToArray(); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var reader0 = md0.MetadataReader; CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "C"); var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider); // gen 1 var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Insert, null, r1))); using var md1 = diff1.GetMetadata(); var reader1 = md1.Reader; var readers = new List<MetadataReader> { reader0, reader1 }; CheckNames(readers, reader1.GetTypeDefNames()); CheckNames(readers, reader1.GetFieldDefNames()); CheckNames(readers, reader1.GetPropertyDefNames(), "R"); CheckNames(readers, reader1.GetMethodDefNames(), "get_R"); CheckNames(readers, diff1.EmitResult.UpdatedMethods); CheckNames(readers, diff1.EmitResult.ChangedTypes, "C"); CheckEncLogDefinitions(reader1, Row(1, TableIndex.StandAloneSig, EditAndContinueOperation.Default), Row(1, TableIndex.PropertyMap, EditAndContinueOperation.Default), Row(2, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(2, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(1, TableIndex.PropertyMap, EditAndContinueOperation.AddProperty), Row(1, TableIndex.Property, EditAndContinueOperation.Default), Row(1, TableIndex.MethodSemantics, EditAndContinueOperation.Default)); CheckEncMapDefinitions(reader1, Handle(2, TableIndex.MethodDef), Handle(1, TableIndex.StandAloneSig), Handle(1, TableIndex.PropertyMap), Handle(1, TableIndex.Property), Handle(1, TableIndex.MethodSemantics)); // gen 2 var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Insert, null, q2))); using var md2 = diff2.GetMetadata(); var reader2 = md2.Reader; readers.Add(reader2); CheckNames(readers, reader2.GetTypeDefNames()); CheckNames(readers, reader2.GetFieldDefNames(), "<Q>k__BackingField"); CheckNames(readers, reader2.GetPropertyDefNames(), "Q"); CheckNames(readers, reader2.GetMethodDefNames(), "get_Q", "set_Q"); CheckNames(readers, diff1.EmitResult.UpdatedMethods); CheckNames(readers, diff1.EmitResult.ChangedTypes, "C"); CheckEncLogDefinitions(reader2, Row(2, TableIndex.TypeDef, EditAndContinueOperation.AddField), Row(1, TableIndex.Field, EditAndContinueOperation.Default), Row(2, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(3, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(2, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(4, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(1, TableIndex.PropertyMap, EditAndContinueOperation.AddProperty), Row(2, TableIndex.Property, EditAndContinueOperation.Default), Row(4, TableIndex.MethodDef, EditAndContinueOperation.AddParameter), Row(1, TableIndex.Param, EditAndContinueOperation.Default), Row(4, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(5, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(6, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(7, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(2, TableIndex.MethodSemantics, EditAndContinueOperation.Default), Row(3, TableIndex.MethodSemantics, EditAndContinueOperation.Default)); CheckEncMapDefinitions(reader2, Handle(1, TableIndex.Field), Handle(3, TableIndex.MethodDef), Handle(4, TableIndex.MethodDef), Handle(1, TableIndex.Param), Handle(4, TableIndex.CustomAttribute), Handle(5, TableIndex.CustomAttribute), Handle(6, TableIndex.CustomAttribute), Handle(7, TableIndex.CustomAttribute), Handle(2, TableIndex.Property), Handle(2, TableIndex.MethodSemantics), Handle(3, TableIndex.MethodSemantics)); } [Fact] public void Event_Add() { var source0 = @" class C { }"; var source1 = @" class C { event System.Action E; }"; var source2 = @" class C { event System.Action E; event System.Action G; }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var compilation2 = compilation0.WithSource(source2); var e1 = compilation1.GetMember<EventSymbol>("C.E"); var g2 = compilation2.GetMember<EventSymbol>("C.G"); var bytes0 = compilation0.EmitToArray(); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var reader0 = md0.MetadataReader; var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider); // gen 1 var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Insert, null, e1))); using var md1 = diff1.GetMetadata(); var reader1 = md1.Reader; var readers = new List<MetadataReader> { reader0, reader1 }; CheckNames(readers, reader1.GetTypeDefNames()); CheckNames(readers, reader1.GetFieldDefNames(), "E"); CheckNames(readers, reader1.GetMethodDefNames(), "add_E", "remove_E"); CheckNames(readers, diff1.EmitResult.UpdatedMethods); CheckNames(readers, diff1.EmitResult.ChangedTypes, "C"); CheckEncLogDefinitions(reader1, Row(1, TableIndex.StandAloneSig, EditAndContinueOperation.Default), Row(1, TableIndex.EventMap, EditAndContinueOperation.Default), Row(1, TableIndex.EventMap, EditAndContinueOperation.AddEvent), Row(1, TableIndex.Event, EditAndContinueOperation.Default), Row(2, TableIndex.TypeDef, EditAndContinueOperation.AddField), Row(1, TableIndex.Field, EditAndContinueOperation.Default), Row(2, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(2, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(2, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(3, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(2, TableIndex.MethodDef, EditAndContinueOperation.AddParameter), Row(1, TableIndex.Param, EditAndContinueOperation.Default), Row(3, TableIndex.MethodDef, EditAndContinueOperation.AddParameter), Row(2, TableIndex.Param, EditAndContinueOperation.Default), Row(4, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(5, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(6, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(7, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(1, TableIndex.MethodSemantics, EditAndContinueOperation.Default), Row(2, TableIndex.MethodSemantics, EditAndContinueOperation.Default)); CheckEncMapDefinitions(reader1, Handle(1, TableIndex.Field), Handle(2, TableIndex.MethodDef), Handle(3, TableIndex.MethodDef), Handle(1, TableIndex.Param), Handle(2, TableIndex.Param), Handle(4, TableIndex.CustomAttribute), Handle(5, TableIndex.CustomAttribute), Handle(6, TableIndex.CustomAttribute), Handle(7, TableIndex.CustomAttribute), Handle(1, TableIndex.StandAloneSig), Handle(1, TableIndex.EventMap), Handle(1, TableIndex.Event), Handle(1, TableIndex.MethodSemantics), Handle(2, TableIndex.MethodSemantics)); // gen 2 var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Insert, null, g2))); using var md2 = diff2.GetMetadata(); var reader2 = md2.Reader; readers.Add(reader2); CheckNames(readers, reader2.GetTypeDefNames()); CheckNames(readers, reader2.GetFieldDefNames(), "G"); CheckNames(readers, reader2.GetMethodDefNames(), "add_G", "remove_G"); CheckNames(readers, diff1.EmitResult.UpdatedMethods); CheckNames(readers, diff1.EmitResult.ChangedTypes, "C"); CheckEncLogDefinitions(reader2, Row(2, TableIndex.StandAloneSig, EditAndContinueOperation.Default), Row(1, TableIndex.EventMap, EditAndContinueOperation.AddEvent), Row(2, TableIndex.Event, EditAndContinueOperation.Default), Row(2, TableIndex.TypeDef, EditAndContinueOperation.AddField), Row(2, TableIndex.Field, EditAndContinueOperation.Default), Row(2, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(4, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(2, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(5, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(4, TableIndex.MethodDef, EditAndContinueOperation.AddParameter), Row(3, TableIndex.Param, EditAndContinueOperation.Default), Row(5, TableIndex.MethodDef, EditAndContinueOperation.AddParameter), Row(4, TableIndex.Param, EditAndContinueOperation.Default), Row(8, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(9, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(10, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(11, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(3, TableIndex.MethodSemantics, EditAndContinueOperation.Default), Row(4, TableIndex.MethodSemantics, EditAndContinueOperation.Default)); CheckEncMapDefinitions(reader2, Handle(2, TableIndex.Field), Handle(4, TableIndex.MethodDef), Handle(5, TableIndex.MethodDef), Handle(3, TableIndex.Param), Handle(4, TableIndex.Param), Handle(8, TableIndex.CustomAttribute), Handle(9, TableIndex.CustomAttribute), Handle(10, TableIndex.CustomAttribute), Handle(11, TableIndex.CustomAttribute), Handle(2, TableIndex.StandAloneSig), Handle(2, TableIndex.Event), Handle(3, TableIndex.MethodSemantics), Handle(4, TableIndex.MethodSemantics)); } [WorkItem(1175704, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1175704")] [Fact] public void EventFields() { var source0 = MarkedSource(@" using System; class C { static event EventHandler handler; static int F() { handler(null, null); return 1; } } "); var source1 = MarkedSource(@" using System; class C { static event EventHandler handler; static int F() { handler(null, null); return 10; } } "); var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll); var compilation1 = compilation0.WithSource(source1.Tree); var f0 = compilation0.GetMember<MethodSymbol>("C.F"); var f1 = compilation1.GetMember<MethodSymbol>("C.F"); var v0 = CompileAndVerify(compilation0); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, f0, f1, preserveLocalVariables: true))); diff1.VerifyIL("C.F", @" { // Code size 21 (0x15) .maxstack 3 .locals init (int V_0) IL_0000: nop IL_0001: ldsfld ""System.EventHandler C.handler"" IL_0006: ldnull IL_0007: ldnull IL_0008: callvirt ""void System.EventHandler.Invoke(object, System.EventArgs)"" IL_000d: nop IL_000e: ldc.i4.s 10 IL_0010: stloc.0 IL_0011: br.s IL_0013 IL_0013: ldloc.0 IL_0014: ret } "); } [Fact] public void UpdateType_AddAttributes() { var source0 = @" class C { }"; var source1 = @" [System.ComponentModel.Description(""C"")] class C { }"; var source2 = @" [System.ComponentModel.Description(""C"")] [System.ObsoleteAttribute] class C { }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll, targetFramework: TargetFramework.NetStandard20); var compilation1 = compilation0.WithSource(source1); var compilation2 = compilation1.WithSource(source2); var c0 = compilation0.GetMember<NamedTypeSymbol>("C"); var c1 = compilation1.GetMember<NamedTypeSymbol>("C"); var c2 = compilation2.GetMember<NamedTypeSymbol>("C"); // Verify full metadata contains expected rows. var bytes0 = compilation0.EmitToArray(); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var reader0 = md0.MetadataReader; CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "C"); Assert.Equal(3, reader0.CustomAttributes.Count); var generation0 = EmitBaseline.CreateInitialBaseline( md0, EmptyLocalsProvider); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, c0, c1))); // Verify delta metadata contains expected rows. using var md1 = diff1.GetMetadata(); var reader1 = md1.Reader; var readers = new[] { reader0, reader1 }; CheckNames(readers, reader1.GetTypeDefNames(), "C"); Assert.Equal(1, reader1.CustomAttributes.Count); CheckEncLogDefinitions(reader1, Row(2, TableIndex.TypeDef, EditAndContinueOperation.Default), Row(4, TableIndex.CustomAttribute, EditAndContinueOperation.Default)); CheckEncMapDefinitions(reader1, Handle(2, TableIndex.TypeDef), Handle(4, TableIndex.CustomAttribute)); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, c1, c2))); // Verify delta metadata contains expected rows. using var md2 = diff2.GetMetadata(); var reader2 = md2.Reader; readers = new[] { reader0, reader1, reader2 }; CheckNames(readers, reader2.GetTypeDefNames(), "C"); Assert.Equal(2, reader2.CustomAttributes.Count); CheckEncLogDefinitions(reader2, Row(2, TableIndex.TypeDef, EditAndContinueOperation.Default), Row(4, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(5, TableIndex.CustomAttribute, EditAndContinueOperation.Default)); CheckEncMapDefinitions(reader2, Handle(2, TableIndex.TypeDef), Handle(4, TableIndex.CustomAttribute), Handle(5, TableIndex.CustomAttribute)); } [Fact] public void ReplaceType() { var source0 = @" class C { void F(int x) {} } "; var source1 = @" class C { void F(int x, int y) { } }"; var source2 = @" class C { void F(int x, int y) { System.Console.WriteLine(1); } }"; var source3 = @" [System.Obsolete] class C { void F(int x, int y) { System.Console.WriteLine(2); } }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll, targetFramework: TargetFramework.NetStandard20); var compilation1 = compilation0.WithSource(source1); var compilation2 = compilation1.WithSource(source2); var compilation3 = compilation2.WithSource(source3); var c0 = compilation0.GetMember<NamedTypeSymbol>("C"); var c1 = compilation1.GetMember<NamedTypeSymbol>("C"); var c2 = compilation2.GetMember<NamedTypeSymbol>("C"); var c3 = compilation3.GetMember<NamedTypeSymbol>("C"); var f2 = c2.GetMember<MethodSymbol>("F"); var f3 = c3.GetMember<MethodSymbol>("F"); // Verify full metadata contains expected rows. var bytes0 = compilation0.EmitToArray(); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var reader0 = md0.MetadataReader; CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "C"); var generation0 = EmitBaseline.CreateInitialBaseline( md0, EmptyLocalsProvider); // This update emulates "Reloadable" type behavior - a new type is generated instead of updating the existing one. var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Replace, null, c1))); // Verify delta metadata contains expected rows. using var md1 = diff1.GetMetadata(); var reader1 = md1.Reader; var readers = new[] { reader0, reader1 }; CheckNames(readers, reader1.GetTypeDefNames(), "C#1"); CheckNames(readers, diff1.EmitResult.ChangedTypes, "C#1"); CheckEncLogDefinitions(reader1, Row(3, TableIndex.TypeDef, EditAndContinueOperation.Default), Row(3, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(3, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(3, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(4, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(3, TableIndex.MethodDef, EditAndContinueOperation.AddParameter), Row(2, TableIndex.Param, EditAndContinueOperation.Default), Row(3, TableIndex.MethodDef, EditAndContinueOperation.AddParameter), Row(3, TableIndex.Param, EditAndContinueOperation.Default)); CheckEncMapDefinitions(reader1, Handle(3, TableIndex.TypeDef), Handle(3, TableIndex.MethodDef), Handle(4, TableIndex.MethodDef), Handle(2, TableIndex.Param), Handle(3, TableIndex.Param)); // This update emulates "Reloadable" type behavior - a new type is generated instead of updating the existing one. var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Replace, null, c2))); // Verify delta metadata contains expected rows. using var md2 = diff2.GetMetadata(); var reader2 = md2.Reader; readers = new[] { reader0, reader1, reader2 }; CheckNames(readers, reader2.GetTypeDefNames(), "C#2"); CheckNames(readers, diff2.EmitResult.ChangedTypes, "C#2"); CheckEncLogDefinitions(reader2, Row(4, TableIndex.TypeDef, EditAndContinueOperation.Default), Row(4, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(5, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(4, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(6, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(5, TableIndex.MethodDef, EditAndContinueOperation.AddParameter), Row(4, TableIndex.Param, EditAndContinueOperation.Default), Row(5, TableIndex.MethodDef, EditAndContinueOperation.AddParameter), Row(5, TableIndex.Param, EditAndContinueOperation.Default)); CheckEncMapDefinitions(reader2, Handle(4, TableIndex.TypeDef), Handle(5, TableIndex.MethodDef), Handle(6, TableIndex.MethodDef), Handle(4, TableIndex.Param), Handle(5, TableIndex.Param)); // This update is an EnC update - even reloadable types are update in-place var diff3 = compilation3.EmitDifference( diff2.NextGeneration, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, c2, c3), SemanticEdit.Create(SemanticEditKind.Update, f2, f3))); // Verify delta metadata contains expected rows. using var md3 = diff3.GetMetadata(); var reader3 = md3.Reader; readers = new[] { reader0, reader1, reader2, reader3 }; CheckNames(readers, reader3.GetTypeDefNames(), "C#2"); CheckNames(readers, diff3.EmitResult.ChangedTypes, "C#2"); CheckEncLogDefinitions(reader3, Row(4, TableIndex.TypeDef, EditAndContinueOperation.Default), Row(5, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(4, TableIndex.Param, EditAndContinueOperation.Default), Row(5, TableIndex.Param, EditAndContinueOperation.Default), Row(4, TableIndex.CustomAttribute, EditAndContinueOperation.Default)); CheckEncMapDefinitions(reader3, Handle(4, TableIndex.TypeDef), Handle(5, TableIndex.MethodDef), Handle(4, TableIndex.Param), Handle(5, TableIndex.Param), Handle(4, TableIndex.CustomAttribute)); } [Fact] public void EventFields_Attributes() { var source0 = MarkedSource(@" using System; class C { static event EventHandler E; } "); var source1 = MarkedSource(@" using System; class C { [System.Obsolete] static event EventHandler E; }"); var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll); var compilation1 = compilation0.WithSource(source1.Tree); var event0 = compilation0.GetMember<EventSymbol>("C.E"); var event1 = compilation1.GetMember<EventSymbol>("C.E"); var v0 = CompileAndVerify(compilation0); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var reader0 = md0.MetadataReader; var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "C"); CheckNames(reader0, reader0.GetMethodDefNames(), "add_E", "remove_E", ".ctor"); CheckAttributes(reader0, new CustomAttributeRow(Handle(1, TableIndex.MethodDef), Handle(4, TableIndex.MemberRef)), new CustomAttributeRow(Handle(1, TableIndex.Field), Handle(4, TableIndex.MemberRef)), new CustomAttributeRow(Handle(1, TableIndex.Field), Handle(5, TableIndex.MemberRef)), new CustomAttributeRow(Handle(1, TableIndex.Assembly), Handle(1, TableIndex.MemberRef)), new CustomAttributeRow(Handle(1, TableIndex.Assembly), Handle(2, TableIndex.MemberRef)), new CustomAttributeRow(Handle(1, TableIndex.Assembly), Handle(3, TableIndex.MemberRef)), new CustomAttributeRow(Handle(2, TableIndex.MethodDef), Handle(4, TableIndex.MemberRef))); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, event0, event1))); // Verify delta metadata contains expected rows. using var md1 = diff1.GetMetadata(); var reader1 = md1.Reader; var readers = new[] { reader0, reader1 }; EncValidation.VerifyModuleMvid(1, reader0, reader1); CheckNames(readers, reader1.GetTypeDefNames()); CheckNames(readers, reader1.GetMethodDefNames()); CheckNames(readers, reader1.GetEventDefNames(), "E"); CheckAttributes(reader1, new CustomAttributeRow(Handle(1, TableIndex.Event), Handle(10, TableIndex.MemberRef))); CheckEncLogDefinitions(reader1, Row(1, TableIndex.Event, EditAndContinueOperation.Default), Row(8, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(3, TableIndex.MethodSemantics, EditAndContinueOperation.Default), Row(4, TableIndex.MethodSemantics, EditAndContinueOperation.Default)); CheckEncMapDefinitions(reader1, Handle(8, TableIndex.CustomAttribute), Handle(1, TableIndex.Event), Handle(3, TableIndex.MethodSemantics), Handle(4, TableIndex.MethodSemantics)); } [Fact] public void ReplaceType_AsyncLambda() { var source0 = @" using System.Threading.Tasks; class C { void F(int x) { Task.Run(async() => {}); } } "; var source1 = @" using System.Threading.Tasks; class C { void F(bool y) { Task.Run(async() => {}); } } "; var source2 = @" using System.Threading.Tasks; class C { void F(uint z) { Task.Run(async() => {}); } } "; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll, targetFramework: TargetFramework.NetStandard20); var compilation1 = compilation0.WithSource(source1); var compilation2 = compilation1.WithSource(source2); var c0 = compilation0.GetMember<NamedTypeSymbol>("C"); var c1 = compilation1.GetMember<NamedTypeSymbol>("C"); var c2 = compilation2.GetMember<NamedTypeSymbol>("C"); var f2 = c2.GetMember<MethodSymbol>("F"); // Verify full metadata contains expected rows. var bytes0 = compilation0.EmitToArray(); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var reader0 = md0.MetadataReader; CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "C", "<>c", "<<F>b__0_0>d"); var generation0 = EmitBaseline.CreateInitialBaseline( md0, EmptyLocalsProvider); // This update emulates "Reloadable" type behavior - a new type is generated instead of updating the existing one. var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Replace, null, c1))); // Verify delta metadata contains expected rows. using var md1 = diff1.GetMetadata(); var reader1 = md1.Reader; var readers = new[] { reader0, reader1 }; // A new nested type <>c is generated in C#1 CheckNames(readers, reader1.GetTypeDefNames(), "C#1", "<>c", "<<F>b__0#1_0#1>d"); CheckNames(readers, diff1.EmitResult.ChangedTypes, "C#1", "<>c", "<<F>b__0#1_0#1>d"); // This update emulates "Reloadable" type behavior - a new type is generated instead of updating the existing one. var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Replace, null, c2))); // Verify delta metadata contains expected rows. using var md2 = diff2.GetMetadata(); var reader2 = md2.Reader; readers = new[] { reader0, reader1, reader2 }; // A new nested type <>c is generated in C#2 CheckNames(readers, reader2.GetTypeDefNames(), "C#2", "<>c", "<<F>b__0#2_0#2>d"); CheckNames(readers, diff2.EmitResult.ChangedTypes, "C#2", "<>c", "<<F>b__0#2_0#2>d"); } [Fact] public void ReplaceType_AsyncLambda_InNestedType() { var source0 = @" using System.Threading.Tasks; class C { class D { void F(int x) { Task.Run(async() => {}); } } } "; var source1 = @" using System.Threading.Tasks; class C { class D { void F(bool y) { Task.Run(async() => {}); } } } "; var source2 = @" using System.Threading.Tasks; class C { class D { void F(uint z) { Task.Run(async() => {}); } } } "; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll, targetFramework: TargetFramework.NetStandard20); var compilation1 = compilation0.WithSource(source1); var compilation2 = compilation1.WithSource(source2); var c0 = compilation0.GetMember<NamedTypeSymbol>("C"); var c1 = compilation1.GetMember<NamedTypeSymbol>("C"); var c2 = compilation2.GetMember<NamedTypeSymbol>("C"); var f2 = c2.GetMember<MethodSymbol>("F"); // Verify full metadata contains expected rows. var bytes0 = compilation0.EmitToArray(); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var reader0 = md0.MetadataReader; CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "C", "D", "<>c", "<<F>b__0_0>d"); var generation0 = EmitBaseline.CreateInitialBaseline( md0, EmptyLocalsProvider); // This update emulates "Reloadable" type behavior - a new type is generated instead of updating the existing one. var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Replace, null, c1))); // Verify delta metadata contains expected rows. using var md1 = diff1.GetMetadata(); var reader1 = md1.Reader; var readers = new[] { reader0, reader1 }; // A new nested type <>c is generated in C#1 CheckNames(readers, reader1.GetTypeDefNames(), "C#1", "D", "<>c", "<<F>b__0#1_0#1>d"); CheckNames(readers, diff1.EmitResult.ChangedTypes, "C#1", "D", "<>c", "<<F>b__0#1_0#1>d"); // This update emulates "Reloadable" type behavior - a new type is generated instead of updating the existing one. var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Replace, null, c2))); // Verify delta metadata contains expected rows. using var md2 = diff2.GetMetadata(); var reader2 = md2.Reader; readers = new[] { reader0, reader1, reader2 }; // A new nested type <>c is generated in C#2 CheckNames(readers, reader2.GetTypeDefNames(), "C#2", "D", "<>c", "<<F>b__0#2_0#2>d"); CheckNames(readers, diff2.EmitResult.ChangedTypes, "C#2", "D", "<>c", "<<F>b__0#2_0#2>d"); } [Fact] public void AddNestedTypeAndMembers() { var source0 = @"class A { class B { } static object F() { return new B(); } }"; var source1 = @"class A { class B { } class C { class D { } static object F; internal static object G() { return F; } } static object F() { return C.G(); } }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var c1 = compilation1.GetMember<NamedTypeSymbol>("A.C"); var f0 = compilation0.GetMember<MethodSymbol>("A.F"); var f1 = compilation1.GetMember<MethodSymbol>("A.F"); // Verify full metadata contains expected rows. var bytes0 = compilation0.EmitToArray(); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var reader0 = md0.MetadataReader; CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "A", "B"); CheckNames(reader0, reader0.GetMethodDefNames(), "F", ".ctor", ".ctor"); Assert.Equal(1, reader0.GetTableRowCount(TableIndex.NestedClass)); var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Insert, null, c1), SemanticEdit.Create(SemanticEditKind.Update, f0, f1))); // Verify delta metadata contains expected rows. using var md1 = diff1.GetMetadata(); var reader1 = md1.Reader; var readers = new[] { reader0, reader1 }; CheckNames(readers, reader1.GetTypeDefNames(), "C", "D"); CheckNames(readers, reader1.GetMethodDefNames(), "F", "G", ".ctor", ".ctor"); CheckNames(readers, diff1.EmitResult.UpdatedMethods, "F"); CheckNames(readers, diff1.EmitResult.ChangedTypes, "A", "C", "D"); Assert.Equal(2, reader1.GetTableRowCount(TableIndex.NestedClass)); CheckEncLog(reader1, Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default), Row(5, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(6, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(2, TableIndex.StandAloneSig, EditAndContinueOperation.Default), Row(4, TableIndex.TypeDef, EditAndContinueOperation.Default), Row(5, TableIndex.TypeDef, EditAndContinueOperation.Default), Row(4, TableIndex.TypeDef, EditAndContinueOperation.AddField), Row(1, TableIndex.Field, EditAndContinueOperation.Default), Row(1, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(4, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(4, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(4, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(5, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(5, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(6, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(2, TableIndex.NestedClass, EditAndContinueOperation.Default), Row(3, TableIndex.NestedClass, EditAndContinueOperation.Default)); CheckEncMap(reader1, Handle(6, TableIndex.TypeRef), Handle(4, TableIndex.TypeDef), Handle(5, TableIndex.TypeDef), Handle(1, TableIndex.Field), Handle(1, TableIndex.MethodDef), Handle(4, TableIndex.MethodDef), Handle(5, TableIndex.MethodDef), Handle(6, TableIndex.MethodDef), Handle(5, TableIndex.MemberRef), Handle(2, TableIndex.StandAloneSig), Handle(2, TableIndex.AssemblyRef), Handle(2, TableIndex.NestedClass), Handle(3, TableIndex.NestedClass)); } /// <summary> /// Nested types should be emitted in the /// same order as full emit. /// </summary> [Fact] public void AddNestedTypesOrder() { var source0 = @"class A { class B1 { class C1 { } } class B2 { class C2 { } } }"; var source1 = @"class A { class B1 { class C1 { } } class B2 { class C2 { } } class B3 { class C3 { } } class B4 { class C4 { } } }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var bytes0 = compilation0.EmitToArray(); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var reader0 = md0.MetadataReader; CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "A", "B1", "B2", "C1", "C2"); Assert.Equal(4, reader0.GetTableRowCount(TableIndex.NestedClass)); var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Insert, null, compilation1.GetMember<NamedTypeSymbol>("A.B3")), SemanticEdit.Create(SemanticEditKind.Insert, null, compilation1.GetMember<NamedTypeSymbol>("A.B4")))); using var md1 = diff1.GetMetadata(); var reader1 = md1.Reader; var readers = new[] { reader0, reader1 }; CheckNames(readers, reader1.GetTypeDefNames(), "B3", "B4", "C3", "C4"); Assert.Equal(4, reader1.GetTableRowCount(TableIndex.NestedClass)); } [Fact] public void AddNestedGenericType() { var source0 = @"class A { class B<T> { } static object F() { return null; } }"; var source1 = @"class A { class B<T> { internal class C<U> { internal object F<V>() where V : T, new() { return new C<V>(); } } } static object F() { return new B<A>.C<B<object>>().F<A>(); } }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var f0 = compilation0.GetMember<MethodSymbol>("A.F"); var f1 = compilation1.GetMember<MethodSymbol>("A.F"); var c1 = compilation1.GetMember<NamedTypeSymbol>("A.B.C"); // Verify full metadata contains expected rows. var bytes0 = compilation0.EmitToArray(); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var reader0 = md0.MetadataReader; CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "A", "B`1"); Assert.Equal(1, reader0.GetTableRowCount(TableIndex.NestedClass)); var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Insert, null, c1), SemanticEdit.Create(SemanticEditKind.Update, f0, f1))); // Verify delta metadata contains expected rows. using var md1 = diff1.GetMetadata(); var reader1 = md1.Reader; var readers = new[] { reader0, reader1 }; CheckNames(readers, diff1.EmitResult.ChangedTypes, "A", "B`1", "C`1"); CheckNames(readers, reader1.GetTypeDefNames(), "C`1"); Assert.Equal(1, reader1.GetTableRowCount(TableIndex.NestedClass)); CheckEncLog(reader1, Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default), Row(5, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(6, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(7, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(8, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(1, TableIndex.MethodSpec, EditAndContinueOperation.Default), Row(6, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(1, TableIndex.TypeSpec, EditAndContinueOperation.Default), Row(2, TableIndex.TypeSpec, EditAndContinueOperation.Default), Row(3, TableIndex.TypeSpec, EditAndContinueOperation.Default), Row(2, TableIndex.StandAloneSig, EditAndContinueOperation.Default), Row(4, TableIndex.TypeDef, EditAndContinueOperation.Default), Row(1, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(4, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(4, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(4, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(5, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(2, TableIndex.NestedClass, EditAndContinueOperation.Default), Row(2, TableIndex.GenericParam, EditAndContinueOperation.Default), Row(3, TableIndex.GenericParam, EditAndContinueOperation.Default), Row(4, TableIndex.GenericParam, EditAndContinueOperation.Default), Row(1, TableIndex.GenericParamConstraint, EditAndContinueOperation.Default)); CheckEncMap(reader1, Handle(6, TableIndex.TypeRef), Handle(4, TableIndex.TypeDef), Handle(1, TableIndex.MethodDef), Handle(4, TableIndex.MethodDef), Handle(5, TableIndex.MethodDef), Handle(5, TableIndex.MemberRef), Handle(6, TableIndex.MemberRef), Handle(7, TableIndex.MemberRef), Handle(8, TableIndex.MemberRef), Handle(2, TableIndex.StandAloneSig), Handle(1, TableIndex.TypeSpec), Handle(2, TableIndex.TypeSpec), Handle(3, TableIndex.TypeSpec), Handle(2, TableIndex.AssemblyRef), Handle(2, TableIndex.NestedClass), Handle(2, TableIndex.GenericParam), Handle(3, TableIndex.GenericParam), Handle(4, TableIndex.GenericParam), Handle(1, TableIndex.MethodSpec), Handle(1, TableIndex.GenericParamConstraint)); } [Fact] public void AddNamespace() { var source0 = @" class C { static void Main() { } }"; var source1 = @" namespace N { class D { public static void F() { } } } class C { static void Main() => N.D.F(); }"; var source2 = @" namespace N { class D { public static void F() { } } namespace M { class E { public static void G() { } } } } class C { static void Main() => N.M.E.G(); }"; var compilation0 = CreateCompilation(source0, options: ComSafeDebugDll); var compilation1 = compilation0.WithSource(source1); var compilation2 = compilation1.WithSource(source2); var main0 = compilation0.GetMember<MethodSymbol>("C.Main"); var main1 = compilation1.GetMember<MethodSymbol>("C.Main"); var main2 = compilation2.GetMember<MethodSymbol>("C.Main"); var d1 = compilation1.GetMember<NamedTypeSymbol>("N.D"); var e2 = compilation2.GetMember<NamedTypeSymbol>("N.M.E"); using var md0 = ModuleMetadata.CreateFromImage(compilation0.EmitToArray()); var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, main0, main1), SemanticEdit.Create(SemanticEditKind.Insert, null, d1))); diff1.VerifyIL("C.Main", @" { // Code size 7 (0x7) .maxstack 0 IL_0000: call ""void N.D.F()"" IL_0005: nop IL_0006: ret }"); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, main1, main2), SemanticEdit.Create(SemanticEditKind.Insert, null, e2))); diff2.VerifyIL("C.Main", @" { // Code size 7 (0x7) .maxstack 0 IL_0000: call ""void N.M.E.G()"" IL_0005: nop IL_0006: ret }"); } [Fact] public void ModifyExplicitImplementation() { var source = @"interface I { void M(); } class C : I { void I.M() { } }"; var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source); var method0 = compilation0.GetMember<NamedTypeSymbol>("C").GetMethod("I.M"); var method1 = compilation1.GetMember<NamedTypeSymbol>("C").GetMethod("I.M"); // Verify full metadata contains expected rows. var bytes0 = compilation0.EmitToArray(); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var reader0 = md0.MetadataReader; CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "I", "C"); CheckNames(reader0, reader0.GetMethodDefNames(), "M", "I.M", ".ctor"); var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1))); // Verify delta metadata contains expected rows. using var block1 = diff1.GetMetadata(); var reader1 = block1.Reader; var readers = new[] { reader0, reader1 }; EncValidation.VerifyModuleMvid(1, reader0, reader1); CheckNames(readers, reader1.GetTypeDefNames()); CheckNames(readers, reader1.GetMethodDefNames(), "I.M"); CheckEncLog(reader1, Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default), Row(6, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(2, TableIndex.MethodDef, EditAndContinueOperation.Default)); CheckEncMap(reader1, Handle(6, TableIndex.TypeRef), Handle(2, TableIndex.MethodDef), Handle(2, TableIndex.AssemblyRef)); } [Fact] public void AddThenModifyExplicitImplementation() { var source0 = @"interface I { void M(); } class A : I { void I.M() { } } class B : I { public void M() { } }"; var source1 = @"interface I { void M(); } class A : I { void I.M() { } } class B : I { public void M() { } void I.M() { } }"; var source2 = source1; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var compilation2 = compilation0.WithSource(source2); var method1 = compilation1.GetMember<NamedTypeSymbol>("B").GetMethod("I.M"); var method2 = compilation2.GetMember<NamedTypeSymbol>("B").GetMethod("I.M"); var bytes0 = compilation0.EmitToArray(); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var reader0 = md0.MetadataReader; var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Insert, null, method1))); using var block1 = diff1.GetMetadata(); var reader1 = block1.Reader; var readers = new List<MetadataReader> { reader0, reader1 }; EncValidation.VerifyModuleMvid(1, reader0, reader1); CheckNames(readers, reader1.GetMethodDefNames(), "I.M"); CheckEncLog(reader1, Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default), Row(6, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(4, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(6, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(2, TableIndex.MethodImpl, EditAndContinueOperation.Default)); CheckEncMap(reader1, Handle(6, TableIndex.TypeRef), Handle(6, TableIndex.MethodDef), Handle(2, TableIndex.MethodImpl), Handle(2, TableIndex.AssemblyRef)); var generation1 = diff1.NextGeneration; var diff2 = compilation2.EmitDifference( generation1, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method1, method2))); using var md2 = diff2.GetMetadata(); var reader2 = md2.Reader; readers.Add(reader2); EncValidation.VerifyModuleMvid(2, reader1, reader2); CheckNames(readers, reader2.GetMethodDefNames(), "I.M"); CheckEncLog(reader2, Row(3, TableIndex.AssemblyRef, EditAndContinueOperation.Default), Row(7, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(6, TableIndex.MethodDef, EditAndContinueOperation.Default)); CheckEncMap(reader2, Handle(7, TableIndex.TypeRef), Handle(6, TableIndex.MethodDef), Handle(3, TableIndex.AssemblyRef)); } [WorkItem(930065, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/930065")] [Fact] public void ModifyConstructorBodyInPresenceOfExplicitInterfaceImplementation() { var source = @" interface I { void M(); } class C : I { public C() { } void I.M() { } } "; var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source); var method0 = compilation0.GetMember<NamedTypeSymbol>("C").InstanceConstructors.Single(); var method1 = compilation1.GetMember<NamedTypeSymbol>("C").InstanceConstructors.Single(); var bytes0 = compilation0.EmitToArray(); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var reader0 = md0.MetadataReader; var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1))); using var block1 = diff1.GetMetadata(); var reader1 = block1.Reader; var readers = new[] { reader0, reader1 }; EncValidation.VerifyModuleMvid(1, reader0, reader1); CheckNames(readers, reader1.GetTypeDefNames()); CheckNames(readers, reader1.GetMethodDefNames(), ".ctor"); CheckEncLog(reader1, Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default), Row(5, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(6, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(2, TableIndex.MethodDef, EditAndContinueOperation.Default)); CheckEncMap(reader1, Handle(6, TableIndex.TypeRef), Handle(2, TableIndex.MethodDef), Handle(5, TableIndex.MemberRef), Handle(2, TableIndex.AssemblyRef)); } [Fact] public void AddAndModifyInterfaceMembers() { var source0 = @" using System; interface I { }"; var source1 = @" using System; interface I { static int X = 10; static event Action Y; static void M() { } void N() { } static int P { get => 1; set { } } int Q { get => 1; set { } } static event Action E { add { } remove { } } event Action F { add { } remove { } } interface J { } }"; var source2 = @" using System; interface I { static int X = 2; static event Action Y; static I() { X--; } static void M() { X++; } void N() { X++; } static int P { get => 3; set { X++; } } int Q { get => 3; set { X++; } } static event Action E { add { X++; } remove { X++; } } event Action F { add { X++; } remove { X++; } } interface J { } }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll, targetFramework: TargetFramework.NetCoreApp); var compilation1 = compilation0.WithSource(source1); var compilation2 = compilation1.WithSource(source2); var x1 = compilation1.GetMember<FieldSymbol>("I.X"); var y1 = compilation1.GetMember<EventSymbol>("I.Y"); var m1 = compilation1.GetMember<MethodSymbol>("I.M"); var n1 = compilation1.GetMember<MethodSymbol>("I.N"); var p1 = compilation1.GetMember<PropertySymbol>("I.P"); var q1 = compilation1.GetMember<PropertySymbol>("I.Q"); var e1 = compilation1.GetMember<EventSymbol>("I.E"); var f1 = compilation1.GetMember<EventSymbol>("I.F"); var j1 = compilation1.GetMember<NamedTypeSymbol>("I.J"); var getP1 = compilation1.GetMember<MethodSymbol>("I.get_P"); var setP1 = compilation1.GetMember<MethodSymbol>("I.set_P"); var getQ1 = compilation1.GetMember<MethodSymbol>("I.get_Q"); var setQ1 = compilation1.GetMember<MethodSymbol>("I.set_Q"); var addE1 = compilation1.GetMember<MethodSymbol>("I.add_E"); var removeE1 = compilation1.GetMember<MethodSymbol>("I.remove_E"); var addF1 = compilation1.GetMember<MethodSymbol>("I.add_F"); var removeF1 = compilation1.GetMember<MethodSymbol>("I.remove_F"); var cctor1 = compilation1.GetMember<NamedTypeSymbol>("I").StaticConstructors.Single(); var x2 = compilation2.GetMember<FieldSymbol>("I.X"); var m2 = compilation2.GetMember<MethodSymbol>("I.M"); var n2 = compilation2.GetMember<MethodSymbol>("I.N"); var getP2 = compilation2.GetMember<MethodSymbol>("I.get_P"); var setP2 = compilation2.GetMember<MethodSymbol>("I.set_P"); var getQ2 = compilation2.GetMember<MethodSymbol>("I.get_Q"); var setQ2 = compilation2.GetMember<MethodSymbol>("I.set_Q"); var addE2 = compilation2.GetMember<MethodSymbol>("I.add_E"); var removeE2 = compilation2.GetMember<MethodSymbol>("I.remove_E"); var addF2 = compilation2.GetMember<MethodSymbol>("I.add_F"); var removeF2 = compilation2.GetMember<MethodSymbol>("I.remove_F"); var cctor2 = compilation2.GetMember<NamedTypeSymbol>("I").StaticConstructors.Single(); var bytes0 = compilation0.EmitToArray(); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var reader0 = md0.MetadataReader; var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Insert, null, x1), SemanticEdit.Create(SemanticEditKind.Insert, null, y1), SemanticEdit.Create(SemanticEditKind.Insert, null, m1), SemanticEdit.Create(SemanticEditKind.Insert, null, n1), SemanticEdit.Create(SemanticEditKind.Insert, null, p1), SemanticEdit.Create(SemanticEditKind.Insert, null, q1), SemanticEdit.Create(SemanticEditKind.Insert, null, e1), SemanticEdit.Create(SemanticEditKind.Insert, null, f1), SemanticEdit.Create(SemanticEditKind.Insert, null, j1), SemanticEdit.Create(SemanticEditKind.Insert, null, cctor1))); using var md1 = diff1.GetMetadata(); var reader1 = md1.Reader; var readers = new[] { reader0, reader1 }; CheckNames(readers, diff1.EmitResult.ChangedTypes, "I", "J"); CheckNames(readers, reader1.GetTypeDefNames(), "J"); CheckNames(readers, reader1.GetFieldDefNames(), "X", "Y"); CheckNames(readers, reader1.GetMethodDefNames(), "add_Y", "remove_Y", "M", "N", "get_P", "set_P", "get_Q", "set_Q", "add_E", "remove_E", "add_F", "remove_F", ".cctor"); Assert.Equal(1, reader1.GetTableRowCount(TableIndex.NestedClass)); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, x1, x2), SemanticEdit.Create(SemanticEditKind.Update, m1, m2), SemanticEdit.Create(SemanticEditKind.Update, n1, n2), SemanticEdit.Create(SemanticEditKind.Update, getP1, getP2), SemanticEdit.Create(SemanticEditKind.Update, setP1, setP2), SemanticEdit.Create(SemanticEditKind.Update, getQ1, getQ2), SemanticEdit.Create(SemanticEditKind.Update, setQ1, setQ2), SemanticEdit.Create(SemanticEditKind.Update, addE1, addE2), SemanticEdit.Create(SemanticEditKind.Update, removeE1, removeE2), SemanticEdit.Create(SemanticEditKind.Update, addF1, addF2), SemanticEdit.Create(SemanticEditKind.Update, removeF1, removeF2), SemanticEdit.Create(SemanticEditKind.Update, cctor1, cctor2))); using var md2 = diff2.GetMetadata(); var reader2 = md2.Reader; readers = new[] { reader0, reader1, reader2 }; CheckNames(readers, diff1.EmitResult.ChangedTypes, "I", "J"); CheckNames(readers, reader2.GetTypeDefNames()); CheckNames(readers, reader2.GetFieldDefNames(), "X"); CheckNames(readers, reader2.GetMethodDefNames(), "M", "N", "get_P", "set_P", "get_Q", "set_Q", "add_E", "remove_E", "add_F", "remove_F", ".cctor"); Assert.Equal(0, reader2.GetTableRowCount(TableIndex.NestedClass)); CheckEncLog(reader2, Row(3, TableIndex.AssemblyRef, EditAndContinueOperation.Default), Row(10, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(2, TableIndex.Event, EditAndContinueOperation.Default), Row(3, TableIndex.Event, EditAndContinueOperation.Default), Row(1, TableIndex.Field, EditAndContinueOperation.Default), Row(3, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(4, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(5, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(6, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(7, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(8, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(9, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(10, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(11, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(12, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(13, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(1, TableIndex.Property, EditAndContinueOperation.Default), Row(2, TableIndex.Property, EditAndContinueOperation.Default), Row(3, TableIndex.Param, EditAndContinueOperation.Default), Row(4, TableIndex.Param, EditAndContinueOperation.Default), Row(5, TableIndex.Param, EditAndContinueOperation.Default), Row(6, TableIndex.Param, EditAndContinueOperation.Default), Row(7, TableIndex.Param, EditAndContinueOperation.Default), Row(8, TableIndex.Param, EditAndContinueOperation.Default), Row(11, TableIndex.MethodSemantics, EditAndContinueOperation.Default), Row(12, TableIndex.MethodSemantics, EditAndContinueOperation.Default), Row(13, TableIndex.MethodSemantics, EditAndContinueOperation.Default), Row(14, TableIndex.MethodSemantics, EditAndContinueOperation.Default), Row(15, TableIndex.MethodSemantics, EditAndContinueOperation.Default), Row(16, TableIndex.MethodSemantics, EditAndContinueOperation.Default), Row(17, TableIndex.MethodSemantics, EditAndContinueOperation.Default), Row(18, TableIndex.MethodSemantics, EditAndContinueOperation.Default)); diff2.VerifyIL(@" { // Code size 14 (0xe) .maxstack 8 IL_0000: nop IL_0001: ldsfld 0x04000001 IL_0006: ldc.i4.1 IL_0007: add IL_0008: stsfld 0x04000001 IL_000d: ret } { // Code size 2 (0x2) .maxstack 8 IL_0000: ldc.i4.3 IL_0001: ret } { // Code size 20 (0x14) .maxstack 8 IL_0000: ldc.i4.2 IL_0001: stsfld 0x04000001 IL_0006: nop IL_0007: ldsfld 0x04000001 IL_000c: ldc.i4.1 IL_000d: sub IL_000e: stsfld 0x04000001 IL_0013: ret } "); } [Fact] public void AddAttributeReferences() { var source0 = @"class A : System.Attribute { } class B : System.Attribute { } class C { [A] static void M1<[B]T>() { } [B] static object F1; [A] static object P1 { get { return null; } } [B] static event D E1; } delegate void D(); "; var source1 = @"class A : System.Attribute { } class B : System.Attribute { } class C { [A] static void M1<[B]T>() { } [B] static void M2<[A]T>() { } [B] static object F1; [A] static object F2; [A] static object P1 { get { return null; } } [B] static object P2 { get { return null; } } [B] static event D E1; [A] static event D E2; } delegate void D(); "; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); // Verify full metadata contains expected rows. var bytes0 = compilation0.EmitToArray(); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var reader0 = md0.MetadataReader; CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "A", "B", "C", "D"); CheckNames(reader0, reader0.GetMethodDefNames(), ".ctor", ".ctor", "M1", "get_P1", "add_E1", "remove_E1", ".ctor", ".ctor", "Invoke", "BeginInvoke", "EndInvoke"); CheckAttributes(reader0, new CustomAttributeRow(Handle(1, TableIndex.Field), Handle(2, TableIndex.MethodDef)), new CustomAttributeRow(Handle(1, TableIndex.Property), Handle(1, TableIndex.MethodDef)), new CustomAttributeRow(Handle(1, TableIndex.Event), Handle(2, TableIndex.MethodDef)), new CustomAttributeRow(Handle(1, TableIndex.Assembly), Handle(1, TableIndex.MemberRef)), new CustomAttributeRow(Handle(1, TableIndex.Assembly), Handle(2, TableIndex.MemberRef)), new CustomAttributeRow(Handle(1, TableIndex.Assembly), Handle(3, TableIndex.MemberRef)), new CustomAttributeRow(Handle(1, TableIndex.GenericParam), Handle(2, TableIndex.MethodDef)), new CustomAttributeRow(Handle(2, TableIndex.Field), Handle(4, TableIndex.MemberRef)), new CustomAttributeRow(Handle(2, TableIndex.Field), Handle(5, TableIndex.MemberRef)), new CustomAttributeRow(Handle(3, TableIndex.MethodDef), Handle(1, TableIndex.MethodDef)), new CustomAttributeRow(Handle(5, TableIndex.MethodDef), Handle(4, TableIndex.MemberRef)), new CustomAttributeRow(Handle(6, TableIndex.MethodDef), Handle(4, TableIndex.MemberRef))); var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Insert, null, compilation1.GetMember<MethodSymbol>("C.M2")), SemanticEdit.Create(SemanticEditKind.Insert, null, compilation1.GetMember<FieldSymbol>("C.F2")), SemanticEdit.Create(SemanticEditKind.Insert, null, compilation1.GetMember<PropertySymbol>("C.P2")), SemanticEdit.Create(SemanticEditKind.Insert, null, compilation1.GetMember<EventSymbol>("C.E2")))); // Verify delta metadata contains expected rows. using var md1 = diff1.GetMetadata(); var reader1 = md1.Reader; var readers = new[] { reader0, reader1 }; CheckNames(readers, diff1.EmitResult.ChangedTypes, "C"); CheckNames(readers, reader1.GetTypeDefNames()); CheckNames(readers, reader1.GetMethodDefNames(), "M2", "get_P2", "add_E2", "remove_E2"); CheckEncLogDefinitions(reader1, Row(3, TableIndex.StandAloneSig, EditAndContinueOperation.Default), Row(4, TableIndex.StandAloneSig, EditAndContinueOperation.Default), Row(1, TableIndex.EventMap, EditAndContinueOperation.AddEvent), Row(2, TableIndex.Event, EditAndContinueOperation.Default), Row(4, TableIndex.TypeDef, EditAndContinueOperation.AddField), Row(3, TableIndex.Field, EditAndContinueOperation.Default), Row(4, TableIndex.TypeDef, EditAndContinueOperation.AddField), Row(4, TableIndex.Field, EditAndContinueOperation.Default), Row(4, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(12, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(4, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(13, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(4, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(14, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(4, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(15, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(1, TableIndex.PropertyMap, EditAndContinueOperation.AddProperty), Row(2, TableIndex.Property, EditAndContinueOperation.Default), Row(14, TableIndex.MethodDef, EditAndContinueOperation.AddParameter), Row(8, TableIndex.Param, EditAndContinueOperation.Default), Row(15, TableIndex.MethodDef, EditAndContinueOperation.AddParameter), Row(9, TableIndex.Param, EditAndContinueOperation.Default), Row(7, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(13, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(14, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(15, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(16, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(17, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(18, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(19, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(20, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(4, TableIndex.MethodSemantics, EditAndContinueOperation.Default), Row(5, TableIndex.MethodSemantics, EditAndContinueOperation.Default), Row(6, TableIndex.MethodSemantics, EditAndContinueOperation.Default), Row(2, TableIndex.GenericParam, EditAndContinueOperation.Default)); CheckEncMapDefinitions(reader1, Handle(3, TableIndex.Field), Handle(4, TableIndex.Field), Handle(12, TableIndex.MethodDef), Handle(13, TableIndex.MethodDef), Handle(14, TableIndex.MethodDef), Handle(15, TableIndex.MethodDef), Handle(8, TableIndex.Param), Handle(9, TableIndex.Param), Handle(7, TableIndex.CustomAttribute), Handle(13, TableIndex.CustomAttribute), Handle(14, TableIndex.CustomAttribute), Handle(15, TableIndex.CustomAttribute), Handle(16, TableIndex.CustomAttribute), Handle(17, TableIndex.CustomAttribute), Handle(18, TableIndex.CustomAttribute), Handle(19, TableIndex.CustomAttribute), Handle(20, TableIndex.CustomAttribute), Handle(3, TableIndex.StandAloneSig), Handle(4, TableIndex.StandAloneSig), Handle(2, TableIndex.Event), Handle(2, TableIndex.Property), Handle(4, TableIndex.MethodSemantics), Handle(5, TableIndex.MethodSemantics), Handle(6, TableIndex.MethodSemantics), Handle(2, TableIndex.GenericParam)); CheckAttributes(reader1, new CustomAttributeRow(Handle(1, TableIndex.GenericParam), Handle(1, TableIndex.MethodDef)), new CustomAttributeRow(Handle(2, TableIndex.Property), Handle(2, TableIndex.MethodDef)), new CustomAttributeRow(Handle(2, TableIndex.Event), Handle(1, TableIndex.MethodDef)), new CustomAttributeRow(Handle(3, TableIndex.Field), Handle(1, TableIndex.MethodDef)), new CustomAttributeRow(Handle(4, TableIndex.Field), Handle(11, TableIndex.MemberRef)), new CustomAttributeRow(Handle(4, TableIndex.Field), Handle(12, TableIndex.MemberRef)), new CustomAttributeRow(Handle(12, TableIndex.MethodDef), Handle(2, TableIndex.MethodDef)), new CustomAttributeRow(Handle(14, TableIndex.MethodDef), Handle(11, TableIndex.MemberRef)), new CustomAttributeRow(Handle(15, TableIndex.MethodDef), Handle(11, TableIndex.MemberRef))); } /// <summary> /// [assembly: ...] and [module: ...] attributes should /// not be included in delta metadata. /// </summary> [Fact] public void AssemblyAndModuleAttributeReferences() { var source0 = @"[assembly: System.CLSCompliantAttribute(true)] [module: System.CLSCompliantAttribute(true)] class C { }"; var source1 = @"[assembly: System.CLSCompliantAttribute(true)] [module: System.CLSCompliantAttribute(true)] class C { static void M() { } }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); // Verify full metadata contains expected rows. var bytes0 = compilation0.EmitToArray(); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var reader0 = md0.MetadataReader; CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "C"); var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Insert, null, compilation1.GetMember<MethodSymbol>("C.M")))); // Verify delta metadata contains expected rows. using var md1 = diff1.GetMetadata(); var readers = new[] { reader0, md1.Reader }; CheckNames(readers, diff1.EmitResult.ChangedTypes, "C"); CheckNames(readers, md1.Reader.GetTypeDefNames()); CheckNames(readers, md1.Reader.GetMethodDefNames(), "M"); CheckEncLog(md1.Reader, Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default), Row(7, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(2, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(2, TableIndex.MethodDef, EditAndContinueOperation.Default)); // C.M CheckEncMap(md1.Reader, Handle(7, TableIndex.TypeRef), Handle(2, TableIndex.MethodDef), Handle(2, TableIndex.AssemblyRef)); } [Fact] public void OtherReferences() { var source0 = @"delegate void D(); class C { object F; object P { get { return null; } } event D E; void M() { } }"; var source1 = @"delegate void D(); class C { object F; object P { get { return null; } } event D E; void M() { object o; o = typeof(D); o = F; o = P; E += null; } }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); // Verify full metadata contains expected rows. var bytes0 = compilation0.EmitToArray(); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var reader0 = md0.MetadataReader; CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "D", "C"); CheckNames(reader0, reader0.GetEventDefNames(), "E"); CheckNames(reader0, reader0.GetFieldDefNames(), "F", "E"); CheckNames(reader0, reader0.GetMethodDefNames(), ".ctor", "Invoke", "BeginInvoke", "EndInvoke", "get_P", "add_E", "remove_E", "M", ".ctor"); CheckNames(reader0, reader0.GetPropertyDefNames(), "P"); var method0 = compilation0.GetMember<MethodSymbol>("C.M"); // Emit delta metadata. var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider); var method1 = compilation1.GetMember<MethodSymbol>("C.M"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true))); // Verify delta metadata contains expected rows. using var md1 = diff1.GetMetadata(); var reader1 = md1.Reader; var readers = new[] { reader0, reader1 }; CheckNames(readers, diff1.EmitResult.ChangedTypes, "C"); CheckNames(readers, reader1.GetTypeDefNames()); CheckNames(readers, reader1.GetEventDefNames()); CheckNames(readers, reader1.GetFieldDefNames()); CheckNames(readers, reader1.GetMethodDefNames(), "M"); CheckNames(readers, reader1.GetPropertyDefNames()); } [Fact] public void ArrayInitializer() { var source0 = WithWindowsLineBreaks(@" class C { static void M() { int[] a = new[] { 1, 2, 3 }; } }"); var source1 = WithWindowsLineBreaks(@" class C { static void M() { int[] a = new[] { 1, 2, 3, 4 }; } }"); var compilation0 = CreateCompilation(Parse(source0, "a.cs"), options: TestOptions.DebugDll); var compilation1 = compilation0.RemoveAllSyntaxTrees().AddSyntaxTrees(Parse(source1, "a.cs")); var testData0 = new CompilationTestData(); var bytes0 = compilation0.EmitToArray(testData: testData0); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var reader0 = md0.MetadataReader; var generation0 = EmitBaseline.CreateInitialBaseline( ModuleMetadata.CreateFromImage(bytes0), testData0.GetMethodData("C.M").EncDebugInfoProvider()); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, compilation0.GetMember("C.M"), compilation1.GetMember("C.M")))); var md1 = diff1.GetMetadata(); var reader1 = md1.Reader; var readers = new[] { reader0, reader1 }; CheckNames(readers, diff1.EmitResult.ChangedTypes, "C"); CheckEncLog(reader1, Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default), Row(12, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(13, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(2, TableIndex.StandAloneSig, EditAndContinueOperation.Default), Row(1, TableIndex.MethodDef, EditAndContinueOperation.Default)); CheckEncMap(reader1, Handle(12, TableIndex.TypeRef), Handle(13, TableIndex.TypeRef), Handle(1, TableIndex.MethodDef), Handle(2, TableIndex.StandAloneSig), Handle(2, TableIndex.AssemblyRef)); diff1.VerifyIL( @"{ // Code size 25 (0x19) .maxstack 4 IL_0000: nop IL_0001: ldc.i4.4 IL_0002: newarr 0x0100000D IL_0007: dup IL_0008: ldc.i4.0 IL_0009: ldc.i4.1 IL_000a: stelem.i4 IL_000b: dup IL_000c: ldc.i4.1 IL_000d: ldc.i4.2 IL_000e: stelem.i4 IL_000f: dup IL_0010: ldc.i4.2 IL_0011: ldc.i4.3 IL_0012: stelem.i4 IL_0013: dup IL_0014: ldc.i4.3 IL_0015: ldc.i4.4 IL_0016: stelem.i4 IL_0017: stloc.0 IL_0018: ret }"); diff1.VerifyPdb(new[] { 0x06000001 }, @"<symbols> <files> <file id=""1"" name=""a.cs"" language=""C#"" checksumAlgorithm=""SHA1"" checksum=""15-9B-5B-24-28-37-02-4F-D2-2E-40-DB-1A-89-9F-4D-54-D5-95-89"" /> </files> <methods> <method token=""0x6000001""> <customDebugInfo> <using> <namespace usingCount=""0"" /> </using> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""5"" startColumn=""5"" endLine=""5"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""6"" startColumn=""9"" endLine=""6"" endColumn=""40"" document=""1"" /> <entry offset=""0x18"" startLine=""7"" startColumn=""5"" endLine=""7"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x19""> <local name=""a"" il_index=""0"" il_start=""0x0"" il_end=""0x19"" attributes=""0"" /> </scope> </method> </methods> </symbols>"); } [Fact] public void PInvokeModuleRefAndImplMap() { var source0 = @"using System.Runtime.InteropServices; class C { [DllImport(""msvcrt.dll"")] public static extern int getchar(); }"; var source1 = @"using System.Runtime.InteropServices; class C { [DllImport(""msvcrt.dll"")] public static extern int getchar(); [DllImport(""msvcrt.dll"")] public static extern int puts(string s); }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var bytes0 = compilation0.EmitToArray(); var generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), EmptyLocalsProvider); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var reader0 = md0.MetadataReader; var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Insert, null, compilation1.GetMember<MethodSymbol>("C.puts")))); using var md1 = diff1.GetMetadata(); var reader1 = md1.Reader; var readers = new[] { reader0, reader1 }; CheckNames(readers, diff1.EmitResult.ChangedTypes, "C"); CheckEncLogDefinitions(reader1, Row(2, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(3, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(3, TableIndex.MethodDef, EditAndContinueOperation.AddParameter), Row(1, TableIndex.Param, EditAndContinueOperation.Default), Row(2, TableIndex.ImplMap, EditAndContinueOperation.Default)); CheckEncMapDefinitions(reader1, Handle(3, TableIndex.MethodDef), Handle(1, TableIndex.Param), Handle(2, TableIndex.ImplMap)); } /// <summary> /// ClassLayout and FieldLayout tables. /// </summary> [Fact] public void ClassAndFieldLayout() { var source0 = @"using System.Runtime.InteropServices; [StructLayout(LayoutKind.Explicit, Pack=2)] class A { [FieldOffset(0)]internal byte F; [FieldOffset(2)]internal byte G; }"; var source1 = @"using System.Runtime.InteropServices; [StructLayout(LayoutKind.Explicit, Pack=2)] class A { [FieldOffset(0)]internal byte F; [FieldOffset(2)]internal byte G; } [StructLayout(LayoutKind.Explicit, Pack=4)] class B { [FieldOffset(0)]internal short F; [FieldOffset(4)]internal short G; }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var bytes0 = compilation0.EmitToArray(); var generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), EmptyLocalsProvider); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Insert, null, compilation1.GetMember<NamedTypeSymbol>("B")))); using var md1 = diff1.GetMetadata(); var reader1 = md1.Reader; CheckEncLog(reader1, Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default), Row(5, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(6, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(3, TableIndex.TypeDef, EditAndContinueOperation.Default), Row(3, TableIndex.TypeDef, EditAndContinueOperation.AddField), Row(3, TableIndex.Field, EditAndContinueOperation.Default), Row(3, TableIndex.TypeDef, EditAndContinueOperation.AddField), Row(4, TableIndex.Field, EditAndContinueOperation.Default), Row(3, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(2, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(2, TableIndex.ClassLayout, EditAndContinueOperation.Default), Row(3, TableIndex.FieldLayout, EditAndContinueOperation.Default), Row(4, TableIndex.FieldLayout, EditAndContinueOperation.Default)); CheckEncMap(reader1, Handle(6, TableIndex.TypeRef), Handle(3, TableIndex.TypeDef), Handle(3, TableIndex.Field), Handle(4, TableIndex.Field), Handle(2, TableIndex.MethodDef), Handle(5, TableIndex.MemberRef), Handle(2, TableIndex.ClassLayout), Handle(3, TableIndex.FieldLayout), Handle(4, TableIndex.FieldLayout), Handle(2, TableIndex.AssemblyRef)); } [Fact] public void NamespacesAndOverloads() { var compilation0 = CreateCompilation(options: TestOptions.DebugDll, source: @"class C { } namespace N { class C { } } namespace M { class C { void M1(N.C o) { } void M1(M.C o) { } void M2(N.C a, M.C b, global::C c) { M1(a); } } }"); var method0 = compilation0.GetMember<MethodSymbol>("M.C.M2"); var bytes0 = compilation0.EmitToArray(); var generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), EmptyLocalsProvider); var compilation1 = compilation0.WithSource(@" class C { } namespace N { class C { } } namespace M { class C { void M1(N.C o) { } void M1(M.C o) { } void M1(global::C o) { } void M2(N.C a, M.C b, global::C c) { M1(a); M1(b); } } }"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Insert, null, compilation1.GetMembers("M.C.M1")[2]))); diff1.VerifyIL( @"{ // Code size 2 (0x2) .maxstack 8 IL_0000: nop IL_0001: ret }"); var compilation2 = compilation1.WithSource(@" class C { } namespace N { class C { } } namespace M { class C { void M1(N.C o) { } void M1(M.C o) { } void M1(global::C o) { } void M2(N.C a, M.C b, global::C c) { M1(a); M1(b); M1(c); } } }"); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, compilation1.GetMember<MethodSymbol>("M.C.M2"), compilation2.GetMember<MethodSymbol>("M.C.M2")))); diff2.VerifyIL( @"{ // Code size 26 (0x1a) .maxstack 8 IL_0000: nop IL_0001: ldarg.0 IL_0002: ldarg.1 IL_0003: call 0x06000002 IL_0008: nop IL_0009: ldarg.0 IL_000a: ldarg.2 IL_000b: call 0x06000003 IL_0010: nop IL_0011: ldarg.0 IL_0012: ldarg.3 IL_0013: call 0x06000007 IL_0018: nop IL_0019: ret }"); } [Fact] public void TypesAndOverloads() { const string source = @"using System; struct A<T> { internal class B<U> { } } class B { } class C { static void M(A<B>.B<object> a) { M(a); M((A<B>.B<B>)null); } static void M(A<B>.B<B> a) { M(a); M((A<B>.B<object>)null); } static void M(A<B> a) { M(a); M((A<B>?)a); } static void M(Nullable<A<B>> a) { M(a); M(a.Value); } unsafe static void M(int* p) { M(p); M((byte*)p); } unsafe static void M(byte* p) { M(p); M((int*)p); } static void M(B[][] b) { M(b); M((object[][])b); } static void M(object[][] b) { M(b); M((B[][])b); } static void M(A<B[]>.B<object> b) { M(b); M((A<B[, ,]>.B<object>)null); } static void M(A<B[, ,]>.B<object> b) { M(b); M((A<B[]>.B<object>)null); } static void M(dynamic d) { M(d); M((dynamic[])d); } static void M(dynamic[] d) { M(d); M((dynamic)d); } static void M<T>(A<int>.B<T> t) where T : B { M(t); M((A<double>.B<int>)null); } static void M<T>(A<double>.B<T> t) where T : struct { M(t); M((A<int>.B<B>)null); } }"; var options = TestOptions.UnsafeDebugDll; var compilation0 = CreateCompilation(source, options: options, references: new[] { CSharpRef }); var bytes0 = compilation0.EmitToArray(); var generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), EmptyLocalsProvider); var n = compilation0.GetMembers("C.M").Length; Assert.Equal(14, n); //static void M(A<B>.B<object> a) //{ // M(a); // M((A<B>.B<B>)null); //} var compilation1 = compilation0.WithSource(source); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, compilation0.GetMembers("C.M")[0], compilation1.GetMembers("C.M")[0]))); diff1.VerifyIL( @"{ // Code size 16 (0x10) .maxstack 8 IL_0000: nop IL_0001: ldarg.0 IL_0002: call 0x06000002 IL_0007: nop IL_0008: ldnull IL_0009: call 0x06000003 IL_000e: nop IL_000f: ret }"); //static void M(A<B>.B<B> a) //{ // M(a); // M((A<B>.B<object>)null); //} var compilation2 = compilation1.WithSource(source); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, compilation1.GetMembers("C.M")[1], compilation2.GetMembers("C.M")[1]))); diff2.VerifyIL( @"{ // Code size 16 (0x10) .maxstack 8 IL_0000: nop IL_0001: ldarg.0 IL_0002: call 0x06000003 IL_0007: nop IL_0008: ldnull IL_0009: call 0x06000002 IL_000e: nop IL_000f: ret }"); //static void M(A<B> a) //{ // M(a); // M((A<B>?)a); //} var compilation3 = compilation2.WithSource(source); var diff3 = compilation3.EmitDifference( diff2.NextGeneration, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, compilation2.GetMembers("C.M")[2], compilation3.GetMembers("C.M")[2]))); diff3.VerifyIL( @"{ // Code size 21 (0x15) .maxstack 8 IL_0000: nop IL_0001: ldarg.0 IL_0002: call 0x06000004 IL_0007: nop IL_0008: ldarg.0 IL_0009: newobj 0x0A000016 IL_000e: call 0x06000005 IL_0013: nop IL_0014: ret }"); //static void M(Nullable<A<B>> a) //{ // M(a); // M(a.Value); //} var compilation4 = compilation3.WithSource(source); var diff4 = compilation4.EmitDifference( diff3.NextGeneration, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, compilation3.GetMembers("C.M")[3], compilation4.GetMembers("C.M")[3]))); diff4.VerifyIL( @"{ // Code size 22 (0x16) .maxstack 8 IL_0000: nop IL_0001: ldarg.0 IL_0002: call 0x06000005 IL_0007: nop IL_0008: ldarga.s V_0 IL_000a: call 0x0A000017 IL_000f: call 0x06000004 IL_0014: nop IL_0015: ret }"); //unsafe static void M(int* p) //{ // M(p); // M((byte*)p); //} var compilation5 = compilation4.WithSource(source); var diff5 = compilation5.EmitDifference( diff4.NextGeneration, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, compilation4.GetMembers("C.M")[4], compilation5.GetMembers("C.M")[4]))); diff5.VerifyIL( @"{ // Code size 16 (0x10) .maxstack 8 IL_0000: nop IL_0001: ldarg.0 IL_0002: call 0x06000006 IL_0007: nop IL_0008: ldarg.0 IL_0009: call 0x06000007 IL_000e: nop IL_000f: ret }"); //unsafe static void M(byte* p) //{ // M(p); // M((int*)p); //} var compilation6 = compilation5.WithSource(source); var diff6 = compilation6.EmitDifference( diff5.NextGeneration, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, compilation5.GetMembers("C.M")[5], compilation6.GetMembers("C.M")[5]))); diff6.VerifyIL( @"{ // Code size 16 (0x10) .maxstack 8 IL_0000: nop IL_0001: ldarg.0 IL_0002: call 0x06000007 IL_0007: nop IL_0008: ldarg.0 IL_0009: call 0x06000006 IL_000e: nop IL_000f: ret }"); //static void M(B[][] b) //{ // M(b); // M((object[][])b); //} var compilation7 = compilation6.WithSource(source); var diff7 = compilation7.EmitDifference( diff6.NextGeneration, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, compilation6.GetMembers("C.M")[6], compilation7.GetMembers("C.M")[6]))); diff7.VerifyIL( @"{ // Code size 18 (0x12) .maxstack 1 IL_0000: nop IL_0001: ldarg.0 IL_0002: call 0x06000008 IL_0007: nop IL_0008: ldarg.0 IL_0009: stloc.0 IL_000a: ldloc.0 IL_000b: call 0x06000009 IL_0010: nop IL_0011: ret }"); //static void M(object[][] b) //{ // M(b); // M((B[][])b); //} var compilation8 = compilation7.WithSource(source); var diff8 = compilation8.EmitDifference( diff7.NextGeneration, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, compilation7.GetMembers("C.M")[7], compilation8.GetMembers("C.M")[7]))); diff8.VerifyIL( @"{ // Code size 21 (0x15) .maxstack 8 IL_0000: nop IL_0001: ldarg.0 IL_0002: call 0x06000009 IL_0007: nop IL_0008: ldarg.0 IL_0009: castclass 0x1B00000A IL_000e: call 0x06000008 IL_0013: nop IL_0014: ret }"); //static void M(A<B[]>.B<object> b) //{ // M(b); // M((A<B[,,]>.B<object>)null); //} var compilation9 = compilation8.WithSource(source); var diff9 = compilation9.EmitDifference( diff8.NextGeneration, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, compilation8.GetMembers("C.M")[8], compilation9.GetMembers("C.M")[8]))); diff9.VerifyIL( @"{ // Code size 16 (0x10) .maxstack 8 IL_0000: nop IL_0001: ldarg.0 IL_0002: call 0x0600000A IL_0007: nop IL_0008: ldnull IL_0009: call 0x0600000B IL_000e: nop IL_000f: ret }"); //static void M(A<B[,,]>.B<object> b) //{ // M(b); // M((A<B[]>.B<object>)null); //} var compilation10 = compilation9.WithSource(source); var diff10 = compilation10.EmitDifference( diff9.NextGeneration, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, compilation9.GetMembers("C.M")[9], compilation10.GetMembers("C.M")[9]))); diff10.VerifyIL( @"{ // Code size 16 (0x10) .maxstack 8 IL_0000: nop IL_0001: ldarg.0 IL_0002: call 0x0600000B IL_0007: nop IL_0008: ldnull IL_0009: call 0x0600000A IL_000e: nop IL_000f: ret }"); // TODO: dynamic #if false //static void M(dynamic d) //{ // M(d); // M((dynamic[])d); //} previousMethod = compilation.GetMembers("C.M")[10]; compilation = compilation0.WithSource(source); generation = compilation.EmitDifference( generation, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, previousMethod, compilation.GetMembers("C.M")[10])), @"{ // Code size 16 (0x10) .maxstack 8 IL_0000: nop IL_0001: ldarg.0 IL_0002: call 0x06000002 IL_0007: nop IL_0008: ldnull IL_0009: call 0x06000003 IL_000e: nop IL_000f: ret }"); //static void M(dynamic[] d) //{ // M(d); // M((dynamic)d); //} previousMethod = compilation.GetMembers("C.M")[11]; compilation = compilation0.WithSource(source); generation = compilation.EmitDifference( generation, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, previousMethod, compilation.GetMembers("C.M")[11])), @"{ // Code size 16 (0x10) .maxstack 8 IL_0000: nop IL_0001: ldarg.0 IL_0002: call 0x06000002 IL_0007: nop IL_0008: ldnull IL_0009: call 0x06000003 IL_000e: nop IL_000f: ret }"); #endif //static void M<T>(A<int>.B<T> t) where T : B //{ // M(t); // M((A<double>.B<int>)null); //} var compilation11 = compilation10.WithSource(source); var diff11 = compilation11.EmitDifference( diff10.NextGeneration, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, compilation10.GetMembers("C.M")[12], compilation11.GetMembers("C.M")[12]))); diff11.VerifyIL( @"{ // Code size 16 (0x10) .maxstack 8 IL_0000: nop IL_0001: ldarg.0 IL_0002: call 0x2B000005 IL_0007: nop IL_0008: ldnull IL_0009: call 0x2B000006 IL_000e: nop IL_000f: ret }"); //static void M<T>(A<double>.B<T> t) where T : struct //{ // M(t); // M((A<int>.B<B>)null); //} var compilation12 = compilation11.WithSource(source); var diff12 = compilation12.EmitDifference( diff11.NextGeneration, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, compilation11.GetMembers("C.M")[13], compilation12.GetMembers("C.M")[13]))); diff12.VerifyIL( @"{ // Code size 16 (0x10) .maxstack 8 IL_0000: nop IL_0001: ldarg.0 IL_0002: call 0x2B000007 IL_0007: nop IL_0008: ldnull IL_0009: call 0x2B000008 IL_000e: nop IL_000f: ret }"); } /// <summary> /// Types should be retained in deleted locals /// for correct alignment of remaining locals. /// </summary> [Fact] public void DeletedValueTypeLocal() { var source0 = @"struct S1 { internal S1(int a, int b) { A = a; B = b; } internal int A; internal int B; } struct S2 { internal S2(int c) { C = c; } internal int C; } class C { static void Main() { var x = new S1(1, 2); var y = new S2(3); System.Console.WriteLine(y.C); } }"; var source1 = @"struct S1 { internal S1(int a, int b) { A = a; B = b; } internal int A; internal int B; } struct S2 { internal S2(int c) { C = c; } internal int C; } class C { static void Main() { var y = new S2(3); System.Console.WriteLine(y.C); } }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugExe); var compilation1 = compilation0.WithSource(source1); var testData0 = new CompilationTestData(); var bytes0 = compilation0.EmitToArray(testData: testData0); var methodData0 = testData0.GetMethodData("C.Main"); var method0 = compilation0.GetMember<MethodSymbol>("C.Main"); var generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), methodData0.EncDebugInfoProvider()); testData0.GetMethodData("C.Main").VerifyIL( @" { // Code size 31 (0x1f) .maxstack 3 .locals init (S1 V_0, //x S2 V_1) //y IL_0000: nop IL_0001: ldloca.s V_0 IL_0003: ldc.i4.1 IL_0004: ldc.i4.2 IL_0005: call ""S1..ctor(int, int)"" IL_000a: ldloca.s V_1 IL_000c: ldc.i4.3 IL_000d: call ""S2..ctor(int)"" IL_0012: ldloc.1 IL_0013: ldfld ""int S2.C"" IL_0018: call ""void System.Console.WriteLine(int)"" IL_001d: nop IL_001e: ret }"); var method1 = compilation1.GetMember<MethodSymbol>("C.Main"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true))); diff1.VerifyIL("C.Main", @"{ // Code size 22 (0x16) .maxstack 2 .locals init ([unchanged] V_0, S2 V_1) //y IL_0000: nop IL_0001: ldloca.s V_1 IL_0003: ldc.i4.3 IL_0004: call ""S2..ctor(int)"" IL_0009: ldloc.1 IL_000a: ldfld ""int S2.C"" IL_000f: call ""void System.Console.WriteLine(int)"" IL_0014: nop IL_0015: ret }"); } /// <summary> /// Instance and static constructors synthesized for /// PrivateImplementationDetails should not be /// generated for delta. /// </summary> [Fact] public void PrivateImplementationDetails() { var source = @"class C { static int[] F = new int[] { 1, 2, 3 }; int[] G = new int[] { 4, 5, 6 }; int M(int index) { return F[index] + G[index]; } }"; var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source); var testData0 = new CompilationTestData(); var bytes0 = compilation0.EmitToArray(testData: testData0); using (var md0 = ModuleMetadata.CreateFromImage(bytes0)) { var reader0 = md0.MetadataReader; var typeNames = new[] { reader0 }.GetStrings(reader0.GetTypeDefNames()); Assert.NotNull(typeNames.FirstOrDefault(n => n.StartsWith("<PrivateImplementationDetails>", StringComparison.Ordinal))); } var methodData0 = testData0.GetMethodData("C.M"); var method0 = compilation0.GetMember<MethodSymbol>("C.M"); var generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), methodData0.EncDebugInfoProvider()); var method1 = compilation1.GetMember<MethodSymbol>("C.M"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true))); diff1.VerifyIL("C.M", @" { // Code size 22 (0x16) .maxstack 3 .locals init ([int] V_0, int V_1) IL_0000: nop IL_0001: ldsfld ""int[] C.F"" IL_0006: ldarg.1 IL_0007: ldelem.i4 IL_0008: ldarg.0 IL_0009: ldfld ""int[] C.G"" IL_000e: ldarg.1 IL_000f: ldelem.i4 IL_0010: add IL_0011: stloc.1 IL_0012: br.s IL_0014 IL_0014: ldloc.1 IL_0015: ret }"); } [WorkItem(780989, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/780989")] [WorkItem(829353, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/829353")] [Fact] public void PrivateImplementationDetails_ArrayInitializer_FromMetadata() { var source0 = @"class C { static void M() { int[] a = { 1, 2, 3 }; System.Console.WriteLine(a[0]); } }"; var source1 = @"class C { static void M() { int[] a = { 1, 2, 3 }; System.Console.WriteLine(a[1]); } }"; var source2 = @"class C { static void M() { int[] a = { 4, 5, 6, 7, 8, 9, 10 }; System.Console.WriteLine(a[1]); } }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll.WithModuleName("MODULE")); var compilation1 = compilation0.WithSource(source1); var compilation2 = compilation1.WithSource(source2); var testData0 = new CompilationTestData(); var bytes0 = compilation0.EmitToArray(testData: testData0); var methodData0 = testData0.GetMethodData("C.M"); methodData0.VerifyIL( @" { // Code size 29 (0x1d) .maxstack 3 .locals init (int[] V_0) //a IL_0000: nop IL_0001: ldc.i4.3 IL_0002: newarr ""int"" IL_0007: dup IL_0008: ldtoken ""<PrivateImplementationDetails>.__StaticArrayInitTypeSize=12 <PrivateImplementationDetails>.4636993D3E1DA4E9D6B8F87B79E8F7C6D018580D52661950EABC3845C5897A4D"" IL_000d: call ""void System.Runtime.CompilerServices.RuntimeHelpers.InitializeArray(System.Array, System.RuntimeFieldHandle)"" IL_0012: stloc.0 IL_0013: ldloc.0 IL_0014: ldc.i4.0 IL_0015: ldelem.i4 IL_0016: call ""void System.Console.WriteLine(int)"" IL_001b: nop IL_001c: ret } "); var method0 = compilation0.GetMember<MethodSymbol>("C.M"); var generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), methodData0.EncDebugInfoProvider()); var method1 = compilation1.GetMember<MethodSymbol>("C.M"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true))); diff1.VerifyIL("C.M", @"{ // Code size 30 (0x1e) .maxstack 4 .locals init (int[] V_0) //a IL_0000: nop IL_0001: ldc.i4.3 IL_0002: newarr ""int"" IL_0007: dup IL_0008: ldc.i4.0 IL_0009: ldc.i4.1 IL_000a: stelem.i4 IL_000b: dup IL_000c: ldc.i4.1 IL_000d: ldc.i4.2 IL_000e: stelem.i4 IL_000f: dup IL_0010: ldc.i4.2 IL_0011: ldc.i4.3 IL_0012: stelem.i4 IL_0013: stloc.0 IL_0014: ldloc.0 IL_0015: ldc.i4.1 IL_0016: ldelem.i4 IL_0017: call ""void System.Console.WriteLine(int)"" IL_001c: nop IL_001d: ret }"); var method2 = compilation2.GetMember<MethodSymbol>("C.M"); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method1, method2, GetEquivalentNodesMap(method2, method1), preserveLocalVariables: true))); diff2.VerifyIL("C.M", @"{ // Code size 48 (0x30) .maxstack 4 .locals init ([unchanged] V_0, int[] V_1) //a IL_0000: nop IL_0001: ldc.i4.7 IL_0002: newarr ""int"" IL_0007: dup IL_0008: ldc.i4.0 IL_0009: ldc.i4.4 IL_000a: stelem.i4 IL_000b: dup IL_000c: ldc.i4.1 IL_000d: ldc.i4.5 IL_000e: stelem.i4 IL_000f: dup IL_0010: ldc.i4.2 IL_0011: ldc.i4.6 IL_0012: stelem.i4 IL_0013: dup IL_0014: ldc.i4.3 IL_0015: ldc.i4.7 IL_0016: stelem.i4 IL_0017: dup IL_0018: ldc.i4.4 IL_0019: ldc.i4.8 IL_001a: stelem.i4 IL_001b: dup IL_001c: ldc.i4.5 IL_001d: ldc.i4.s 9 IL_001f: stelem.i4 IL_0020: dup IL_0021: ldc.i4.6 IL_0022: ldc.i4.s 10 IL_0024: stelem.i4 IL_0025: stloc.1 IL_0026: ldloc.1 IL_0027: ldc.i4.1 IL_0028: ldelem.i4 IL_0029: call ""void System.Console.WriteLine(int)"" IL_002e: nop IL_002f: ret }"); } [WorkItem(780989, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/780989")] [WorkItem(829353, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/829353")] [Fact] public void PrivateImplementationDetails_ArrayInitializer_FromSource() { // PrivateImplementationDetails not needed initially. var source0 = @"class C { static object F1() { return null; } static object F2() { return null; } static object F3() { return null; } static object F4() { return null; } }"; var source1 = @"class C { static object F1() { return new[] { 1, 2, 3 }; } static object F2() { return new[] { 4, 5, 6 }; } static object F3() { return null; } static object F4() { return new[] { 7, 8, 9 }; } }"; var source2 = @"class C { static object F1() { return new[] { 1, 2, 3 } ?? new[] { 10, 11, 12 }; } static object F2() { return new[] { 4, 5, 6 }; } static object F3() { return new[] { 13, 14, 15 }; } static object F4() { return new[] { 7, 8, 9 }; } }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var compilation2 = compilation1.WithSource(source2); var testData0 = new CompilationTestData(); var bytes0 = compilation0.EmitToArray(testData: testData0); var generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), EmptyLocalsProvider); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, compilation0.GetMember<MethodSymbol>("C.F1"), compilation1.GetMember<MethodSymbol>("C.F1")), SemanticEdit.Create(SemanticEditKind.Update, compilation0.GetMember<MethodSymbol>("C.F2"), compilation1.GetMember<MethodSymbol>("C.F2")), SemanticEdit.Create(SemanticEditKind.Update, compilation0.GetMember<MethodSymbol>("C.F4"), compilation1.GetMember<MethodSymbol>("C.F4")))); diff1.VerifyIL("C.F1", @"{ // Code size 24 (0x18) .maxstack 4 .locals init (object V_0) IL_0000: nop IL_0001: ldc.i4.3 IL_0002: newarr ""int"" IL_0007: dup IL_0008: ldc.i4.0 IL_0009: ldc.i4.1 IL_000a: stelem.i4 IL_000b: dup IL_000c: ldc.i4.1 IL_000d: ldc.i4.2 IL_000e: stelem.i4 IL_000f: dup IL_0010: ldc.i4.2 IL_0011: ldc.i4.3 IL_0012: stelem.i4 IL_0013: stloc.0 IL_0014: br.s IL_0016 IL_0016: ldloc.0 IL_0017: ret }"); diff1.VerifyIL("C.F4", @"{ // Code size 25 (0x19) .maxstack 4 .locals init (object V_0) IL_0000: nop IL_0001: ldc.i4.3 IL_0002: newarr ""int"" IL_0007: dup IL_0008: ldc.i4.0 IL_0009: ldc.i4.7 IL_000a: stelem.i4 IL_000b: dup IL_000c: ldc.i4.1 IL_000d: ldc.i4.8 IL_000e: stelem.i4 IL_000f: dup IL_0010: ldc.i4.2 IL_0011: ldc.i4.s 9 IL_0013: stelem.i4 IL_0014: stloc.0 IL_0015: br.s IL_0017 IL_0017: ldloc.0 IL_0018: ret }"); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, compilation1.GetMember<MethodSymbol>("C.F1"), compilation2.GetMember<MethodSymbol>("C.F1")), SemanticEdit.Create(SemanticEditKind.Update, compilation1.GetMember<MethodSymbol>("C.F3"), compilation2.GetMember<MethodSymbol>("C.F3")))); diff2.VerifyIL("C.F1", @"{ // Code size 49 (0x31) .maxstack 4 .locals init (object V_0) IL_0000: nop IL_0001: ldc.i4.3 IL_0002: newarr ""int"" IL_0007: dup IL_0008: ldc.i4.0 IL_0009: ldc.i4.1 IL_000a: stelem.i4 IL_000b: dup IL_000c: ldc.i4.1 IL_000d: ldc.i4.2 IL_000e: stelem.i4 IL_000f: dup IL_0010: ldc.i4.2 IL_0011: ldc.i4.3 IL_0012: stelem.i4 IL_0013: dup IL_0014: brtrue.s IL_002c IL_0016: pop IL_0017: ldc.i4.3 IL_0018: newarr ""int"" IL_001d: dup IL_001e: ldc.i4.0 IL_001f: ldc.i4.s 10 IL_0021: stelem.i4 IL_0022: dup IL_0023: ldc.i4.1 IL_0024: ldc.i4.s 11 IL_0026: stelem.i4 IL_0027: dup IL_0028: ldc.i4.2 IL_0029: ldc.i4.s 12 IL_002b: stelem.i4 IL_002c: stloc.0 IL_002d: br.s IL_002f IL_002f: ldloc.0 IL_0030: ret }"); diff2.VerifyIL("C.F3", @"{ // Code size 27 (0x1b) .maxstack 4 .locals init (object V_0) IL_0000: nop IL_0001: ldc.i4.3 IL_0002: newarr ""int"" IL_0007: dup IL_0008: ldc.i4.0 IL_0009: ldc.i4.s 13 IL_000b: stelem.i4 IL_000c: dup IL_000d: ldc.i4.1 IL_000e: ldc.i4.s 14 IL_0010: stelem.i4 IL_0011: dup IL_0012: ldc.i4.2 IL_0013: ldc.i4.s 15 IL_0015: stelem.i4 IL_0016: stloc.0 IL_0017: br.s IL_0019 IL_0019: ldloc.0 IL_001a: ret }"); } /// <summary> /// Should not generate method for string switch since /// the CLR only allows adding private members. /// </summary> [WorkItem(834086, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/834086")] [Fact] public void PrivateImplementationDetails_ComputeStringHash() { var source = @"class C { static int F(string s) { switch (s) { case ""1"": return 1; case ""2"": return 2; case ""3"": return 3; case ""4"": return 4; case ""5"": return 5; case ""6"": return 6; case ""7"": return 7; default: return 0; } } }"; const string ComputeStringHashName = "ComputeStringHash"; var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source); var testData0 = new CompilationTestData(); var bytes0 = compilation0.EmitToArray(testData: testData0); var methodData0 = testData0.GetMethodData("C.F"); var method0 = compilation0.GetMember<MethodSymbol>("C.F"); var generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), methodData0.EncDebugInfoProvider()); // Should have generated call to ComputeStringHash and // added the method to <PrivateImplementationDetails>. var actualIL0 = methodData0.GetMethodIL(); Assert.True(actualIL0.Contains(ComputeStringHashName)); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var reader0 = md0.MetadataReader; CheckNames(reader0, reader0.GetMethodDefNames(), "F", ".ctor", ComputeStringHashName); var method1 = compilation1.GetMember<MethodSymbol>("C.F"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true))); // Should not have generated call to ComputeStringHash nor // added the method to <PrivateImplementationDetails>. var actualIL1 = diff1.GetMethodIL("C.F"); Assert.False(actualIL1.Contains(ComputeStringHashName)); using var md1 = diff1.GetMetadata(); var reader1 = md1.Reader; var readers = new[] { reader0, reader1 }; CheckNames(readers, reader1.GetMethodDefNames(), "F"); } /// <summary> /// Unique ids should not conflict with ids /// from previous generation. /// </summary> [WorkItem(9847, "https://github.com/dotnet/roslyn/issues/9847")] [Fact(Skip = "https://github.com/dotnet/roslyn/issues/9847")] public void UniqueIds() { var source0 = @"class C { int F() { System.Func<int> f = () => 3; return f(); } static int F(bool b) { System.Func<int> f = () => 1; System.Func<int> g = () => 2; return (b ? f : g)(); } }"; var source1 = @"class C { int F() { System.Func<int> f = () => 3; return f(); } static int F(bool b) { System.Func<int> f = () => 1; return f(); } }"; var source2 = @"class C { int F() { System.Func<int> f = () => 3; return f(); } static int F(bool b) { System.Func<int> g = () => 2; return g(); } }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var compilation2 = compilation1.WithSource(source2); var testData0 = new CompilationTestData(); var bytes0 = compilation0.EmitToArray(testData: testData0); var generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), EmptyLocalsProvider); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, compilation0.GetMembers("C.F")[1], compilation1.GetMembers("C.F")[1]))); diff1.VerifyIL("C.F", @"{ // Code size 40 (0x28) .maxstack 2 .locals init (System.Func<int> V_0, //f int V_1) IL_0000: nop IL_0001: ldsfld ""System.Func<int> C.CS$<>9__CachedAnonymousMethodDelegate6"" IL_0006: dup IL_0007: brtrue.s IL_001c IL_0009: pop IL_000a: ldnull IL_000b: ldftn ""int C.<F>b__5()"" IL_0011: newobj ""System.Func<int>..ctor(object, System.IntPtr)"" IL_0016: dup IL_0017: stsfld ""System.Func<int> C.CS$<>9__CachedAnonymousMethodDelegate6"" IL_001c: stloc.0 IL_001d: ldloc.0 IL_001e: callvirt ""int System.Func<int>.Invoke()"" IL_0023: stloc.1 IL_0024: br.s IL_0026 IL_0026: ldloc.1 IL_0027: ret }"); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, compilation1.GetMembers("C.F")[1], compilation2.GetMembers("C.F")[1]))); diff2.VerifyIL("C.F", @"{ // Code size 40 (0x28) .maxstack 2 .locals init (System.Func<int> V_0, //g int V_1) IL_0000: nop IL_0001: ldsfld ""System.Func<int> C.CS$<>9__CachedAnonymousMethodDelegate8"" IL_0006: dup IL_0007: brtrue.s IL_001c IL_0009: pop IL_000a: ldnull IL_000b: ldftn ""int C.<F>b__7()"" IL_0011: newobj ""System.Func<int>..ctor(object, System.IntPtr)"" IL_0016: dup IL_0017: stsfld ""System.Func<int> C.CS$<>9__CachedAnonymousMethodDelegate8"" IL_001c: stloc.0 IL_001d: ldloc.0 IL_001e: callvirt ""int System.Func<int>.Invoke()"" IL_0023: stloc.1 IL_0024: br.s IL_0026 IL_0026: ldloc.1 IL_0027: ret }"); } /// <summary> /// Avoid adding references from method bodies /// other than the changed methods. /// </summary> [Fact] public void ReferencesInIL() { var source0 = @"class C { static void F() { System.Console.WriteLine(1); } static void G() { System.Console.WriteLine(2); } }"; var source1 = @"class C { static void F() { System.Console.WriteLine(1); } static void G() { System.Console.Write(2); } }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); // Verify full metadata contains expected rows. var bytes0 = compilation0.EmitToArray(); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var reader0 = md0.MetadataReader; CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "C"); CheckNames(reader0, reader0.GetMethodDefNames(), "F", "G", ".ctor"); CheckNames(reader0, reader0.GetMemberRefNames(), ".ctor", ".ctor", ".ctor", "WriteLine", ".ctor"); var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider); var method0 = compilation0.GetMember<MethodSymbol>("C.G"); var method1 = compilation1.GetMember<MethodSymbol>("C.G"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create( SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true))); // "Write" should be included in string table, but "WriteLine" should not. Assert.True(diff1.MetadataDelta.IsIncluded("Write")); Assert.False(diff1.MetadataDelta.IsIncluded("WriteLine")); } /// <summary> /// Local slots must be preserved based on signature. /// </summary> [Fact] public void PreserveLocalSlots() { var source0 = @"class A<T> { } class B : A<B> { static B F() { return null; } static void M(object o) { object x = F(); A<B> y = F(); object z = F(); M(x); M(y); M(z); } static void N() { object a = F(); object b = F(); M(a); M(b); } }"; var methodNames0 = new[] { "A<T>..ctor", "B.F", "B.M", "B.N" }; var source1 = @"class A<T> { } class B : A<B> { static B F() { return null; } static void M(object o) { B z = F(); A<B> y = F(); object w = F(); M(w); M(y); } static void N() { object a = F(); object b = F(); M(a); M(b); } }"; var source2 = @"class A<T> { } class B : A<B> { static B F() { return null; } static void M(object o) { object x = F(); B z = F(); M(x); M(z); } static void N() { object a = F(); object b = F(); M(a); M(b); } }"; var source3 = @"class A<T> { } class B : A<B> { static B F() { return null; } static void M(object o) { object x = F(); B z = F(); M(x); M(z); } static void N() { object c = F(); object b = F(); M(c); M(b); } }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var compilation2 = compilation1.WithSource(source2); var compilation3 = compilation2.WithSource(source3); var method0 = compilation0.GetMember<MethodSymbol>("B.M"); var methodN = compilation0.GetMember<MethodSymbol>("B.N"); var testData0 = new CompilationTestData(); var bytes0 = compilation0.EmitToArray(testData: testData0); var generation0 = EmitBaseline.CreateInitialBaseline( ModuleMetadata.CreateFromImage(bytes0), m => testData0.GetMethodData(methodNames0[MetadataTokens.GetRowNumber(m) - 1]).GetEncDebugInfo()); #region Gen1 var method1 = compilation1.GetMember<MethodSymbol>("B.M"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true))); diff1.VerifyIL( @"{ // Code size 36 (0x24) .maxstack 1 IL_0000: nop IL_0001: call 0x06000002 IL_0006: stloc.3 IL_0007: call 0x06000002 IL_000c: stloc.1 IL_000d: call 0x06000002 IL_0012: stloc.s V_4 IL_0014: ldloc.s V_4 IL_0016: call 0x06000003 IL_001b: nop IL_001c: ldloc.1 IL_001d: call 0x06000003 IL_0022: nop IL_0023: ret }"); diff1.VerifyPdb(new[] { 0x06000001, 0x06000002, 0x06000003, 0x06000004 }, @" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method token=""0x6000003""> <customDebugInfo> <using> <namespace usingCount=""0"" /> </using> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""9"" startColumn=""5"" endLine=""9"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""10"" startColumn=""9"" endLine=""10"" endColumn=""19"" document=""1"" /> <entry offset=""0x7"" startLine=""11"" startColumn=""9"" endLine=""11"" endColumn=""22"" document=""1"" /> <entry offset=""0xd"" startLine=""12"" startColumn=""9"" endLine=""12"" endColumn=""24"" document=""1"" /> <entry offset=""0x14"" startLine=""13"" startColumn=""9"" endLine=""13"" endColumn=""14"" document=""1"" /> <entry offset=""0x1c"" startLine=""14"" startColumn=""9"" endLine=""14"" endColumn=""14"" document=""1"" /> <entry offset=""0x23"" startLine=""15"" startColumn=""5"" endLine=""15"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x24""> <local name=""z"" il_index=""3"" il_start=""0x0"" il_end=""0x24"" attributes=""0"" /> <local name=""y"" il_index=""1"" il_start=""0x0"" il_end=""0x24"" attributes=""0"" /> <local name=""w"" il_index=""4"" il_start=""0x0"" il_end=""0x24"" attributes=""0"" /> </scope> </method> </methods> </symbols>"); #endregion #region Gen2 var method2 = compilation2.GetMember<MethodSymbol>("B.M"); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method1, method2, GetEquivalentNodesMap(method2, method1), preserveLocalVariables: true))); diff2.VerifyIL( @"{ // Code size 30 (0x1e) .maxstack 1 IL_0000: nop IL_0001: call 0x06000002 IL_0006: stloc.s V_5 IL_0008: call 0x06000002 IL_000d: stloc.3 IL_000e: ldloc.s V_5 IL_0010: call 0x06000003 IL_0015: nop IL_0016: ldloc.3 IL_0017: call 0x06000003 IL_001c: nop IL_001d: ret }"); diff2.VerifyPdb(new[] { 0x06000001, 0x06000002, 0x06000003, 0x06000004 }, @" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method token=""0x6000003""> <customDebugInfo> <using> <namespace usingCount=""0"" /> </using> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""9"" startColumn=""5"" endLine=""9"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""10"" startColumn=""9"" endLine=""10"" endColumn=""24"" document=""1"" /> <entry offset=""0x8"" startLine=""11"" startColumn=""9"" endLine=""11"" endColumn=""19"" document=""1"" /> <entry offset=""0xe"" startLine=""12"" startColumn=""9"" endLine=""12"" endColumn=""14"" document=""1"" /> <entry offset=""0x16"" startLine=""13"" startColumn=""9"" endLine=""13"" endColumn=""14"" document=""1"" /> <entry offset=""0x1d"" startLine=""14"" startColumn=""5"" endLine=""14"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x1e""> <local name=""x"" il_index=""5"" il_start=""0x0"" il_end=""0x1e"" attributes=""0"" /> <local name=""z"" il_index=""3"" il_start=""0x0"" il_end=""0x1e"" attributes=""0"" /> </scope> </method> </methods> </symbols>"); #endregion #region Gen3 // Modify different method. (Previous generations // have not referenced method.) method2 = compilation2.GetMember<MethodSymbol>("B.N"); var method3 = compilation3.GetMember<MethodSymbol>("B.N"); var diff3 = compilation3.EmitDifference( diff2.NextGeneration, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method2, method3, GetEquivalentNodesMap(method3, method2), preserveLocalVariables: true))); diff3.VerifyIL( @"{ // Code size 28 (0x1c) .maxstack 1 IL_0000: nop IL_0001: call 0x06000002 IL_0006: stloc.2 IL_0007: call 0x06000002 IL_000c: stloc.1 IL_000d: ldloc.2 IL_000e: call 0x06000003 IL_0013: nop IL_0014: ldloc.1 IL_0015: call 0x06000003 IL_001a: nop IL_001b: ret }"); diff3.VerifyPdb(new[] { 0x06000001, 0x06000002, 0x06000003, 0x06000004 }, @" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method token=""0x6000004""> <customDebugInfo> <using> <namespace usingCount=""0"" /> </using> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""16"" startColumn=""5"" endLine=""16"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""17"" startColumn=""9"" endLine=""17"" endColumn=""24"" document=""1"" /> <entry offset=""0x7"" startLine=""18"" startColumn=""9"" endLine=""18"" endColumn=""24"" document=""1"" /> <entry offset=""0xd"" startLine=""19"" startColumn=""9"" endLine=""19"" endColumn=""14"" document=""1"" /> <entry offset=""0x14"" startLine=""20"" startColumn=""9"" endLine=""20"" endColumn=""14"" document=""1"" /> <entry offset=""0x1b"" startLine=""21"" startColumn=""5"" endLine=""21"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x1c""> <local name=""c"" il_index=""2"" il_start=""0x0"" il_end=""0x1c"" attributes=""0"" /> <local name=""b"" il_index=""1"" il_start=""0x0"" il_end=""0x1c"" attributes=""0"" /> </scope> </method> </methods> </symbols>"); #endregion } /// <summary> /// Preserve locals for method added after initial compilation. /// </summary> [Fact] public void PreserveLocalSlots_NewMethod() { var source0 = @"class C { }"; var source1 = @"class C { static void M() { var a = new object(); var b = string.Empty; } }"; var source2 = @"class C { static void M() { var a = 1; var b = string.Empty; } }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var compilation2 = compilation1.WithSource(source2); var bytes0 = compilation0.EmitToArray(); var generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), EmptyLocalsProvider); var m1 = compilation1.GetMember<MethodSymbol>("C.M"); var m2 = compilation2.GetMember<MethodSymbol>("C.M"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Insert, null, m1, null, preserveLocalVariables: true))); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, m1, m2, GetEquivalentNodesMap(m2, m1), preserveLocalVariables: true))); diff2.VerifyIL("C.M", @"{ // Code size 10 (0xa) .maxstack 1 .locals init ([object] V_0, string V_1, //b int V_2) //a IL_0000: nop IL_0001: ldc.i4.1 IL_0002: stloc.2 IL_0003: ldsfld ""string string.Empty"" IL_0008: stloc.1 IL_0009: ret }"); diff2.VerifyPdb(new[] { 0x06000002 }, @" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method token=""0x6000002""> <customDebugInfo> <using> <namespace usingCount=""0"" /> </using> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""4"" startColumn=""5"" endLine=""4"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""5"" startColumn=""9"" endLine=""5"" endColumn=""19"" document=""1"" /> <entry offset=""0x3"" startLine=""6"" startColumn=""9"" endLine=""6"" endColumn=""30"" document=""1"" /> <entry offset=""0x9"" startLine=""7"" startColumn=""5"" endLine=""7"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0xa""> <local name=""a"" il_index=""2"" il_start=""0x0"" il_end=""0xa"" attributes=""0"" /> <local name=""b"" il_index=""1"" il_start=""0x0"" il_end=""0xa"" attributes=""0"" /> </scope> </method> </methods> </symbols>"); } /// <summary> /// Local types should be retained, even if the local is no longer /// used by the method body, since there may be existing /// references to that slot, in a Watch window for instance. /// </summary> [WorkItem(843320, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/843320")] [Fact] public void PreserveLocalTypes() { var source0 = @"class C { static void Main() { var x = true; var y = x; System.Console.WriteLine(y); } }"; var source1 = @"class C { static void Main() { var x = ""A""; var y = x; System.Console.WriteLine(y); } }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var method0 = compilation0.GetMember<MethodSymbol>("C.Main"); var method1 = compilation1.GetMember<MethodSymbol>("C.Main"); var testData0 = new CompilationTestData(); var bytes0 = compilation0.EmitToArray(testData: testData0); var generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), testData0.GetMethodData("C.Main").EncDebugInfoProvider()); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true))); diff1.VerifyIL("C.Main", @" { // Code size 17 (0x11) .maxstack 1 .locals init ([bool] V_0, [bool] V_1, string V_2, //x string V_3) //y IL_0000: nop IL_0001: ldstr ""A"" IL_0006: stloc.2 IL_0007: ldloc.2 IL_0008: stloc.3 IL_0009: ldloc.3 IL_000a: call ""void System.Console.WriteLine(string)"" IL_000f: nop IL_0010: ret }"); } /// <summary> /// Preserve locals if SemanticEdit.PreserveLocalVariables is set. /// </summary> [Fact] public void PreserveLocalVariablesFlag() { var source = @"class C { static System.IDisposable F() { return null; } static void M() { using (F()) { } using (var x = F()) { } } }"; var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source); var testData0 = new CompilationTestData(); var bytes0 = compilation0.EmitToArray(testData: testData0); var method0 = compilation0.GetMember<MethodSymbol>("C.M"); var generation0 = EmitBaseline.CreateInitialBaseline( ModuleMetadata.CreateFromImage(bytes0), testData0.GetMethodData("C.M").EncDebugInfoProvider()); var method1 = compilation1.GetMember<MethodSymbol>("C.M"); var diff1a = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, preserveLocalVariables: false))); diff1a.VerifyIL("C.M", @" { // Code size 44 (0x2c) .maxstack 1 .locals init (System.IDisposable V_0, System.IDisposable V_1) //x IL_0000: nop IL_0001: call ""System.IDisposable C.F()"" IL_0006: stloc.0 .try { IL_0007: nop IL_0008: nop IL_0009: leave.s IL_0016 } finally { IL_000b: ldloc.0 IL_000c: brfalse.s IL_0015 IL_000e: ldloc.0 IL_000f: callvirt ""void System.IDisposable.Dispose()"" IL_0014: nop IL_0015: endfinally } IL_0016: call ""System.IDisposable C.F()"" IL_001b: stloc.1 .try { IL_001c: nop IL_001d: nop IL_001e: leave.s IL_002b } finally { IL_0020: ldloc.1 IL_0021: brfalse.s IL_002a IL_0023: ldloc.1 IL_0024: callvirt ""void System.IDisposable.Dispose()"" IL_0029: nop IL_002a: endfinally } IL_002b: ret } "); var diff1b = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, preserveLocalVariables: true))); diff1b.VerifyIL("C.M", @"{ // Code size 44 (0x2c) .maxstack 1 .locals init (System.IDisposable V_0, System.IDisposable V_1) //x IL_0000: nop IL_0001: call ""System.IDisposable C.F()"" IL_0006: stloc.0 .try { IL_0007: nop IL_0008: nop IL_0009: leave.s IL_0016 } finally { IL_000b: ldloc.0 IL_000c: brfalse.s IL_0015 IL_000e: ldloc.0 IL_000f: callvirt ""void System.IDisposable.Dispose()"" IL_0014: nop IL_0015: endfinally } IL_0016: call ""System.IDisposable C.F()"" IL_001b: stloc.1 .try { IL_001c: nop IL_001d: nop IL_001e: leave.s IL_002b } finally { IL_0020: ldloc.1 IL_0021: brfalse.s IL_002a IL_0023: ldloc.1 IL_0024: callvirt ""void System.IDisposable.Dispose()"" IL_0029: nop IL_002a: endfinally } IL_002b: ret }"); } [WorkItem(779531, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/779531")] [Fact] public void ChangeLocalType() { var source0 = @"enum E { } class C { static void M1() { var x = default(E); var y = x; var z = default(E); System.Console.WriteLine(y); } static void M2() { var x = default(E); var y = x; var z = default(E); System.Console.WriteLine(y); } }"; // Change locals in one method to type added. var source1 = @"enum E { } class A { } class C { static void M1() { var x = default(A); var y = x; var z = default(E); System.Console.WriteLine(y); } static void M2() { var x = default(E); var y = x; var z = default(E); System.Console.WriteLine(y); } }"; // Change locals in another method. var source2 = @"enum E { } class A { } class C { static void M1() { var x = default(A); var y = x; var z = default(E); System.Console.WriteLine(y); } static void M2() { var x = default(A); var y = x; var z = default(E); System.Console.WriteLine(y); } }"; // Change locals in same method. var source3 = @"enum E { } class A { } class C { static void M1() { var x = default(A); var y = x; var z = default(E); System.Console.WriteLine(y); } static void M2() { var x = default(A); var y = x; var z = default(A); System.Console.WriteLine(y); } }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var compilation2 = compilation1.WithSource(source2); var compilation3 = compilation2.WithSource(source3); var testData0 = new CompilationTestData(); var bytes0 = compilation0.EmitToArray(testData: testData0); var methodData0 = testData0.GetMethodData("C.M1"); var method0 = compilation0.GetMember<MethodSymbol>("C.M1"); var generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), methodData0.EncDebugInfoProvider()); var method1 = compilation1.GetMember<MethodSymbol>("C.M1"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Insert, null, compilation1.GetMember<NamedTypeSymbol>("A")), SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true))); diff1.VerifyIL("C.M1", @"{ // Code size 17 (0x11) .maxstack 1 .locals init ([unchanged] V_0, [unchanged] V_1, E V_2, //z A V_3, //x A V_4) //y IL_0000: nop IL_0001: ldnull IL_0002: stloc.3 IL_0003: ldloc.3 IL_0004: stloc.s V_4 IL_0006: ldc.i4.0 IL_0007: stloc.2 IL_0008: ldloc.s V_4 IL_000a: call ""void System.Console.WriteLine(object)"" IL_000f: nop IL_0010: ret }"); var method2 = compilation2.GetMember<MethodSymbol>("C.M2"); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, method1, method2, GetEquivalentNodesMap(method2, method1), preserveLocalVariables: true))); diff2.VerifyIL("C.M2", @"{ // Code size 17 (0x11) .maxstack 1 .locals init ([unchanged] V_0, [unchanged] V_1, E V_2, //z A V_3, //x A V_4) //y IL_0000: nop IL_0001: ldnull IL_0002: stloc.3 IL_0003: ldloc.3 IL_0004: stloc.s V_4 IL_0006: ldc.i4.0 IL_0007: stloc.2 IL_0008: ldloc.s V_4 IL_000a: call ""void System.Console.WriteLine(object)"" IL_000f: nop IL_0010: ret }"); var method3 = compilation3.GetMember<MethodSymbol>("C.M2"); var diff3 = compilation3.EmitDifference( diff2.NextGeneration, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, method2, method3, GetEquivalentNodesMap(method3, method2), preserveLocalVariables: true))); diff3.VerifyIL("C.M2", @"{ // Code size 18 (0x12) .maxstack 1 .locals init ([unchanged] V_0, [unchanged] V_1, [unchanged] V_2, A V_3, //x A V_4, //y A V_5) //z IL_0000: nop IL_0001: ldnull IL_0002: stloc.3 IL_0003: ldloc.3 IL_0004: stloc.s V_4 IL_0006: ldnull IL_0007: stloc.s V_5 IL_0009: ldloc.s V_4 IL_000b: call ""void System.Console.WriteLine(object)"" IL_0010: nop IL_0011: ret }"); } [Fact] public void AnonymousTypes_Update() { var source0 = MarkedSource(@" class C { static void F() { var <N:0>x = new { A = 1 }</N:0>; } } "); var source1 = MarkedSource(@" class C { static void F() { var <N:0>x = new { A = 2 }</N:0>; } } "); var source2 = MarkedSource(@" class C { static void F() { var <N:0>x = new { A = 3 }</N:0>; } } "); var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll.WithMetadataImportOptions(MetadataImportOptions.All)); var compilation1 = compilation0.WithSource(source1.Tree); var compilation2 = compilation1.WithSource(source2.Tree); var v0 = CompileAndVerify(compilation0); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var f0 = compilation0.GetMember<MethodSymbol>("C.F"); var f1 = compilation1.GetMember<MethodSymbol>("C.F"); var f2 = compilation2.GetMember<MethodSymbol>("C.F"); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); v0.VerifyIL("C.F", @" { // Code size 9 (0x9) .maxstack 1 .locals init (<>f__AnonymousType0<int> V_0) //x IL_0000: nop IL_0001: ldc.i4.1 IL_0002: newobj ""<>f__AnonymousType0<int>..ctor(int)"" IL_0007: stloc.0 IL_0008: ret } "); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true))); diff1.VerifySynthesizedMembers( "<>f__AnonymousType0<<A>j__TPar>: {Equals, GetHashCode, ToString}"); diff1.VerifyIL("C.F", @" { // Code size 9 (0x9) .maxstack 1 .locals init (<>f__AnonymousType0<int> V_0) //x IL_0000: nop IL_0001: ldc.i4.2 IL_0002: newobj ""<>f__AnonymousType0<int>..ctor(int)"" IL_0007: stloc.0 IL_0008: ret } "); // expect a single TypeRef for System.Object var md1 = diff1.GetMetadata(); AssertEx.Equal(new[] { "[0x23000002] System.Object" }, DumpTypeRefs(new[] { md0.MetadataReader, md1.Reader })); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, f1, f2, GetSyntaxMapFromMarkers(source1, source2), preserveLocalVariables: true))); diff2.VerifySynthesizedMembers( "<>f__AnonymousType0<<A>j__TPar>: {Equals, GetHashCode, ToString}"); diff2.VerifyIL("C.F", @" { // Code size 9 (0x9) .maxstack 1 .locals init (<>f__AnonymousType0<int> V_0) //x IL_0000: nop IL_0001: ldc.i4.3 IL_0002: newobj ""<>f__AnonymousType0<int>..ctor(int)"" IL_0007: stloc.0 IL_0008: ret } "); // expect a single TypeRef for System.Object var md2 = diff2.GetMetadata(); AssertEx.Equal(new[] { "[0x23000003] System.Object" }, DumpTypeRefs(new[] { md0.MetadataReader, md1.Reader, md2.Reader })); } [Fact] public void AnonymousTypes_UpdateAfterAdd() { var source0 = MarkedSource(@" class C { static void F() { } } "); var source1 = MarkedSource(@" class C { static void F() { var <N:0>x = new { A = 2 }</N:0>; } } "); var source2 = MarkedSource(@" class C { static void F() { var <N:0>x = new { A = 3 }</N:0>; } } "); var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll.WithMetadataImportOptions(MetadataImportOptions.All), targetFramework: TargetFramework.NetStandard20); var compilation1 = compilation0.WithSource(source1.Tree); var compilation2 = compilation1.WithSource(source2.Tree); var v0 = CompileAndVerify(compilation0); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var f0 = compilation0.GetMember<MethodSymbol>("C.F"); var f1 = compilation1.GetMember<MethodSymbol>("C.F"); var f2 = compilation2.GetMember<MethodSymbol>("C.F"); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true))); var md1 = diff1.GetMetadata(); diff1.VerifySynthesizedMembers( "<>f__AnonymousType0<<A>j__TPar>: {Equals, GetHashCode, ToString}"); diff1.VerifyIL("C.F", @" { // Code size 9 (0x9) .maxstack 1 .locals init (<>f__AnonymousType0<int> V_0) //x IL_0000: nop IL_0001: ldc.i4.2 IL_0002: newobj ""<>f__AnonymousType0<int>..ctor(int)"" IL_0007: stloc.0 IL_0008: ret } "); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, f1, f2, GetSyntaxMapFromMarkers(source1, source2), preserveLocalVariables: true))); diff2.VerifySynthesizedMembers( "<>f__AnonymousType0<<A>j__TPar>: {Equals, GetHashCode, ToString}"); diff2.VerifyIL("C.F", @" { // Code size 9 (0x9) .maxstack 1 .locals init (<>f__AnonymousType0<int> V_0) //x IL_0000: nop IL_0001: ldc.i4.3 IL_0002: newobj ""<>f__AnonymousType0<int>..ctor(int)"" IL_0007: stloc.0 IL_0008: ret } "); // expect a single TypeRef for System.Object var md2 = diff2.GetMetadata(); AssertEx.Equal(new[] { "[0x23000003] System.Object" }, DumpTypeRefs(new[] { md0.MetadataReader, md1.Reader, md2.Reader })); } /// <summary> /// Reuse existing anonymous types. /// </summary> [WorkItem(825903, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/825903")] [Fact] public void AnonymousTypes() { var source0 = @"namespace N { class A { static object F = new { A = 1, B = 2 }; } } namespace M { class B { static void M() { var x = new { B = 3, A = 4 }; var y = x.A; var z = new { }; } } }"; var source1 = @"namespace N { class A { static object F = new { A = 1, B = 2 }; } } namespace M { class B { static void M() { var x = new { B = 3, A = 4 }; var y = new { A = x.A }; var z = new { }; } } }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var m0 = compilation0.GetMember<MethodSymbol>("M.B.M"); var m1 = compilation1.GetMember<MethodSymbol>("M.B.M"); var testData0 = new CompilationTestData(); var bytes0 = compilation0.EmitToArray(testData: testData0); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var generation0 = EmitBaseline.CreateInitialBaseline(md0, testData0.GetMethodData("M.B.M").EncDebugInfoProvider()); var reader0 = md0.MetadataReader; CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "<>f__AnonymousType0`2", "<>f__AnonymousType1`2", "<>f__AnonymousType2", "B", "A"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, m0, m1, GetEquivalentNodesMap(m1, m0), preserveLocalVariables: true))); using var md1 = diff1.GetMetadata(); var reader1 = md1.Reader; CheckNames(new[] { reader0, reader1 }, reader1.GetTypeDefNames(), "<>f__AnonymousType3`1"); // one additional type diff1.VerifyIL("M.B.M", @" { // Code size 28 (0x1c) .maxstack 2 .locals init (<>f__AnonymousType1<int, int> V_0, //x [int] V_1, <>f__AnonymousType2 V_2, //z <>f__AnonymousType3<int> V_3) //y IL_0000: nop IL_0001: ldc.i4.3 IL_0002: ldc.i4.4 IL_0003: newobj ""<>f__AnonymousType1<int, int>..ctor(int, int)"" IL_0008: stloc.0 IL_0009: ldloc.0 IL_000a: callvirt ""int <>f__AnonymousType1<int, int>.A.get"" IL_000f: newobj ""<>f__AnonymousType3<int>..ctor(int)"" IL_0014: stloc.3 IL_0015: newobj ""<>f__AnonymousType2..ctor()"" IL_001a: stloc.2 IL_001b: ret }"); } /// <summary> /// Anonymous type names with module ids /// and gaps in indices. /// </summary> [ConditionalFact(typeof(WindowsOnly), Reason = "ILASM doesn't support Portable PDBs")] [WorkItem(2982, "https://github.com/dotnet/coreclr/issues/2982")] public void AnonymousTypes_OtherTypeNames() { var ilSource = @".assembly extern netstandard { .ver 2:0:0:0 .publickeytoken = (cc 7b 13 ff cd 2d dd 51) } // Valid signature, although not sequential index .class '<>f__AnonymousType2'<'<A>j__TPar', '<B>j__TPar'> extends object { .field public !'<A>j__TPar' A .field public !'<B>j__TPar' B } // Invalid signature, unexpected type parameter names .class '<>f__AnonymousType1'<A, B> extends object { .field public !A A .field public !B B } // Module id, duplicate index .class '<m>f__AnonymousType2`1'<'<A>j__TPar'> extends object { .field public !'<A>j__TPar' A } // Module id .class '<m>f__AnonymousType3`1'<'<B>j__TPar'> extends object { .field public !'<B>j__TPar' B } .class public C extends object { .method public specialname rtspecialname instance void .ctor() { ret } .method public static object F() { ldnull ret } }"; var source0 = @"class C { static object F() { return 0; } }"; var source1 = @"class C { static object F() { var x = new { A = new object(), B = 1 }; var y = new { A = x.A }; return y; } }"; var metadata0 = (MetadataImageReference)CompileIL(ilSource, prependDefaultHeader: false); var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll, targetFramework: TargetFramework.NetStandard20); var compilation1 = compilation0.WithSource(source1); var f0 = compilation0.GetMember<MethodSymbol>("C.F"); var f1 = compilation1.GetMember<MethodSymbol>("C.F"); var moduleMetadata0 = ((AssemblyMetadata)metadata0.GetMetadataNoCopy()).GetModules()[0]; var generation0 = EmitBaseline.CreateInitialBaseline(moduleMetadata0, m => default); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetEquivalentNodesMap(f1, f0), preserveLocalVariables: true))); using var md1 = diff1.GetMetadata(); diff1.VerifyIL("C.F", @"{ // Code size 31 (0x1f) .maxstack 2 .locals init (<>f__AnonymousType2<object, int> V_0, //x <>f__AnonymousType3<object> V_1, //y object V_2) IL_0000: nop IL_0001: newobj ""object..ctor()"" IL_0006: ldc.i4.1 IL_0007: newobj ""<>f__AnonymousType2<object, int>..ctor(object, int)"" IL_000c: stloc.0 IL_000d: ldloc.0 IL_000e: callvirt ""object <>f__AnonymousType2<object, int>.A.get"" IL_0013: newobj ""<>f__AnonymousType3<object>..ctor(object)"" IL_0018: stloc.1 IL_0019: ldloc.1 IL_001a: stloc.2 IL_001b: br.s IL_001d IL_001d: ldloc.2 IL_001e: ret }"); } /// <summary> /// Update method with anonymous type that was /// not directly referenced in previous generation. /// </summary> [Fact] public void AnonymousTypes_SkipGeneration() { var source0 = MarkedSource( @"class A { } class B { static object F() { var <N:0>x = new { A = 1 }</N:0>; return x.A; } static object G() { var <N:1>x = 1</N:1>; return x; } }"); var source1 = MarkedSource( @"class A { } class B { static object F() { var <N:0>x = new { A = 1 }</N:0>; return x.A; } static object G() { var <N:1>x = 1</N:1>; return x + 1; } }"); var source2 = MarkedSource( @"class A { } class B { static object F() { var <N:0>x = new { A = 1 }</N:0>; return x.A; } static object G() { var <N:1>x = new { A = new A() }</N:1>; var <N:2>y = new { B = 2 }</N:2>; return x.A; } }"); var source3 = MarkedSource( @"class A { } class B { static object F() { var <N:0>x = new { A = 1 }</N:0>; return x.A; } static object G() { var <N:1>x = new { A = new A() }</N:1>; var <N:2>y = new { B = 3 }</N:2>; return y.B; } }"); var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll); var compilation1 = compilation0.WithSource(source1.Tree); var compilation2 = compilation1.WithSource(source2.Tree); var compilation3 = compilation2.WithSource(source3.Tree); var v0 = CompileAndVerify(compilation0); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); var method0 = compilation0.GetMember<MethodSymbol>("B.G"); var method1 = compilation1.GetMember<MethodSymbol>("B.G"); var method2 = compilation2.GetMember<MethodSymbol>("B.G"); var method3 = compilation3.GetMember<MethodSymbol>("B.G"); var reader0 = md0.MetadataReader; CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "<>f__AnonymousType0`1", "A", "B"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true))); var md1 = diff1.GetMetadata(); var reader1 = md1.Reader; CheckNames(new[] { reader0, reader1 }, reader1.GetTypeDefNames()); // no additional types diff1.VerifyIL("B.G", @" { // Code size 16 (0x10) .maxstack 2 .locals init (int V_0, //x [object] V_1, object V_2) IL_0000: nop IL_0001: ldc.i4.1 IL_0002: stloc.0 IL_0003: ldloc.0 IL_0004: ldc.i4.1 IL_0005: add IL_0006: box ""int"" IL_000b: stloc.2 IL_000c: br.s IL_000e IL_000e: ldloc.2 IL_000f: ret }"); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method1, method2, GetSyntaxMapFromMarkers(source1, source2), preserveLocalVariables: true))); var md2 = diff2.GetMetadata(); var reader2 = md2.Reader; CheckNames(new[] { reader0, reader1, reader2 }, reader2.GetTypeDefNames(), "<>f__AnonymousType1`1"); // one additional type diff2.VerifyIL("B.G", @" { // Code size 33 (0x21) .maxstack 1 .locals init ([int] V_0, [object] V_1, [object] V_2, <>f__AnonymousType0<A> V_3, //x <>f__AnonymousType1<int> V_4, //y object V_5) IL_0000: nop IL_0001: newobj ""A..ctor()"" IL_0006: newobj ""<>f__AnonymousType0<A>..ctor(A)"" IL_000b: stloc.3 IL_000c: ldc.i4.2 IL_000d: newobj ""<>f__AnonymousType1<int>..ctor(int)"" IL_0012: stloc.s V_4 IL_0014: ldloc.3 IL_0015: callvirt ""A <>f__AnonymousType0<A>.A.get"" IL_001a: stloc.s V_5 IL_001c: br.s IL_001e IL_001e: ldloc.s V_5 IL_0020: ret }"); var diff3 = compilation3.EmitDifference( diff2.NextGeneration, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method2, method3, GetSyntaxMapFromMarkers(source2, source3), preserveLocalVariables: true))); var md3 = diff3.GetMetadata(); var reader3 = md3.Reader; CheckNames(new[] { reader0, reader1, reader2, reader3 }, reader3.GetTypeDefNames()); // no additional types diff3.VerifyIL("B.G", @" { // Code size 39 (0x27) .maxstack 1 .locals init ([int] V_0, [object] V_1, [object] V_2, <>f__AnonymousType0<A> V_3, //x <>f__AnonymousType1<int> V_4, //y [object] V_5, object V_6) IL_0000: nop IL_0001: newobj ""A..ctor()"" IL_0006: newobj ""<>f__AnonymousType0<A>..ctor(A)"" IL_000b: stloc.3 IL_000c: ldc.i4.3 IL_000d: newobj ""<>f__AnonymousType1<int>..ctor(int)"" IL_0012: stloc.s V_4 IL_0014: ldloc.s V_4 IL_0016: callvirt ""int <>f__AnonymousType1<int>.B.get"" IL_001b: box ""int"" IL_0020: stloc.s V_6 IL_0022: br.s IL_0024 IL_0024: ldloc.s V_6 IL_0026: ret }"); } /// <summary> /// Update another method (without directly referencing /// anonymous type) after updating method with anonymous type. /// </summary> [Fact] public void AnonymousTypes_SkipGeneration_2() { var source0 = @"class C { static object F() { var x = new { A = 1 }; return x.A; } static object G() { var x = 1; return x; } }"; var source1 = @"class C { static object F() { var x = new { A = 2, B = 3 }; return x.A; } static object G() { var x = 1; return x; } }"; var source2 = @"class C { static object F() { var x = new { A = 2, B = 3 }; return x.A; } static object G() { var x = 1; return x + 1; } }"; var source3 = @"class C { static object F() { var x = new { A = 2, B = 3 }; return x.A; } static object G() { var x = new { A = (object)null }; var y = new { A = 'a', B = 'b' }; return x; } }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var compilation2 = compilation1.WithSource(source2); var compilation3 = compilation2.WithSource(source3); var f0 = compilation0.GetMember<MethodSymbol>("C.F"); var f1 = compilation1.GetMember<MethodSymbol>("C.F"); var g1 = compilation1.GetMember<MethodSymbol>("C.G"); var g2 = compilation2.GetMember<MethodSymbol>("C.G"); var g3 = compilation3.GetMember<MethodSymbol>("C.G"); var testData0 = new CompilationTestData(); var bytes0 = compilation0.EmitToArray(testData: testData0); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var generation0 = EmitBaseline.CreateInitialBaseline( md0, m => md0.MetadataReader.GetString(md0.MetadataReader.GetMethodDefinition(m).Name) switch { "F" => testData0.GetMethodData("C.F").GetEncDebugInfo(), "G" => testData0.GetMethodData("C.G").GetEncDebugInfo(), _ => default, }); var reader0 = md0.MetadataReader; CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "<>f__AnonymousType0`1", "C"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetEquivalentNodesMap(f1, f0), preserveLocalVariables: true))); using var md1 = diff1.GetMetadata(); var reader1 = md1.Reader; var readers = new List<MetadataReader> { reader0, reader1 }; CheckNames(readers, reader1.GetTypeDefNames(), "<>f__AnonymousType1`2"); // one additional type var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, g1, g2, GetEquivalentNodesMap(g2, g1), preserveLocalVariables: true))); using var md2 = diff2.GetMetadata(); var reader2 = md2.Reader; readers.Add(reader2); CheckNames(readers, reader2.GetTypeDefNames()); // no additional types var diff3 = compilation3.EmitDifference( diff2.NextGeneration, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, g2, g3, GetEquivalentNodesMap(g3, g2), preserveLocalVariables: true))); using var md3 = diff3.GetMetadata(); var reader3 = md3.Reader; readers.Add(reader3); CheckNames(readers, reader3.GetTypeDefNames()); // no additional types } /// <summary> /// Local from previous generation is of an anonymous /// type not available in next generation. /// </summary> [Fact] public void AnonymousTypes_AddThenDelete() { var source0 = @"class C { object A; static object F() { var x = new C(); var y = x.A; return y; } }"; var source1 = @"class C { static object F() { var x = new { A = new object() }; var y = x.A; return y; } }"; var source2 = @"class C { static object F() { var x = new { A = new object(), B = 2 }; var y = x.A; y = new { B = new object() }.B; return y; } }"; var source3 = @"class C { static object F() { var x = new { A = new object(), B = 3 }; var y = x.A; return y; } }"; var source4 = @"class C { static object F() { var x = new { B = 4, A = new object() }; var y = x.A; return y; } }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var compilation2 = compilation1.WithSource(source2); var compilation3 = compilation2.WithSource(source3); var compilation4 = compilation3.WithSource(source4); var testData0 = new CompilationTestData(); var bytes0 = compilation0.EmitToArray(testData: testData0); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var generation0 = EmitBaseline.CreateInitialBaseline(md0, testData0.GetMethodData("C.F").EncDebugInfoProvider()); var method0 = compilation0.GetMember<MethodSymbol>("C.F"); var reader0 = md0.MetadataReader; CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "C"); var method1 = compilation1.GetMember<MethodSymbol>("C.F"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true))); using var md1 = diff1.GetMetadata(); var reader1 = md1.Reader; CheckNames(new[] { reader0, reader1 }, reader1.GetTypeDefNames(), "<>f__AnonymousType0`1"); // one additional type diff1.VerifyIL("C.F", @" { // Code size 27 (0x1b) .maxstack 1 .locals init ([unchanged] V_0, object V_1, //y [object] V_2, <>f__AnonymousType0<object> V_3, //x object V_4) IL_0000: nop IL_0001: newobj ""object..ctor()"" IL_0006: newobj ""<>f__AnonymousType0<object>..ctor(object)"" IL_000b: stloc.3 IL_000c: ldloc.3 IL_000d: callvirt ""object <>f__AnonymousType0<object>.A.get"" IL_0012: stloc.1 IL_0013: ldloc.1 IL_0014: stloc.s V_4 IL_0016: br.s IL_0018 IL_0018: ldloc.s V_4 IL_001a: ret }"); var method2 = compilation2.GetMember<MethodSymbol>("C.F"); } [Fact] public void AnonymousTypes_DifferentCase() { var source0 = MarkedSource(@" class C { static void M() { var <N:0>x = new { A = 1, B = 2 }</N:0>; var <N:1>y = new { a = 3, b = 4 }</N:1>; } }"); var source1 = MarkedSource(@" class C { static void M() { var <N:0>x = new { a = 1, B = 2 }</N:0>; var <N:1>y = new { AB = 3 }</N:1>; } }"); var source2 = MarkedSource(@" class C { static void M() { var <N:0>x = new { a = 1, B = 2 }</N:0>; var <N:1>y = new { Ab = 5 }</N:1>; } }"); var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll); var compilation1 = compilation0.WithSource(source1.Tree); var compilation2 = compilation1.WithSource(source2.Tree); var v0 = CompileAndVerify(compilation0); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var reader0 = md0.MetadataReader; var m0 = compilation0.GetMember<MethodSymbol>("C.M"); var m1 = compilation1.GetMember<MethodSymbol>("C.M"); var m2 = compilation2.GetMember<MethodSymbol>("C.M"); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "<>f__AnonymousType0`2", "<>f__AnonymousType1`2", "C"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, m0, m1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true))); var reader1 = diff1.GetMetadata().Reader; CheckNames(new[] { reader0, reader1 }, reader1.GetTypeDefNames(), "<>f__AnonymousType2`2", "<>f__AnonymousType3`1"); // the first two slots can't be reused since the type changed diff1.VerifyIL("C.M", @"{ // Code size 17 (0x11) .maxstack 2 .locals init ([unchanged] V_0, [unchanged] V_1, <>f__AnonymousType2<int, int> V_2, //x <>f__AnonymousType3<int> V_3) //y IL_0000: nop IL_0001: ldc.i4.1 IL_0002: ldc.i4.2 IL_0003: newobj ""<>f__AnonymousType2<int, int>..ctor(int, int)"" IL_0008: stloc.2 IL_0009: ldc.i4.3 IL_000a: newobj ""<>f__AnonymousType3<int>..ctor(int)"" IL_000f: stloc.3 IL_0010: ret }"); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, m1, m2, GetSyntaxMapFromMarkers(source1, source2), preserveLocalVariables: true))); var reader2 = diff2.GetMetadata().Reader; CheckNames(new[] { reader0, reader1, reader2 }, reader2.GetTypeDefNames(), "<>f__AnonymousType4`1"); // we can reuse slot for "x", it's type haven't changed diff2.VerifyIL("C.M", @"{ // Code size 18 (0x12) .maxstack 2 .locals init ([unchanged] V_0, [unchanged] V_1, <>f__AnonymousType2<int, int> V_2, //x [unchanged] V_3, <>f__AnonymousType4<int> V_4) //y IL_0000: nop IL_0001: ldc.i4.1 IL_0002: ldc.i4.2 IL_0003: newobj ""<>f__AnonymousType2<int, int>..ctor(int, int)"" IL_0008: stloc.2 IL_0009: ldc.i4.5 IL_000a: newobj ""<>f__AnonymousType4<int>..ctor(int)"" IL_000f: stloc.s V_4 IL_0011: ret }"); } [Fact] public void AnonymousTypes_Nested1() { var template = @" using System; using System.Linq; class C { static void F(string[] args) { var <N:0>result = from a in args <N:1>let x = a.Reverse()</N:1> <N:2>let y = x.Reverse()</N:2> <N:3>where x.SequenceEqual(y)</N:3> <N:4>select new { Value = a, Length = a.Length }</N:4></N:0>; Console.WriteLine(<<VALUE>>); } }"; var source0 = MarkedSource(template.Replace("<<VALUE>>", "0")); var source1 = MarkedSource(template.Replace("<<VALUE>>", "1")); var source2 = MarkedSource(template.Replace("<<VALUE>>", "2")); var compilation0 = CreateCompilationWithMscorlib45(new[] { source0.Tree }, new[] { SystemCoreRef }, options: ComSafeDebugDll); var compilation1 = compilation0.WithSource(source1.Tree); var compilation2 = compilation0.WithSource(source2.Tree); var v0 = CompileAndVerify(compilation0); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var f0 = compilation0.GetMember<MethodSymbol>("C.F"); var f1 = compilation1.GetMember<MethodSymbol>("C.F"); var f2 = compilation2.GetMember<MethodSymbol>("C.F"); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); var expectedIL = @" { // Code size 155 (0x9b) .maxstack 3 .locals init (System.Collections.Generic.IEnumerable<<anonymous type: string Value, int Length>> V_0) //result IL_0000: nop IL_0001: ldarg.0 IL_0002: ldsfld ""System.Func<string, <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>> C.<>c.<>9__0_0"" IL_0007: dup IL_0008: brtrue.s IL_0021 IL_000a: pop IL_000b: ldsfld ""C.<>c C.<>c.<>9"" IL_0010: ldftn ""<anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> C.<>c.<F>b__0_0(string)"" IL_0016: newobj ""System.Func<string, <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>>..ctor(object, System.IntPtr)"" IL_001b: dup IL_001c: stsfld ""System.Func<string, <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>> C.<>c.<>9__0_0"" IL_0021: call ""System.Collections.Generic.IEnumerable<<anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>> System.Linq.Enumerable.Select<string, <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>>(System.Collections.Generic.IEnumerable<string>, System.Func<string, <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>>)"" IL_0026: ldsfld ""System.Func<<anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>, <anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>> C.<>c.<>9__0_1"" IL_002b: dup IL_002c: brtrue.s IL_0045 IL_002e: pop IL_002f: ldsfld ""C.<>c C.<>c.<>9"" IL_0034: ldftn ""<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y> C.<>c.<F>b__0_1(<anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>)"" IL_003a: newobj ""System.Func<<anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>, <anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>>..ctor(object, System.IntPtr)"" IL_003f: dup IL_0040: stsfld ""System.Func<<anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>, <anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>> C.<>c.<>9__0_1"" IL_0045: call ""System.Collections.Generic.IEnumerable<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>> System.Linq.Enumerable.Select<<anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>, <anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>>(System.Collections.Generic.IEnumerable<<anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>>, System.Func<<anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>, <anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>>)"" IL_004a: ldsfld ""System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, bool> C.<>c.<>9__0_2"" IL_004f: dup IL_0050: brtrue.s IL_0069 IL_0052: pop IL_0053: ldsfld ""C.<>c C.<>c.<>9"" IL_0058: ldftn ""bool C.<>c.<F>b__0_2(<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>)"" IL_005e: newobj ""System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, bool>..ctor(object, System.IntPtr)"" IL_0063: dup IL_0064: stsfld ""System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, bool> C.<>c.<>9__0_2"" IL_0069: call ""System.Collections.Generic.IEnumerable<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>> System.Linq.Enumerable.Where<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>>(System.Collections.Generic.IEnumerable<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>>, System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, bool>)"" IL_006e: ldsfld ""System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, <anonymous type: string Value, int Length>> C.<>c.<>9__0_3"" IL_0073: dup IL_0074: brtrue.s IL_008d IL_0076: pop IL_0077: ldsfld ""C.<>c C.<>c.<>9"" IL_007c: ldftn ""<anonymous type: string Value, int Length> C.<>c.<F>b__0_3(<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>)"" IL_0082: newobj ""System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, <anonymous type: string Value, int Length>>..ctor(object, System.IntPtr)"" IL_0087: dup IL_0088: stsfld ""System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, <anonymous type: string Value, int Length>> C.<>c.<>9__0_3"" IL_008d: call ""System.Collections.Generic.IEnumerable<<anonymous type: string Value, int Length>> System.Linq.Enumerable.Select<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, <anonymous type: string Value, int Length>>(System.Collections.Generic.IEnumerable<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>>, System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, <anonymous type: string Value, int Length>>)"" IL_0092: stloc.0 IL_0093: ldc.i4.<<VALUE>> IL_0094: call ""void System.Console.WriteLine(int)"" IL_0099: nop IL_009a: ret } "; v0.VerifyIL("C.F", expectedIL.Replace("<<VALUE>>", "0")); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true))); diff1.VerifySynthesizedMembers( "C: {<>c}", "C.<>c: {<>9__0_0, <>9__0_1, <>9__0_2, <>9__0_3, <F>b__0_0, <F>b__0_1, <F>b__0_2, <F>b__0_3}", "<>f__AnonymousType2<<Value>j__TPar, <Length>j__TPar>: {Equals, GetHashCode, ToString}", "<>f__AnonymousType1<<<>h__TransparentIdentifier0>j__TPar, <y>j__TPar>: {Equals, GetHashCode, ToString}", "<>f__AnonymousType0<<a>j__TPar, <x>j__TPar>: {Equals, GetHashCode, ToString}"); diff1.VerifyIL("C.F", expectedIL.Replace("<<VALUE>>", "1")); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, f1, f2, GetSyntaxMapFromMarkers(source1, source2), preserveLocalVariables: true))); diff2.VerifySynthesizedMembers( "C: {<>c}", "C.<>c: {<>9__0_0, <>9__0_1, <>9__0_2, <>9__0_3, <F>b__0_0, <F>b__0_1, <F>b__0_2, <F>b__0_3}", "<>f__AnonymousType2<<Value>j__TPar, <Length>j__TPar>: {Equals, GetHashCode, ToString}", "<>f__AnonymousType1<<<>h__TransparentIdentifier0>j__TPar, <y>j__TPar>: {Equals, GetHashCode, ToString}", "<>f__AnonymousType0<<a>j__TPar, <x>j__TPar>: {Equals, GetHashCode, ToString}"); diff2.VerifyIL("C.F", expectedIL.Replace("<<VALUE>>", "2")); } [Fact] public void AnonymousTypes_Nested2() { var template = @" using System; using System.Linq; class C { static void F(string[] args) { var <N:0>result = from a in args <N:1>let x = a.Reverse()</N:1> <N:2>let y = x.Reverse()</N:2> <N:3>where x.SequenceEqual(y)</N:3> <N:4>select new { Value = a, Length = a.Length }</N:4></N:0>; Console.WriteLine(<<VALUE>>); } }"; var source0 = MarkedSource(template.Replace("<<VALUE>>", "0")); var source1 = MarkedSource(template.Replace("<<VALUE>>", "1")); var source2 = MarkedSource(template.Replace("<<VALUE>>", "2")); var compilation0 = CreateCompilationWithMscorlib45(new[] { source0.Tree }, new[] { SystemCoreRef }, options: ComSafeDebugDll); var compilation1 = compilation0.WithSource(source1.Tree); var compilation2 = compilation0.WithSource(source2.Tree); var v0 = CompileAndVerify(compilation0); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var f0 = compilation0.GetMember<MethodSymbol>("C.F"); var f1 = compilation1.GetMember<MethodSymbol>("C.F"); var f2 = compilation2.GetMember<MethodSymbol>("C.F"); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); var expectedIL = @" { // Code size 155 (0x9b) .maxstack 3 .locals init (System.Collections.Generic.IEnumerable<<anonymous type: string Value, int Length>> V_0) //result IL_0000: nop IL_0001: ldarg.0 IL_0002: ldsfld ""System.Func<string, <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>> C.<>c.<>9__0_0"" IL_0007: dup IL_0008: brtrue.s IL_0021 IL_000a: pop IL_000b: ldsfld ""C.<>c C.<>c.<>9"" IL_0010: ldftn ""<anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> C.<>c.<F>b__0_0(string)"" IL_0016: newobj ""System.Func<string, <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>>..ctor(object, System.IntPtr)"" IL_001b: dup IL_001c: stsfld ""System.Func<string, <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>> C.<>c.<>9__0_0"" IL_0021: call ""System.Collections.Generic.IEnumerable<<anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>> System.Linq.Enumerable.Select<string, <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>>(System.Collections.Generic.IEnumerable<string>, System.Func<string, <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>>)"" IL_0026: ldsfld ""System.Func<<anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>, <anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>> C.<>c.<>9__0_1"" IL_002b: dup IL_002c: brtrue.s IL_0045 IL_002e: pop IL_002f: ldsfld ""C.<>c C.<>c.<>9"" IL_0034: ldftn ""<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y> C.<>c.<F>b__0_1(<anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>)"" IL_003a: newobj ""System.Func<<anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>, <anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>>..ctor(object, System.IntPtr)"" IL_003f: dup IL_0040: stsfld ""System.Func<<anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>, <anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>> C.<>c.<>9__0_1"" IL_0045: call ""System.Collections.Generic.IEnumerable<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>> System.Linq.Enumerable.Select<<anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>, <anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>>(System.Collections.Generic.IEnumerable<<anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>>, System.Func<<anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>, <anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>>)"" IL_004a: ldsfld ""System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, bool> C.<>c.<>9__0_2"" IL_004f: dup IL_0050: brtrue.s IL_0069 IL_0052: pop IL_0053: ldsfld ""C.<>c C.<>c.<>9"" IL_0058: ldftn ""bool C.<>c.<F>b__0_2(<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>)"" IL_005e: newobj ""System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, bool>..ctor(object, System.IntPtr)"" IL_0063: dup IL_0064: stsfld ""System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, bool> C.<>c.<>9__0_2"" IL_0069: call ""System.Collections.Generic.IEnumerable<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>> System.Linq.Enumerable.Where<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>>(System.Collections.Generic.IEnumerable<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>>, System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, bool>)"" IL_006e: ldsfld ""System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, <anonymous type: string Value, int Length>> C.<>c.<>9__0_3"" IL_0073: dup IL_0074: brtrue.s IL_008d IL_0076: pop IL_0077: ldsfld ""C.<>c C.<>c.<>9"" IL_007c: ldftn ""<anonymous type: string Value, int Length> C.<>c.<F>b__0_3(<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>)"" IL_0082: newobj ""System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, <anonymous type: string Value, int Length>>..ctor(object, System.IntPtr)"" IL_0087: dup IL_0088: stsfld ""System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, <anonymous type: string Value, int Length>> C.<>c.<>9__0_3"" IL_008d: call ""System.Collections.Generic.IEnumerable<<anonymous type: string Value, int Length>> System.Linq.Enumerable.Select<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, <anonymous type: string Value, int Length>>(System.Collections.Generic.IEnumerable<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>>, System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, <anonymous type: string Value, int Length>>)"" IL_0092: stloc.0 IL_0093: ldc.i4.<<VALUE>> IL_0094: call ""void System.Console.WriteLine(int)"" IL_0099: nop IL_009a: ret } "; v0.VerifyIL("C.F", expectedIL.Replace("<<VALUE>>", "0")); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true))); diff1.VerifySynthesizedMembers( "C: {<>c}", "C.<>c: {<>9__0_0, <>9__0_1, <>9__0_2, <>9__0_3, <F>b__0_0, <F>b__0_1, <F>b__0_2, <F>b__0_3}", "<>f__AnonymousType2<<Value>j__TPar, <Length>j__TPar>: {Equals, GetHashCode, ToString}", "<>f__AnonymousType1<<<>h__TransparentIdentifier0>j__TPar, <y>j__TPar>: {Equals, GetHashCode, ToString}", "<>f__AnonymousType0<<a>j__TPar, <x>j__TPar>: {Equals, GetHashCode, ToString}"); diff1.VerifyIL("C.F", expectedIL.Replace("<<VALUE>>", "1")); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, f1, f2, GetSyntaxMapFromMarkers(source1, source2), preserveLocalVariables: true))); diff2.VerifySynthesizedMembers( "C: {<>c}", "C.<>c: {<>9__0_0, <>9__0_1, <>9__0_2, <>9__0_3, <F>b__0_0, <F>b__0_1, <F>b__0_2, <F>b__0_3}", "<>f__AnonymousType2<<Value>j__TPar, <Length>j__TPar>: {Equals, GetHashCode, ToString}", "<>f__AnonymousType1<<<>h__TransparentIdentifier0>j__TPar, <y>j__TPar>: {Equals, GetHashCode, ToString}", "<>f__AnonymousType0<<a>j__TPar, <x>j__TPar>: {Equals, GetHashCode, ToString}"); diff2.VerifyIL("C.F", expectedIL.Replace("<<VALUE>>", "2")); } [Fact] public void AnonymousTypes_Query1() { var source0 = MarkedSource(@" using System.Linq; class C { static void F(string[] args) { args = new[] { ""a"", ""bB"", ""Cc"", ""DD"" }; var <N:4>result = from a in args <N:0>let x = a.Reverse()</N:0> <N:1>let y = x.Reverse()</N:1> <N:2>where x.SequenceEqual(y)</N:2> <N:3>select new { Value = a, Length = a.Length }</N:3></N:4>; var <N:8>newArgs = from a in result <N:5>let value = a.Value</N:5> <N:6>let length = a.Length</N:6> <N:7>where value.Length == length</N:7> select value</N:8>; args = args.Concat(newArgs).ToArray(); System.Diagnostics.Debugger.Break(); result.ToString(); } } "); var source1 = MarkedSource(@" using System.Linq; class C { static void F(string[] args) { args = new[] { ""a"", ""bB"", ""Cc"", ""DD"" }; var list = false ? null : new { Head = (dynamic)null, Tail = (dynamic)null }; for (int i = 0; i < 10; i++) { var <N:4>result = from a in args <N:0>let x = a.Reverse()</N:0> <N:1>let y = x.Reverse()</N:1> <N:2>where x.SequenceEqual(y)</N:2> orderby a.Length ascending, a descending <N:3>select new { Value = a, Length = x.Count() }</N:3></N:4>; var linked = result.Aggregate( false ? new { Head = (string)null, Tail = (dynamic)null } : null, (total, curr) => new { Head = curr.Value, Tail = (dynamic)total }); var str = linked?.Tail?.Head; var <N:8>newArgs = from a in result <N:5>let value = a.Value</N:5> <N:6>let length = a.Length</N:6> <N:7>where value.Length == length</N:7> select value + value</N:8>; args = args.Concat(newArgs).ToArray(); list = new { Head = (dynamic)i, Tail = (dynamic)list }; System.Diagnostics.Debugger.Break(); } System.Diagnostics.Debugger.Break(); } } "); var compilation0 = CreateCompilationWithMscorlib45(new[] { source0.Tree }, new[] { SystemCoreRef, CSharpRef }, options: ComSafeDebugDll); var compilation1 = compilation0.WithSource(source1.Tree); var v0 = CompileAndVerify(compilation0); v0.VerifyDiagnostics(); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var f0 = compilation0.GetMember<MethodSymbol>("C.F"); var f1 = compilation1.GetMember<MethodSymbol>("C.F"); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); v0.VerifyLocalSignature("C.F", @" .locals init (System.Collections.Generic.IEnumerable<<anonymous type: string Value, int Length>> V_0, //result System.Collections.Generic.IEnumerable<string> V_1) //newArgs "); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true))); diff1.VerifySynthesizedMembers( "C.<>o__0#1: {<>p__0}", "C: {<>o__0#1, <>c}", "C.<>c: {<>9__0_0, <>9__0_1, <>9__0_2, <>9__0_3#1, <>9__0_4#1, <>9__0_3, <>9__0_6#1, <>9__0_4, <>9__0_5, <>9__0_6, <>9__0_10#1, <F>b__0_0, <F>b__0_1, <F>b__0_2, <F>b__0_3#1, <F>b__0_4#1, <F>b__0_3, <F>b__0_6#1, <F>b__0_4, <F>b__0_5, <F>b__0_6, <F>b__0_10#1}", "<>f__AnonymousType4<<<>h__TransparentIdentifier0>j__TPar, <length>j__TPar>: {Equals, GetHashCode, ToString}", "<>f__AnonymousType2<<Value>j__TPar, <Length>j__TPar>: {Equals, GetHashCode, ToString}", "<>f__AnonymousType5<<Head>j__TPar, <Tail>j__TPar>: {Equals, GetHashCode, ToString}", "<>f__AnonymousType3<<a>j__TPar, <value>j__TPar>: {Equals, GetHashCode, ToString}", "<>f__AnonymousType0<<a>j__TPar, <x>j__TPar>: {Equals, GetHashCode, ToString}", "<>f__AnonymousType1<<<>h__TransparentIdentifier0>j__TPar, <y>j__TPar>: {Equals, GetHashCode, ToString}"); diff1.VerifyLocalSignature("C.F", @" .locals init (System.Collections.Generic.IEnumerable<<anonymous type: string Value, int Length>> V_0, //result System.Collections.Generic.IEnumerable<string> V_1, //newArgs <>f__AnonymousType5<dynamic, dynamic> V_2, //list int V_3, //i <>f__AnonymousType5<string, dynamic> V_4, //linked object V_5, //str <>f__AnonymousType5<string, dynamic> V_6, object V_7, bool V_8) "); } [Fact] public void AnonymousTypes_Dynamic1() { var template = @" using System; class C { public void F() { var <N:0>x = new { A = (dynamic)null, B = 1 }</N:0>; Console.WriteLine(x.B + <<VALUE>>); } } "; var source0 = MarkedSource(template.Replace("<<VALUE>>", "0")); var source1 = MarkedSource(template.Replace("<<VALUE>>", "1")); var source2 = MarkedSource(template.Replace("<<VALUE>>", "2")); var compilation0 = CreateCompilationWithMscorlib45(new[] { source0.Tree }, options: ComSafeDebugDll); var compilation1 = compilation0.WithSource(source1.Tree); var compilation2 = compilation1.WithSource(source2.Tree); var v0 = CompileAndVerify(compilation0); v0.VerifyDiagnostics(); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var f0 = compilation0.GetMember<MethodSymbol>("C.F"); var f1 = compilation1.GetMember<MethodSymbol>("C.F"); var f2 = compilation2.GetMember<MethodSymbol>("C.F"); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); var baselineIL0 = @" { // Code size 22 (0x16) .maxstack 2 .locals init (<>f__AnonymousType0<dynamic, int> V_0) //x IL_0000: nop IL_0001: ldnull IL_0002: ldc.i4.1 IL_0003: newobj ""<>f__AnonymousType0<dynamic, int>..ctor(dynamic, int)"" IL_0008: stloc.0 IL_0009: ldloc.0 IL_000a: callvirt ""int <>f__AnonymousType0<dynamic, int>.B.get"" IL_000f: call ""void System.Console.WriteLine(int)"" IL_0014: nop IL_0015: ret } "; v0.VerifyIL("C.F", baselineIL0); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true))); diff1.VerifySynthesizedMembers( "<>f__AnonymousType0<<A>j__TPar, <B>j__TPar>: {Equals, GetHashCode, ToString}"); var baselineIL = @" { // Code size 24 (0x18) .maxstack 2 .locals init (<>f__AnonymousType0<dynamic, int> V_0) //x IL_0000: nop IL_0001: ldnull IL_0002: ldc.i4.1 IL_0003: newobj ""<>f__AnonymousType0<dynamic, int>..ctor(dynamic, int)"" IL_0008: stloc.0 IL_0009: ldloc.0 IL_000a: callvirt ""int <>f__AnonymousType0<dynamic, int>.B.get"" IL_000f: ldc.i4.<<VALUE>> IL_0010: add IL_0011: call ""void System.Console.WriteLine(int)"" IL_0016: nop IL_0017: ret } "; diff1.VerifyIL("C.F", baselineIL.Replace("<<VALUE>>", "1")); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, f1, f2, GetSyntaxMapFromMarkers(source1, source2), preserveLocalVariables: true))); diff2.VerifySynthesizedMembers( "<>f__AnonymousType0<<A>j__TPar, <B>j__TPar>: {Equals, GetHashCode, ToString}"); diff2.VerifyIL("C.F", baselineIL.Replace("<<VALUE>>", "2")); } /// <summary> /// Should not re-use locals if the method metadata /// signature is unsupported. /// </summary> [WorkItem(9849, "https://github.com/dotnet/roslyn/issues/9849")] [Fact(Skip = "https://github.com/dotnet/roslyn/issues/9849")] public void LocalType_UnsupportedSignatureContent() { // Equivalent to C#, but with extra local and required modifier on // expected local. Used to generate initial (unsupported) metadata. var ilSource = @".assembly extern mscorlib { .ver 4:0:0:0 .publickeytoken = (B7 7A 5C 56 19 34 E0 89) } .assembly '<<GeneratedFileName>>' { } .class C { .method public specialname rtspecialname instance void .ctor() { ret } .method private static object F() { ldnull ret } .method private static void M1() { .locals init ([0] object other, [1] object modreq(int32) o) call object C::F() stloc.1 ldloc.1 call void C::M2(object) ret } .method private static void M2(object o) { ret } }"; var source = @"class C { static object F() { return null; } static void M1() { object o = F(); M2(o); } static void M2(object o) { } }"; ImmutableArray<byte> assemblyBytes; ImmutableArray<byte> pdbBytes; EmitILToArray(ilSource, appendDefaultHeader: false, includePdb: false, assemblyBytes: out assemblyBytes, pdbBytes: out pdbBytes); var md0 = ModuleMetadata.CreateFromImage(assemblyBytes); // Still need a compilation with source for the initial // generation - to get a MethodSymbol and syntax map. var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source); var method0 = compilation0.GetMember<MethodSymbol>("C.M1"); var generation0 = EmitBaseline.CreateInitialBaseline(md0, m => default); var method1 = compilation1.GetMember<MethodSymbol>("C.M1"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true))); diff1.VerifyIL("C.M1", @"{ // Code size 15 (0xf) .maxstack 1 .locals init (object V_0) //o IL_0000: nop IL_0001: call ""object C.F()"" IL_0006: stloc.0 IL_0007: ldloc.0 IL_0008: call ""void C.M2(object)"" IL_000d: nop IL_000e: ret }"); } /// <summary> /// Should not re-use locals with custom modifiers. /// </summary> [WorkItem(9848, "https://github.com/dotnet/roslyn/issues/9848")] [Fact(Skip = "https://github.com/dotnet/roslyn/issues/9848")] public void LocalType_CustomModifiers() { // Equivalent method signature to C#, but // with optional modifier on locals. var ilSource = @".assembly extern mscorlib { .ver 4:0:0:0 .publickeytoken = (B7 7A 5C 56 19 34 E0 89) } .assembly '<<GeneratedFileName>>' { } .class public C { .method public specialname rtspecialname instance void .ctor() { ret } .method public static object F(class [mscorlib]System.IDisposable d) { .locals init ([0] class C modopt(int32) c, [1] class [mscorlib]System.IDisposable modopt(object), [2] bool V_2, [3] object V_3) ldnull ret } }"; var source = @"class C { static object F(System.IDisposable d) { C c; using (d) { c = (C)d; } return c; } }"; var metadata0 = (MetadataImageReference)CompileIL(ilSource, prependDefaultHeader: false); // Still need a compilation with source for the initial // generation - to get a MethodSymbol and syntax map. var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source); var moduleMetadata0 = ((AssemblyMetadata)metadata0.GetMetadataNoCopy()).GetModules()[0]; var method0 = compilation0.GetMember<MethodSymbol>("C.F"); var generation0 = EmitBaseline.CreateInitialBaseline( moduleMetadata0, m => default); var method1 = compilation1.GetMember<MethodSymbol>("C.F"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true))); diff1.VerifyIL("C.F", @" { // Code size 38 (0x26) .maxstack 1 .locals init ([unchanged] V_0, [unchanged] V_1, [bool] V_2, [object] V_3, C V_4, //c System.IDisposable V_5, object V_6) -IL_0000: nop -IL_0001: ldarg.0 IL_0002: stloc.s V_5 .try { -IL_0004: nop -IL_0005: ldarg.0 IL_0006: castclass ""C"" IL_000b: stloc.s V_4 -IL_000d: nop IL_000e: leave.s IL_001d } finally { ~IL_0010: ldloc.s V_5 IL_0012: brfalse.s IL_001c IL_0014: ldloc.s V_5 IL_0016: callvirt ""void System.IDisposable.Dispose()"" IL_001b: nop IL_001c: endfinally } -IL_001d: ldloc.s V_4 IL_001f: stloc.s V_6 IL_0021: br.s IL_0023 -IL_0023: ldloc.s V_6 IL_0025: ret }", methodToken: diff1.EmitResult.UpdatedMethods.Single()); } /// <summary> /// Temporaries for locals used within a single /// statement should not be preserved. /// </summary> [Fact] public void TemporaryLocals_Other() { // Use increment as an example of a compiler generated // temporary that does not span multiple statements. var source = @"class C { int P { get; set; } static int M() { var c = new C(); return c.P++; } }"; var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source); var testData0 = new CompilationTestData(); var bytes0 = compilation0.EmitToArray(testData: testData0); var methodData0 = testData0.GetMethodData("C.M"); var method0 = compilation0.GetMember<MethodSymbol>("C.M"); var generation0 = EmitBaseline.CreateInitialBaseline( ModuleMetadata.CreateFromImage(bytes0), methodData0.EncDebugInfoProvider()); var method1 = compilation1.GetMember<MethodSymbol>("C.M"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true))); diff1.VerifyIL("C.M", @" { // Code size 32 (0x20) .maxstack 3 .locals init (C V_0, //c [int] V_1, [int] V_2, int V_3, int V_4) IL_0000: nop IL_0001: newobj ""C..ctor()"" IL_0006: stloc.0 IL_0007: ldloc.0 IL_0008: dup IL_0009: callvirt ""int C.P.get"" IL_000e: stloc.3 IL_000f: ldloc.3 IL_0010: ldc.i4.1 IL_0011: add IL_0012: callvirt ""void C.P.set"" IL_0017: nop IL_0018: ldloc.3 IL_0019: stloc.s V_4 IL_001b: br.s IL_001d IL_001d: ldloc.s V_4 IL_001f: ret }"); } /// <summary> /// Local names array (from PDB) may have fewer slots than method /// signature (from metadata) when the trailing slots are unnamed. /// </summary> [WorkItem(782270, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/782270")] [Fact] public void Bug782270() { var source = @"class C { static System.IDisposable F() { return null; } static void M() { using (var o = F()) { } } }"; var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source); var testData0 = new CompilationTestData(); var bytes0 = compilation0.EmitToArray(testData: testData0); var methodData0 = testData0.GetMethodData("C.M"); var method0 = compilation0.GetMember<MethodSymbol>("C.M"); var generation0 = EmitBaseline.CreateInitialBaseline( ModuleMetadata.CreateFromImage(bytes0), testData0.GetMethodData("C.M").EncDebugInfoProvider()); testData0.GetMethodData("C.M").VerifyIL(@" { // Code size 23 (0x17) .maxstack 1 .locals init (System.IDisposable V_0) //o IL_0000: nop IL_0001: call ""System.IDisposable C.F()"" IL_0006: stloc.0 .try { IL_0007: nop IL_0008: nop IL_0009: leave.s IL_0016 } finally { IL_000b: ldloc.0 IL_000c: brfalse.s IL_0015 IL_000e: ldloc.0 IL_000f: callvirt ""void System.IDisposable.Dispose()"" IL_0014: nop IL_0015: endfinally } IL_0016: ret }"); var method1 = compilation1.GetMember<MethodSymbol>("C.M"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true))); diff1.VerifyIL("C.M", @" { // Code size 23 (0x17) .maxstack 1 .locals init (System.IDisposable V_0) //o IL_0000: nop IL_0001: call ""System.IDisposable C.F()"" IL_0006: stloc.0 .try { IL_0007: nop IL_0008: nop IL_0009: leave.s IL_0016 } finally { IL_000b: ldloc.0 IL_000c: brfalse.s IL_0015 IL_000e: ldloc.0 IL_000f: callvirt ""void System.IDisposable.Dispose()"" IL_0014: nop IL_0015: endfinally } IL_0016: ret }"); } /// <summary> /// Similar to above test but with no named locals in original. /// </summary> [WorkItem(782270, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/782270")] [Fact] public void Bug782270_NoNamedLocals() { // Equivalent to C#, but with unnamed locals. // Used to generate initial metadata. var ilSource = @".assembly extern netstandard { .ver 2:0:0:0 .publickeytoken = (cc 7b 13 ff cd 2d dd 51) } .assembly '<<GeneratedFileName>>' { } .class C extends object { .method private static class [netstandard]System.IDisposable F() { ldnull ret } .method private static void M() { .locals init ([0] object, [1] object) ret } }"; var source0 = @"class C { static System.IDisposable F() { return null; } static void M() { } }"; var source1 = @"class C { static System.IDisposable F() { return null; } static void M() { using (var o = F()) { } } }"; EmitILToArray(ilSource, appendDefaultHeader: false, includePdb: false, assemblyBytes: out var assemblyBytes, pdbBytes: out var pdbBytes); var md0 = ModuleMetadata.CreateFromImage(assemblyBytes); // Still need a compilation with source for the initial // generation - to get a MethodSymbol and syntax map. var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll, targetFramework: TargetFramework.NetStandard20); var compilation1 = compilation0.WithSource(source1); var method0 = compilation0.GetMember<MethodSymbol>("C.M"); var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider); var method1 = compilation1.GetMember<MethodSymbol>("C.M"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true))); diff1.VerifyIL("C.M", @" { // Code size 23 (0x17) .maxstack 1 .locals init ([object] V_0, [object] V_1, System.IDisposable V_2) //o IL_0000: nop IL_0001: call ""System.IDisposable C.F()"" IL_0006: stloc.2 .try { IL_0007: nop IL_0008: nop IL_0009: leave.s IL_0016 } finally { IL_000b: ldloc.2 IL_000c: brfalse.s IL_0015 IL_000e: ldloc.2 IL_000f: callvirt ""void System.IDisposable.Dispose()"" IL_0014: nop IL_0015: endfinally } IL_0016: ret } "); } [Fact] public void TemporaryLocals_ReferencedType() { var source = @"class C { static object F() { return null; } static void M() { var x = new System.Collections.Generic.HashSet<int>(); x.Add(1); } }"; var compilation0 = CreateCompilation(source, new[] { CSharpRef }, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source); var testData0 = new CompilationTestData(); var bytes0 = compilation0.EmitToArray(testData: testData0); var methodData0 = testData0.GetMethodData("C.M"); var method0 = compilation0.GetMember<MethodSymbol>("C.M"); var modMeta = ModuleMetadata.CreateFromImage(bytes0); var generation0 = EmitBaseline.CreateInitialBaseline( modMeta, methodData0.EncDebugInfoProvider()); var method1 = compilation1.GetMember<MethodSymbol>("C.M"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true))); diff1.VerifyIL("C.M", @" { // Code size 16 (0x10) .maxstack 2 .locals init (System.Collections.Generic.HashSet<int> V_0) //x IL_0000: nop IL_0001: newobj ""System.Collections.Generic.HashSet<int>..ctor()"" IL_0006: stloc.0 IL_0007: ldloc.0 IL_0008: ldc.i4.1 IL_0009: callvirt ""bool System.Collections.Generic.HashSet<int>.Add(int)"" IL_000e: pop IL_000f: ret } "); } [WorkItem(770502, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/770502")] [WorkItem(839565, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/839565")] [Fact] public void DynamicOperations() { var source = @"class A { static object F = null; object x = ((dynamic)F) + 1; static A() { ((dynamic)F).F(); } A() { } static void M(object o) { ((dynamic)o).x = 1; } static void N(A o) { o.x = 1; } } class B { static object F = null; static object G = ((dynamic)F).F(); object x = ((dynamic)F) + 1; }"; var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll, references: new[] { CSharpRef }); var compilation1 = compilation0.WithSource(source); var testData0 = new CompilationTestData(); var bytes0 = compilation0.EmitToArray(testData: testData0); using var md0 = ModuleMetadata.CreateFromImage(bytes0); // Source method with dynamic operations. var methodData0 = testData0.GetMethodData("A.M"); var generation0 = EmitBaseline.CreateInitialBaseline(md0, methodData0.EncDebugInfoProvider()); var method0 = compilation0.GetMember<MethodSymbol>("A.M"); var method1 = compilation1.GetMember<MethodSymbol>("A.M"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true))); diff1.EmitResult.Diagnostics.Verify(); // Source method with no dynamic operations. methodData0 = testData0.GetMethodData("A.N"); generation0 = EmitBaseline.CreateInitialBaseline(md0, methodData0.EncDebugInfoProvider()); method0 = compilation0.GetMember<MethodSymbol>("A.N"); method1 = compilation1.GetMember<MethodSymbol>("A.N"); diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true))); diff1.EmitResult.Diagnostics.Verify(); // Explicit .ctor with dynamic operations. methodData0 = testData0.GetMethodData("A..ctor"); generation0 = EmitBaseline.CreateInitialBaseline(md0, methodData0.EncDebugInfoProvider()); method0 = compilation0.GetMember<MethodSymbol>("A..ctor"); method1 = compilation1.GetMember<MethodSymbol>("A..ctor"); diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true))); diff1.EmitResult.Diagnostics.Verify(); // Explicit .cctor with dynamic operations. methodData0 = testData0.GetMethodData("A..cctor"); generation0 = EmitBaseline.CreateInitialBaseline(md0, methodData0.EncDebugInfoProvider()); method0 = compilation0.GetMember<MethodSymbol>("A..cctor"); method1 = compilation1.GetMember<MethodSymbol>("A..cctor"); diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true))); diff1.EmitResult.Diagnostics.Verify(); // Implicit .ctor with dynamic operations. methodData0 = testData0.GetMethodData("B..ctor"); generation0 = EmitBaseline.CreateInitialBaseline(md0, methodData0.EncDebugInfoProvider()); method0 = compilation0.GetMember<MethodSymbol>("B..ctor"); method1 = compilation1.GetMember<MethodSymbol>("B..ctor"); diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true))); diff1.EmitResult.Diagnostics.Verify(); // Implicit .cctor with dynamic operations. methodData0 = testData0.GetMethodData("B..cctor"); generation0 = EmitBaseline.CreateInitialBaseline(md0, methodData0.EncDebugInfoProvider()); method0 = compilation0.GetMember<MethodSymbol>("B..cctor"); method1 = compilation1.GetMember<MethodSymbol>("B..cctor"); diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true))); diff1.EmitResult.Diagnostics.Verify(); } [Fact] public void DynamicLocals() { var template = @" using System; class C { public void F() { dynamic <N:0>x = 1</N:0>; Console.WriteLine((int)x + <<VALUE>>); } } "; var source0 = MarkedSource(template.Replace("<<VALUE>>", "0")); var source1 = MarkedSource(template.Replace("<<VALUE>>", "1")); var source2 = MarkedSource(template.Replace("<<VALUE>>", "2")); var compilation0 = CreateCompilationWithMscorlib45(new[] { source0.Tree }, new[] { SystemCoreRef, CSharpRef }, options: ComSafeDebugDll); var compilation1 = compilation0.WithSource(source1.Tree); var compilation2 = compilation1.WithSource(source2.Tree); var v0 = CompileAndVerify(compilation0); v0.VerifyDiagnostics(); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var f0 = compilation0.GetMember<MethodSymbol>("C.F"); var f1 = compilation1.GetMember<MethodSymbol>("C.F"); var f2 = compilation2.GetMember<MethodSymbol>("C.F"); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); v0.VerifyIL("C.F", @" { // Code size 82 (0x52) .maxstack 3 .locals init (object V_0) //x IL_0000: nop IL_0001: ldc.i4.1 IL_0002: box ""int"" IL_0007: stloc.0 IL_0008: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>> C.<>o__0.<>p__0"" IL_000d: brfalse.s IL_0011 IL_000f: br.s IL_0036 IL_0011: ldc.i4.s 16 IL_0013: ldtoken ""int"" IL_0018: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_001d: ldtoken ""C"" IL_0022: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0027: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.Convert(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Type, System.Type)"" IL_002c: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0031: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>> C.<>o__0.<>p__0"" IL_0036: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>> C.<>o__0.<>p__0"" IL_003b: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>>.Target"" IL_0040: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>> C.<>o__0.<>p__0"" IL_0045: ldloc.0 IL_0046: callvirt ""int System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>.Invoke(System.Runtime.CompilerServices.CallSite, dynamic)"" IL_004b: call ""void System.Console.WriteLine(int)"" IL_0050: nop IL_0051: ret } "); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true))); diff1.VerifySynthesizedMembers( "C: {<>o__0#1}", "C.<>o__0#1: {<>p__0}"); diff1.VerifyIL("C.F", @" { // Code size 84 (0x54) .maxstack 3 .locals init (object V_0) //x IL_0000: nop IL_0001: ldc.i4.1 IL_0002: box ""int"" IL_0007: stloc.0 IL_0008: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>> C.<>o__0#1.<>p__0"" IL_000d: brfalse.s IL_0011 IL_000f: br.s IL_0036 IL_0011: ldc.i4.s 16 IL_0013: ldtoken ""int"" IL_0018: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_001d: ldtoken ""C"" IL_0022: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0027: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.Convert(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Type, System.Type)"" IL_002c: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0031: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>> C.<>o__0#1.<>p__0"" IL_0036: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>> C.<>o__0#1.<>p__0"" IL_003b: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>>.Target"" IL_0040: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>> C.<>o__0#1.<>p__0"" IL_0045: ldloc.0 IL_0046: callvirt ""int System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>.Invoke(System.Runtime.CompilerServices.CallSite, dynamic)"" IL_004b: ldc.i4.1 IL_004c: add IL_004d: call ""void System.Console.WriteLine(int)"" IL_0052: nop IL_0053: ret } "); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, f1, f2, GetSyntaxMapFromMarkers(source1, source2), preserveLocalVariables: true))); diff2.VerifySynthesizedMembers( "C: {<>o__0#2, <>o__0#1}", "C.<>o__0#1: {<>p__0}", "C.<>o__0#2: {<>p__0}"); diff2.VerifyIL("C.F", @" { // Code size 84 (0x54) .maxstack 3 .locals init (object V_0) //x IL_0000: nop IL_0001: ldc.i4.1 IL_0002: box ""int"" IL_0007: stloc.0 IL_0008: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>> C.<>o__0#2.<>p__0"" IL_000d: brfalse.s IL_0011 IL_000f: br.s IL_0036 IL_0011: ldc.i4.s 16 IL_0013: ldtoken ""int"" IL_0018: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_001d: ldtoken ""C"" IL_0022: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0027: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.Convert(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Type, System.Type)"" IL_002c: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0031: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>> C.<>o__0#2.<>p__0"" IL_0036: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>> C.<>o__0#2.<>p__0"" IL_003b: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>>.Target"" IL_0040: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>> C.<>o__0#2.<>p__0"" IL_0045: ldloc.0 IL_0046: callvirt ""int System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>.Invoke(System.Runtime.CompilerServices.CallSite, dynamic)"" IL_004b: ldc.i4.2 IL_004c: add IL_004d: call ""void System.Console.WriteLine(int)"" IL_0052: nop IL_0053: ret } "); } [Fact] public void ExceptionFilters() { var source0 = MarkedSource(@" using System; using System.IO; class C { static bool G(Exception e) => true; static void F() { try { throw new InvalidOperationException(); } catch <N:0>(IOException e)</N:0> <N:1>when (G(e))</N:1> { Console.WriteLine(); } catch <N:2>(Exception e)</N:2> <N:3>when (G(e))</N:3> { Console.WriteLine(); } } } "); var source1 = MarkedSource(@" using System; using System.IO; class C { static bool G(Exception e) => true; static void F() { try { throw new InvalidOperationException(); } catch <N:0>(IOException e)</N:0> <N:1>when (G(e))</N:1> { Console.WriteLine(); } catch <N:2>(Exception e)</N:2> <N:3>when (G(e))</N:3> { Console.WriteLine(); } Console.WriteLine(1); } }"); var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll); var compilation1 = compilation0.WithSource(source1.Tree); var v0 = CompileAndVerify(compilation0); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var f0 = compilation0.GetMember<MethodSymbol>("C.F"); var f1 = compilation1.GetMember<MethodSymbol>("C.F"); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true))); diff1.VerifyIL("C.F", @" { // Code size 90 (0x5a) .maxstack 2 .locals init (System.IO.IOException V_0, //e bool V_1, System.Exception V_2, //e bool V_3) IL_0000: nop .try { IL_0001: nop IL_0002: newobj ""System.InvalidOperationException..ctor()"" IL_0007: throw } filter { IL_0008: isinst ""System.IO.IOException"" IL_000d: dup IL_000e: brtrue.s IL_0014 IL_0010: pop IL_0011: ldc.i4.0 IL_0012: br.s IL_0020 IL_0014: stloc.0 IL_0015: ldloc.0 IL_0016: call ""bool C.G(System.Exception)"" IL_001b: stloc.1 IL_001c: ldloc.1 IL_001d: ldc.i4.0 IL_001e: cgt.un IL_0020: endfilter } // end filter { // handler IL_0022: pop IL_0023: nop IL_0024: call ""void System.Console.WriteLine()"" IL_0029: nop IL_002a: nop IL_002b: leave.s IL_0052 } filter { IL_002d: isinst ""System.Exception"" IL_0032: dup IL_0033: brtrue.s IL_0039 IL_0035: pop IL_0036: ldc.i4.0 IL_0037: br.s IL_0045 IL_0039: stloc.2 IL_003a: ldloc.2 IL_003b: call ""bool C.G(System.Exception)"" IL_0040: stloc.3 IL_0041: ldloc.3 IL_0042: ldc.i4.0 IL_0043: cgt.un IL_0045: endfilter } // end filter { // handler IL_0047: pop IL_0048: nop IL_0049: call ""void System.Console.WriteLine()"" IL_004e: nop IL_004f: nop IL_0050: leave.s IL_0052 } IL_0052: ldc.i4.1 IL_0053: call ""void System.Console.WriteLine(int)"" IL_0058: nop IL_0059: ret } "); } [ConditionalFact(typeof(WindowsDesktopOnly), Reason = ConditionalSkipReason.NoPiaNeedsDesktop)] public void MethodSignatureWithNoPIAType() { var sourcePIA = @" using System; using System.Runtime.InteropServices; [assembly: ImportedFromTypeLib(""_.dll"")] [assembly: Guid(""35DB1A6B-D635-4320-A062-28D42920E2A3"")] [ComImport()] [Guid(""35DB1A6B-D635-4320-A062-28D42920E2A4"")] public interface I { }"; var source0 = MarkedSource(@" class C { static void M(I x) { System.Console.WriteLine(1); } }"); var source1 = MarkedSource(@" class C { static void M(I x) { System.Console.WriteLine(2); } }"); var compilationPIA = CreateCompilation(sourcePIA, options: TestOptions.DebugDll); var referencePIA = compilationPIA.EmitToImageReference(embedInteropTypes: true); var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll, references: new MetadataReference[] { referencePIA }); var compilation1 = compilation0.WithSource(source1.Tree); var method0 = compilation0.GetMember<MethodSymbol>("C.M"); var method1 = compilation1.GetMember<MethodSymbol>("C.M"); var v0 = CompileAndVerify(compilation0); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true))); diff1.EmitResult.Diagnostics.Verify( // error CS7096: Cannot continue since the edit includes a reference to an embedded type: 'I'. Diagnostic(ErrorCode.ERR_EncNoPIAReference).WithArguments("I")); } [WorkItem(844472, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/844472")] [ConditionalFact(typeof(WindowsDesktopOnly), Reason = ConditionalSkipReason.NoPiaNeedsDesktop)] public void LocalSignatureWithNoPIAType() { var sourcePIA = @" using System; using System.Runtime.InteropServices; [assembly: ImportedFromTypeLib(""_.dll"")] [assembly: Guid(""35DB1A6B-D635-4320-A062-28D42920E2A3"")] [ComImport()] [Guid(""35DB1A6B-D635-4320-A062-28D42920E2A4"")] public interface I { }"; var source0 = MarkedSource(@" class C { static void M(I x) { I <N:0>y = null</N:0>; M(null); } }"); var source1 = MarkedSource(@" class C { static void M(I x) { I <N:0>y = null</N:0>; M(x); } }"); var compilationPIA = CreateCompilation(sourcePIA, options: TestOptions.DebugDll); var referencePIA = compilationPIA.EmitToImageReference(embedInteropTypes: true); var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll, references: new MetadataReference[] { referencePIA }); var compilation1 = compilation0.WithSource(source1.Tree); var method0 = compilation0.GetMember<MethodSymbol>("C.M"); var method1 = compilation1.GetMember<MethodSymbol>("C.M"); var v0 = CompileAndVerify(compilation0); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true))); diff1.EmitResult.Diagnostics.Verify( // (6,16): warning CS0219: The variable 'y' is assigned but its value is never used Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "y").WithArguments("y"), // error CS7096: Cannot continue since the edit includes a reference to an embedded type: 'I'. Diagnostic(ErrorCode.ERR_EncNoPIAReference).WithArguments("I")); } /// <summary> /// Disallow edits that require NoPIA references. /// </summary> [ConditionalFact(typeof(WindowsDesktopOnly), Reason = ConditionalSkipReason.NoPiaNeedsDesktop)] public void NoPIAReferences() { var sourcePIA = @"using System; using System.Runtime.InteropServices; [assembly: ImportedFromTypeLib(""_.dll"")] [assembly: Guid(""35DB1A6B-D635-4320-A062-28D42921E2B3"")] [ComImport()] [Guid(""35DB1A6B-D635-4320-A062-28D42921E2B4"")] public interface IA { void M(); int P { get; } event Action E; } [ComImport()] [Guid(""35DB1A6B-D635-4320-A062-28D42921E2B5"")] public interface IB { } [ComImport()] [Guid(""35DB1A6B-D635-4320-A062-28D42921E2B6"")] public interface IC { } public struct S { public object F; }"; var source0 = @"class C<T> { static object F = typeof(IC); static void M1() { var o = default(IA); o.M(); M2(o.P); o.E += M1; M2(C<IA>.F); M2(new S()); } static void M2(object o) { } }"; var source1A = source0; var source1B = @"class C<T> { static object F = typeof(IC); static void M1() { M2(null); } static void M2(object o) { } }"; var compilationPIA = CreateCompilation(sourcePIA, options: TestOptions.DebugDll); var referencePIA = compilationPIA.EmitToImageReference(embedInteropTypes: true); var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll, references: new MetadataReference[] { referencePIA, CSharpRef }); var compilation1A = compilation0.WithSource(source1A); var compilation1B = compilation0.WithSource(source1B); var method0 = compilation0.GetMember<MethodSymbol>("C.M1"); var method1B = compilation1B.GetMember<MethodSymbol>("C.M1"); var method1A = compilation1A.GetMember<MethodSymbol>("C.M1"); var testData0 = new CompilationTestData(); var bytes0 = compilation0.EmitToArray(testData: testData0); var methodData0 = testData0.GetMethodData("C<T>.M1"); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var reader0 = md0.MetadataReader; CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "C`1", "IA", "IC", "S"); var generation0 = EmitBaseline.CreateInitialBaseline(md0, methodData0.EncDebugInfoProvider()); // Disallow edits that require NoPIA references. var diff1A = compilation1A.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1A, GetEquivalentNodesMap(method1A, method0), preserveLocalVariables: true))); diff1A.EmitResult.Diagnostics.Verify( // error CS7094: Cannot continue since the edit includes a reference to an embedded type: 'S'. Diagnostic(ErrorCode.ERR_EncNoPIAReference).WithArguments("S"), // error CS7094: Cannot continue since the edit includes a reference to an embedded type: 'IA'. Diagnostic(ErrorCode.ERR_EncNoPIAReference).WithArguments("IA")); // Allow edits that do not require NoPIA references, // even if the previous code included references. var diff1B = compilation1B.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1B, GetEquivalentNodesMap(method1B, method0), preserveLocalVariables: true))); diff1B.VerifyIL("C<T>.M1", @"{ // Code size 9 (0x9) .maxstack 1 .locals init ([unchanged] V_0, [unchanged] V_1) IL_0000: nop IL_0001: ldnull IL_0002: call ""void C<T>.M2(object)"" IL_0007: nop IL_0008: ret }"); using var md1 = diff1B.GetMetadata(); var reader1 = md1.Reader; var readers = new[] { reader0, reader1 }; CheckNames(readers, reader1.GetTypeDefNames()); } [WorkItem(844536, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/844536")] [ConditionalFact(typeof(WindowsDesktopOnly), Reason = ConditionalSkipReason.NoPiaNeedsDesktop)] public void NoPIATypeInNamespace() { var sourcePIA = @"using System; using System.Runtime.InteropServices; [assembly: ImportedFromTypeLib(""_.dll"")] [assembly: Guid(""35DB1A6B-D635-4320-A062-28D42920E2A5"")] namespace N { [ComImport()] [Guid(""35DB1A6B-D635-4320-A062-28D42920E2A6"")] public interface IA { } } [ComImport()] [Guid(""35DB1A6B-D635-4320-A062-28D42920E2A7"")] public interface IB { }"; var source = @"class C<T> { static void M(object o) { M(C<N.IA>.E.X); M(C<IB>.E.X); } enum E { X } }"; var compilationPIA = CreateCompilation(sourcePIA, options: TestOptions.DebugDll); var referencePIA = compilationPIA.EmitToImageReference(embedInteropTypes: true); var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll, references: new MetadataReference[] { referencePIA, CSharpRef }); var compilation1 = compilation0.WithSource(source); var bytes0 = compilation0.EmitToArray(); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var generation0 = EmitBaseline.CreateInitialBaseline(md0, m => default); var method0 = compilation0.GetMember<MethodSymbol>("C.M"); var method1 = compilation1.GetMember<MethodSymbol>("C.M"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1))); diff1.EmitResult.Diagnostics.Verify( // error CS7094: Cannot continue since the edit includes a reference to an embedded type: 'N.IA'. Diagnostic(ErrorCode.ERR_EncNoPIAReference).WithArguments("N.IA"), // error CS7094: Cannot continue since the edit includes a reference to an embedded type: 'IB'. Diagnostic(ErrorCode.ERR_EncNoPIAReference).WithArguments("IB")); diff1.VerifyIL("C<T>.M", @"{ // Code size 26 (0x1a) .maxstack 1 IL_0000: nop IL_0001: ldc.i4.0 IL_0002: box ""C<N.IA>.E"" IL_0007: call ""void C<T>.M(object)"" IL_000c: nop IL_000d: ldc.i4.0 IL_000e: box ""C<IB>.E"" IL_0013: call ""void C<T>.M(object)"" IL_0018: nop IL_0019: ret }"); } /// <summary> /// Should use TypeDef rather than TypeRef for unrecognized /// local of a type defined in the original assembly. /// </summary> [WorkItem(910777, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/910777")] [Fact] public void UnrecognizedLocalOfTypeFromAssembly() { var source = @"class E : System.Exception { } class C { static void M() { try { } catch (E e) { } } }"; var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll, targetFramework: TargetFramework.NetStandard20); var compilation1 = compilation0.WithSource(source); var testData0 = new CompilationTestData(); var bytes0 = compilation0.EmitToArray(testData: testData0); var methodData0 = testData0.GetMethodData("C.M"); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var reader0 = md0.MetadataReader; CheckNames(reader0, reader0.GetAssemblyRefNames(), "netstandard"); var method0 = compilation0.GetMember<MethodSymbol>("C.M"); var method1 = compilation1.GetMember<MethodSymbol>("C.M"); var generation0 = EmitBaseline.CreateInitialBaseline(md0, methodData0.EncDebugInfoProvider()); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true))); using var md1 = diff1.GetMetadata(); var reader1 = md1.Reader; var readers = new[] { reader0, reader1 }; CheckNames(readers, reader1.GetAssemblyRefNames(), "netstandard"); CheckNames(readers, reader1.GetTypeRefNames(), "Object"); CheckEncLog(reader1, Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default), Row(7, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(2, TableIndex.StandAloneSig, EditAndContinueOperation.Default), Row(2, TableIndex.MethodDef, EditAndContinueOperation.Default)); CheckEncMap(reader1, Handle(7, TableIndex.TypeRef), Handle(2, TableIndex.MethodDef), Handle(2, TableIndex.StandAloneSig), Handle(2, TableIndex.AssemblyRef)); diff1.VerifyIL("C.M", @" { // Code size 11 (0xb) .maxstack 1 .locals init (E V_0) //e IL_0000: nop .try { IL_0001: nop IL_0002: nop IL_0003: leave.s IL_000a } catch E { IL_0005: stloc.0 IL_0006: nop IL_0007: nop IL_0008: leave.s IL_000a } IL_000a: ret }"); } /// <summary> /// Similar to above test but with anonymous type /// added in subsequent generation. /// </summary> [WorkItem(910777, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/910777")] [Fact] public void UnrecognizedLocalOfAnonymousTypeFromAssembly() { var source0 = @"class C { static string F() { return null; } static string G() { var o = new { Y = 1 }; return o.ToString(); } }"; var source1 = @"class C { static string F() { var o = new { X = 1 }; return o.ToString(); } static string G() { var o = new { Y = 1 }; return o.ToString(); } }"; var source2 = @"class C { static string F() { return null; } static string G() { return null; } }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll, targetFramework: TargetFramework.NetStandard20); var compilation1 = compilation0.WithSource(source1); var compilation2 = compilation1.WithSource(source2); var method0F = compilation0.GetMember<MethodSymbol>("C.F"); var method1F = compilation1.GetMember<MethodSymbol>("C.F"); var method1G = compilation1.GetMember<MethodSymbol>("C.G"); var method2F = compilation2.GetMember<MethodSymbol>("C.F"); var method2G = compilation2.GetMember<MethodSymbol>("C.G"); var bytes0 = compilation0.EmitToArray(); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var reader0 = md0.MetadataReader; CheckNames(reader0, reader0.GetAssemblyRefNames(), "netstandard"); // Use empty LocalVariableNameProvider for original locals and // use preserveLocalVariables: true for the edit so that existing // locals are retained even though all are unrecognized. var generation0 = EmitBaseline.CreateInitialBaseline( md0, EmptyLocalsProvider); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0F, method1F, syntaxMap: s => null, preserveLocalVariables: true))); using var md1 = diff1.GetMetadata(); var reader1 = md1.Reader; var readers = new List<MetadataReader> { reader0, reader1 }; CheckNames(readers, reader1.GetAssemblyRefNames(), "netstandard"); CheckNames(readers, reader1.GetTypeDefNames(), "<>f__AnonymousType1`1"); CheckNames(readers, reader1.GetTypeRefNames(), "CompilerGeneratedAttribute", "DebuggerDisplayAttribute", "Object", "DebuggerBrowsableState", "DebuggerBrowsableAttribute", "DebuggerHiddenAttribute", "EqualityComparer`1", "String", "IFormatProvider"); // Change method updated in generation 1. var diff2F = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method1F, method2F, syntaxMap: s => null, preserveLocalVariables: true))); using var md2 = diff2F.GetMetadata(); var reader2 = md2.Reader; readers.Add(reader2); CheckNames(readers, reader2.GetAssemblyRefNames(), "netstandard"); CheckNames(readers, reader2.GetTypeDefNames()); CheckNames(readers, reader2.GetTypeRefNames(), "Object"); // Change method unchanged since generation 0. var diff2G = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method1G, method2G, syntaxMap: s => null, preserveLocalVariables: true))); } [Fact] public void BrokenOutputStreams() { var source0 = @"class C { static string F() { return null; } }"; var source1 = @"class C { static string F() { var o = new { X = 1 }; return o.ToString(); } }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var bytes0 = compilation0.EmitToArray(); using (new EnsureEnglishUICulture()) using (var md0 = ModuleMetadata.CreateFromImage(bytes0)) { var method0F = compilation0.GetMember<MethodSymbol>("C.F"); var generation0 = EmitBaseline.CreateInitialBaseline( md0, EmptyLocalsProvider); var method1F = compilation1.GetMember<MethodSymbol>("C.F"); using MemoryStream mdStream = new MemoryStream(), ilStream = new MemoryStream(), pdbStream = new MemoryStream(); var isAddedSymbol = new Func<ISymbol, bool>(s => false); var badStream = new BrokenStream(); badStream.BreakHow = BrokenStream.BreakHowType.ThrowOnWrite; var result = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0F, method1F, syntaxMap: s => null, preserveLocalVariables: true)), isAddedSymbol, badStream, ilStream, pdbStream, new CompilationTestData(), default); Assert.False(result.Success); result.Diagnostics.Verify( // error CS8104: An error occurred while writing the output file: System.IO.IOException: I/O error occurred. Diagnostic(ErrorCode.ERR_PeWritingFailure).WithArguments(badStream.ThrownException.ToString()).WithLocation(1, 1) ); result = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0F, method1F, syntaxMap: s => null, preserveLocalVariables: true)), isAddedSymbol, mdStream, badStream, pdbStream, new CompilationTestData(), default); Assert.False(result.Success); result.Diagnostics.Verify( // error CS8104: An error occurred while writing the output file: System.IO.IOException: I/O error occurred. Diagnostic(ErrorCode.ERR_PeWritingFailure).WithArguments(badStream.ThrownException.ToString()).WithLocation(1, 1) ); result = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0F, method1F, syntaxMap: s => null, preserveLocalVariables: true)), isAddedSymbol, mdStream, ilStream, badStream, new CompilationTestData(), default); Assert.False(result.Success); result.Diagnostics.Verify( // error CS0041: Unexpected error writing debug information -- 'I/O error occurred.' Diagnostic(ErrorCode.FTL_DebugEmitFailure).WithArguments("I/O error occurred.").WithLocation(1, 1) ); } } [Fact] public void BrokenPortablePdbStream() { var source0 = @"class C { static string F() { return null; } }"; var source1 = @"class C { static string F() { var o = new { X = 1 }; return o.ToString(); } }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var bytes0 = compilation0.EmitToArray(EmitOptions.Default.WithDebugInformationFormat(DebugInformationFormat.PortablePdb)); using (new EnsureEnglishUICulture()) using (var md0 = ModuleMetadata.CreateFromImage(bytes0)) { var method0F = compilation0.GetMember<MethodSymbol>("C.F"); var generation0 = EmitBaseline.CreateInitialBaseline( md0, EmptyLocalsProvider); var method1F = compilation1.GetMember<MethodSymbol>("C.F"); using MemoryStream mdStream = new MemoryStream(), ilStream = new MemoryStream(), pdbStream = new MemoryStream(); var isAddedSymbol = new Func<ISymbol, bool>(s => false); var badStream = new BrokenStream(); badStream.BreakHow = BrokenStream.BreakHowType.ThrowOnWrite; var result = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0F, method1F, syntaxMap: s => null, preserveLocalVariables: true)), isAddedSymbol, mdStream, ilStream, badStream, new CompilationTestData(), default); Assert.False(result.Success); result.Diagnostics.Verify( // error CS0041: Unexpected error writing debug information -- 'I/O error occurred.' Diagnostic(ErrorCode.FTL_DebugEmitFailure).WithArguments("I/O error occurred.").WithLocation(1, 1) ); } } [WorkItem(923492, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/923492")] [ConditionalFact(typeof(WindowsDesktopOnly), Reason = ConditionalSkipReason.NativePdbRequiresDesktop)] public void SymWriterErrors() { var source0 = @"class C { }"; var source1 = @"class C { static void Main() { } }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); // Verify full metadata contains expected rows. var bytes0 = compilation0.EmitToArray(); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var diff1 = compilation1.EmitDifference( EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider), ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Insert, null, compilation1.GetMember<MethodSymbol>("C.Main"))), testData: new CompilationTestData { SymWriterFactory = _ => new MockSymUnmanagedWriter() }); diff1.EmitResult.Diagnostics.Verify( // error CS0041: Unexpected error writing debug information -- 'MockSymUnmanagedWriter error message' Diagnostic(ErrorCode.FTL_DebugEmitFailure).WithArguments("MockSymUnmanagedWriter error message")); Assert.False(diff1.EmitResult.Success); } [WorkItem(1058058, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1058058")] [Fact] public void BlobContainsInvalidValues() { var source0 = @"class C { static void F() { string goo = ""abc""; } }"; var source1 = @"class C { static void F() { float goo = 10; } }"; var source2 = @"class C { static void F() { bool goo = true; } }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll, targetFramework: TargetFramework.NetStandard20); var compilation1 = compilation0.WithSource(source1); var compilation2 = compilation1.WithSource(source2); var bytes0 = compilation0.EmitToArray(); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var reader0 = md0.MetadataReader; CheckNames(reader0, reader0.GetAssemblyRefNames(), "netstandard"); var method0F = compilation0.GetMember<MethodSymbol>("C.F"); var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider); var method1F = compilation1.GetMember<MethodSymbol>("C.F"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0F, method1F, syntaxMap: s => null, preserveLocalVariables: true))); var handle = MetadataTokens.BlobHandle(1); byte[] value0 = reader0.GetBlobBytes(handle); Assert.Equal("20-01-01-08", BitConverter.ToString(value0)); using var md1 = diff1.GetMetadata(); var reader1 = md1.Reader; var method2F = compilation2.GetMember<MethodSymbol>("C.F"); var diff2F = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method1F, method2F, syntaxMap: s => null, preserveLocalVariables: true))); byte[] value1 = reader1.GetBlobBytes(handle); Assert.Equal("07-02-0E-0C", BitConverter.ToString(value1)); using var md2 = diff2F.GetMetadata(); var reader2 = md2.Reader; byte[] value2 = reader2.GetBlobBytes(handle); Assert.Equal("07-03-0E-0C-02", BitConverter.ToString(value2)); } [Fact] public void ReferenceToMemberAddedToAnotherAssembly1() { var sourceA0 = @" public class A { } "; var sourceA1 = @" public class A { public void M() { System.Console.WriteLine(1);} } public class X {} "; var sourceB0 = @" public class B { public static void F() { } }"; var sourceB1 = @" public class B { public static void F() { new A().M(); } } public class Y : X { } "; var compilationA0 = CreateCompilation(sourceA0, options: TestOptions.DebugDll, assemblyName: "LibA"); var compilationA1 = compilationA0.WithSource(sourceA1); var compilationB0 = CreateCompilation(sourceB0, new[] { compilationA0.ToMetadataReference() }, options: TestOptions.DebugDll, assemblyName: "LibB"); var compilationB1 = CreateCompilation(sourceB1, new[] { compilationA1.ToMetadataReference() }, options: TestOptions.DebugDll, assemblyName: "LibB"); var bytesA0 = compilationA0.EmitToArray(); var bytesB0 = compilationB0.EmitToArray(); var mdA0 = ModuleMetadata.CreateFromImage(bytesA0); var mdB0 = ModuleMetadata.CreateFromImage(bytesB0); var generationA0 = EmitBaseline.CreateInitialBaseline(mdA0, EmptyLocalsProvider); var generationB0 = EmitBaseline.CreateInitialBaseline(mdB0, EmptyLocalsProvider); var mA1 = compilationA1.GetMember<MethodSymbol>("A.M"); var mX1 = compilationA1.GetMember<TypeSymbol>("X"); var allAddedSymbols = new ISymbol[] { mA1.GetPublicSymbol(), mX1.GetPublicSymbol() }; var diffA1 = compilationA1.EmitDifference( generationA0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Insert, null, mA1), SemanticEdit.Create(SemanticEditKind.Insert, null, mX1)), allAddedSymbols); diffA1.EmitResult.Diagnostics.Verify(); var diffB1 = compilationB1.EmitDifference( generationB0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, compilationB0.GetMember<MethodSymbol>("B.F"), compilationB1.GetMember<MethodSymbol>("B.F")), SemanticEdit.Create(SemanticEditKind.Insert, null, compilationB1.GetMember<TypeSymbol>("Y"))), allAddedSymbols); diffB1.EmitResult.Diagnostics.Verify( // (7,14): error CS7101: Member 'X' added during the current debug session can only be accessed from within its declaring assembly 'LibA'. // public class X {} Diagnostic(ErrorCode.ERR_EncReferenceToAddedMember, "X").WithArguments("X", "LibA").WithLocation(7, 14), // (4,17): error CS7101: Member 'M' added during the current debug session can only be accessed from within its declaring assembly 'LibA'. // public void M() { System.Console.WriteLine(1);} Diagnostic(ErrorCode.ERR_EncReferenceToAddedMember, "M").WithArguments("M", "LibA").WithLocation(4, 17)); } [Fact] public void ReferenceToMemberAddedToAnotherAssembly2() { var sourceA = @" public class A { public void M() { } }"; var sourceB0 = @" public class B { public static void F() { var a = new A(); } }"; var sourceB1 = @" public class B { public static void F() { var a = new A(); a.M(); } }"; var sourceB2 = @" public class B { public static void F() { var a = new A(); } }"; var compilationA = CreateCompilation(sourceA, options: TestOptions.DebugDll, assemblyName: "AssemblyA"); var aRef = compilationA.ToMetadataReference(); var compilationB0 = CreateCompilation(sourceB0, new[] { aRef }, options: TestOptions.DebugDll, assemblyName: "AssemblyB"); var compilationB1 = compilationB0.WithSource(sourceB1); var compilationB2 = compilationB1.WithSource(sourceB2); var testDataB0 = new CompilationTestData(); var bytesB0 = compilationB0.EmitToArray(testData: testDataB0); var mdB0 = ModuleMetadata.CreateFromImage(bytesB0); var generationB0 = EmitBaseline.CreateInitialBaseline(mdB0, testDataB0.GetMethodData("B.F").EncDebugInfoProvider()); var f0 = compilationB0.GetMember<MethodSymbol>("B.F"); var f1 = compilationB1.GetMember<MethodSymbol>("B.F"); var f2 = compilationB2.GetMember<MethodSymbol>("B.F"); var diffB1 = compilationB1.EmitDifference( generationB0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetEquivalentNodesMap(f1, f0), preserveLocalVariables: true))); diffB1.VerifyIL("B.F", @" { // Code size 15 (0xf) .maxstack 1 .locals init (A V_0) //a IL_0000: nop IL_0001: newobj ""A..ctor()"" IL_0006: stloc.0 IL_0007: ldloc.0 IL_0008: callvirt ""void A.M()"" IL_000d: nop IL_000e: ret } "); var diffB2 = compilationB2.EmitDifference( diffB1.NextGeneration, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, f1, f2, GetEquivalentNodesMap(f2, f1), preserveLocalVariables: true))); diffB2.VerifyIL("B.F", @" { // Code size 8 (0x8) .maxstack 1 .locals init (A V_0) //a IL_0000: nop IL_0001: newobj ""A..ctor()"" IL_0006: stloc.0 IL_0007: ret } "); } [ConditionalFact(typeof(WindowsDesktopOnly), Reason = ConditionalSkipReason.TestExecutionNeedsDesktopTypes)] public void UniqueSynthesizedNames_DynamicSiteContainer() { var source0 = @" public class C { public static void F(dynamic d) { d.Goo(); } }"; var source1 = @" public class C { public static void F(dynamic d) { d.Bar(); } }"; var source2 = @" public class C { public static void F(dynamic d, byte b) { d.Bar(); } public static void F(dynamic d) { d.Bar(); } }"; var compilation0 = CreateCompilation(source0, targetFramework: TargetFramework.StandardAndCSharp, options: ComSafeDebugDll.WithMetadataImportOptions(MetadataImportOptions.All), assemblyName: "A"); var compilation1 = compilation0.WithSource(source1); var compilation2 = compilation1.WithSource(source2); var f0 = compilation0.GetMember<MethodSymbol>("C.F"); var f1 = compilation1.GetMember<MethodSymbol>("C.F"); var f_byte2 = compilation2.GetMembers("C.F").Single(m => m.ToString() == "C.F(dynamic, byte)"); var v0 = CompileAndVerify(compilation0); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, f0, f1, preserveLocalVariables: true))); diff1.EmitResult.Diagnostics.Verify(); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Insert, null, f_byte2))); diff2.EmitResult.Diagnostics.Verify(); var reader0 = md0.MetadataReader; var reader1 = diff1.GetMetadata().Reader; var reader2 = diff2.GetMetadata().Reader; CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "C", "<>o__0"); CheckNames(new[] { reader0, reader1 }, reader1.GetTypeDefNames(), "<>o__0#1"); CheckNames(new[] { reader0, reader1, reader2 }, reader2.GetTypeDefNames(), "<>o__0#2"); } [WorkItem(918650, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/918650")] [Fact] public void ManyGenerations() { var source = @"class C {{ static int F() {{ return {0}; }} }}"; var compilation0 = CreateCompilation(String.Format(source, 1), options: TestOptions.DebugDll); var bytes0 = compilation0.EmitToArray(); var md0 = ModuleMetadata.CreateFromImage(bytes0); var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider); var method0 = compilation0.GetMember<MethodSymbol>("C.F"); for (int i = 2; i <= 50; i++) { var compilation1 = compilation0.WithSource(String.Format(source, i)); var method1 = compilation1.GetMember<MethodSymbol>("C.F"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1))); compilation0 = compilation1; method0 = method1; generation0 = diff1.NextGeneration; } } [WorkItem(187868, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/187868")] [Fact] public void PdbReadingErrors() { var source0 = MarkedSource(@" using System; class C { static void F() { <N:0>Console.WriteLine(1);</N:0> } }"); var source1 = MarkedSource(@" using System; class C { static void F() { <N:0>Console.WriteLine(2);</N:0> } }"); var compilation0 = CreateCompilation(source0.Tree, options: TestOptions.DebugDll, assemblyName: "PdbReadingErrorsAssembly"); var compilation1 = compilation0.WithSource(source1.Tree); var v0 = CompileAndVerify(compilation0); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var f0 = compilation0.GetMember<MethodSymbol>("C.F"); var f1 = compilation1.GetMember<MethodSymbol>("C.F"); var generation0 = EmitBaseline.CreateInitialBaseline(md0, methodHandle => { throw new InvalidDataException("Bad PDB!"); }); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true))); diff1.EmitResult.Diagnostics.Verify( // (6,14): error CS7038: Failed to emit module 'Unable to read debug information of method 'C.F()' (token 0x06000001) from assembly 'PdbReadingErrorsAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null''. Diagnostic(ErrorCode.ERR_InvalidDebugInfo, "F").WithArguments("C.F()", "100663297", "PdbReadingErrorsAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(6, 14)); } [Fact] public void PdbReadingErrors_PassThruExceptions() { var source0 = MarkedSource(@" using System; class C { static void F() { <N:0>Console.WriteLine(1);</N:0> } }"); var source1 = MarkedSource(@" using System; class C { static void F() { <N:0>Console.WriteLine(2);</N:0> } }"); var compilation0 = CreateCompilation(source0.Tree, options: TestOptions.DebugDll, assemblyName: "PdbReadingErrorsAssembly"); var compilation1 = compilation0.WithSource(source1.Tree); var v0 = CompileAndVerify(compilation0); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var f0 = compilation0.GetMember<MethodSymbol>("C.F"); var f1 = compilation1.GetMember<MethodSymbol>("C.F"); var generation0 = EmitBaseline.CreateInitialBaseline(md0, methodHandle => { throw new ArgumentOutOfRangeException(); }); // the compiler should't swallow any exceptions but InvalidDataException Assert.Throws<ArgumentOutOfRangeException>(() => compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true)))); } [Fact] public void PatternVariable_TypeChange() { var source0 = MarkedSource(@" class C { static int F(object o) { if (o is int <N:0>i</N:0>) { return i; } return 0; } }"); var source1 = MarkedSource(@" class C { static int F(object o) { if (o is bool <N:0>i</N:0>) { return i ? 1 : 0; } return 0; } }"); var source2 = MarkedSource(@" class C { static int F(object o) { if (o is int <N:0>j</N:0>) { return j; } return 0; } }"); var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll); var compilation1 = compilation0.WithSource(source1.Tree); var compilation2 = compilation1.WithSource(source2.Tree); var f0 = compilation0.GetMember<MethodSymbol>("C.F"); var f1 = compilation1.GetMember<MethodSymbol>("C.F"); var f2 = compilation2.GetMember<MethodSymbol>("C.F"); var v0 = CompileAndVerify(compilation0); v0.VerifyIL("C.F", @" { // Code size 35 (0x23) .maxstack 1 .locals init (int V_0, //i bool V_1, int V_2) IL_0000: nop IL_0001: ldarg.0 IL_0002: isinst ""int"" IL_0007: brfalse.s IL_0013 IL_0009: ldarg.0 IL_000a: unbox.any ""int"" IL_000f: stloc.0 IL_0010: ldc.i4.1 IL_0011: br.s IL_0014 IL_0013: ldc.i4.0 IL_0014: stloc.1 IL_0015: ldloc.1 IL_0016: brfalse.s IL_001d IL_0018: nop IL_0019: ldloc.0 IL_001a: stloc.2 IL_001b: br.s IL_0021 IL_001d: ldc.i4.0 IL_001e: stloc.2 IL_001f: br.s IL_0021 IL_0021: ldloc.2 IL_0022: ret }"); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true))); diff1.VerifyIL("C.F", @" { // Code size 46 (0x2e) .maxstack 1 .locals init ([int] V_0, [bool] V_1, [int] V_2, bool V_3, //i bool V_4, int V_5) IL_0000: nop IL_0001: ldarg.0 IL_0002: isinst ""bool"" IL_0007: brfalse.s IL_0013 IL_0009: ldarg.0 IL_000a: unbox.any ""bool"" IL_000f: stloc.3 IL_0010: ldc.i4.1 IL_0011: br.s IL_0014 IL_0013: ldc.i4.0 IL_0014: stloc.s V_4 IL_0016: ldloc.s V_4 IL_0018: brfalse.s IL_0026 IL_001a: nop IL_001b: ldloc.3 IL_001c: brtrue.s IL_0021 IL_001e: ldc.i4.0 IL_001f: br.s IL_0022 IL_0021: ldc.i4.1 IL_0022: stloc.s V_5 IL_0024: br.s IL_002b IL_0026: ldc.i4.0 IL_0027: stloc.s V_5 IL_0029: br.s IL_002b IL_002b: ldloc.s V_5 IL_002d: ret }"); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, f1, f2, GetSyntaxMapFromMarkers(source1, source2), preserveLocalVariables: true))); diff2.VerifyIL("C.F", @" { // Code size 42 (0x2a) .maxstack 1 .locals init ([int] V_0, [bool] V_1, [int] V_2, [bool] V_3, [bool] V_4, [int] V_5, int V_6, //j bool V_7, int V_8) IL_0000: nop IL_0001: ldarg.0 IL_0002: isinst ""int"" IL_0007: brfalse.s IL_0014 IL_0009: ldarg.0 IL_000a: unbox.any ""int"" IL_000f: stloc.s V_6 IL_0011: ldc.i4.1 IL_0012: br.s IL_0015 IL_0014: ldc.i4.0 IL_0015: stloc.s V_7 IL_0017: ldloc.s V_7 IL_0019: brfalse.s IL_0022 IL_001b: nop IL_001c: ldloc.s V_6 IL_001e: stloc.s V_8 IL_0020: br.s IL_0027 IL_0022: ldc.i4.0 IL_0023: stloc.s V_8 IL_0025: br.s IL_0027 IL_0027: ldloc.s V_8 IL_0029: ret }"); } [Fact] public void PatternVariable_DeleteInsert() { var source0 = MarkedSource(@" class C { static int F(object o) { if (o is int <N:0>i</N:0>) { return i; } return 0; } }"); var source1 = MarkedSource(@" class C { static int F(object o) { if (o is int) { return 1; } return 0; } }"); var source2 = MarkedSource(@" class C { static int F(object o) { if (o is int <N:0>i</N:0>) { return i; } return 0; } }"); var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll); var compilation1 = compilation0.WithSource(source1.Tree); var compilation2 = compilation1.WithSource(source2.Tree); var f0 = compilation0.GetMember<MethodSymbol>("C.F"); var f1 = compilation1.GetMember<MethodSymbol>("C.F"); var f2 = compilation2.GetMember<MethodSymbol>("C.F"); var v0 = CompileAndVerify(compilation0); v0.VerifyIL("C.F", @" { // Code size 35 (0x23) .maxstack 1 .locals init (int V_0, //i bool V_1, int V_2) IL_0000: nop IL_0001: ldarg.0 IL_0002: isinst ""int"" IL_0007: brfalse.s IL_0013 IL_0009: ldarg.0 IL_000a: unbox.any ""int"" IL_000f: stloc.0 IL_0010: ldc.i4.1 IL_0011: br.s IL_0014 IL_0013: ldc.i4.0 IL_0014: stloc.1 IL_0015: ldloc.1 IL_0016: brfalse.s IL_001d IL_0018: nop IL_0019: ldloc.0 IL_001a: stloc.2 IL_001b: br.s IL_0021 IL_001d: ldc.i4.0 IL_001e: stloc.2 IL_001f: br.s IL_0021 IL_0021: ldloc.2 IL_0022: ret }"); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true))); diff1.VerifyIL("C.F", @" { // Code size 28 (0x1c) .maxstack 2 .locals init ([int] V_0, [bool] V_1, [int] V_2, bool V_3, int V_4) IL_0000: nop IL_0001: ldarg.0 IL_0002: isinst ""int"" IL_0007: ldnull IL_0008: cgt.un IL_000a: stloc.3 IL_000b: ldloc.3 IL_000c: brfalse.s IL_0014 IL_000e: nop IL_000f: ldc.i4.1 IL_0010: stloc.s V_4 IL_0012: br.s IL_0019 IL_0014: ldc.i4.0 IL_0015: stloc.s V_4 IL_0017: br.s IL_0019 IL_0019: ldloc.s V_4 IL_001b: ret }"); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, f1, f2, GetSyntaxMapFromMarkers(source1, source2), preserveLocalVariables: true))); diff2.VerifyIL("C.F", @" { // Code size 42 (0x2a) .maxstack 1 .locals init ([int] V_0, [bool] V_1, [int] V_2, [bool] V_3, [int] V_4, int V_5, //i bool V_6, int V_7) IL_0000: nop IL_0001: ldarg.0 IL_0002: isinst ""int"" IL_0007: brfalse.s IL_0014 IL_0009: ldarg.0 IL_000a: unbox.any ""int"" IL_000f: stloc.s V_5 IL_0011: ldc.i4.1 IL_0012: br.s IL_0015 IL_0014: ldc.i4.0 IL_0015: stloc.s V_6 IL_0017: ldloc.s V_6 IL_0019: brfalse.s IL_0022 IL_001b: nop IL_001c: ldloc.s V_5 IL_001e: stloc.s V_7 IL_0020: br.s IL_0027 IL_0022: ldc.i4.0 IL_0023: stloc.s V_7 IL_0025: br.s IL_0027 IL_0027: ldloc.s V_7 IL_0029: ret }"); } [Fact] public void PatternVariable_InConstructorInitializer() { var baseClass = "public class Base { public Base(bool x) { } }"; var source0 = MarkedSource(@" public class C : Base { public C(int a) : base(a is int <N:0>x</N:0> && x == 0 && a is int <N:1>y</N:1>) { y = 1; } }" + baseClass); var source1 = MarkedSource(@" public class C : Base { public C(int a) : base(a is int <N:0>x</N:0> && x == 0) { } }" + baseClass); var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll); var compilation1 = compilation0.WithSource(source1.Tree); var compilation2 = compilation1.WithSource(source0.Tree); var ctor0 = compilation0.GetMember<MethodSymbol>("C..ctor"); var ctor1 = compilation1.GetMember<MethodSymbol>("C..ctor"); var ctor2 = compilation2.GetMember<MethodSymbol>("C..ctor"); var v0 = CompileAndVerify(compilation0); v0.VerifyIL("C..ctor", @" { // Code size 22 (0x16) .maxstack 2 .locals init (int V_0, //x int V_1) //y IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: stloc.0 IL_0003: ldloc.0 IL_0004: brtrue.s IL_000b IL_0006: ldarg.1 IL_0007: stloc.1 IL_0008: ldc.i4.1 IL_0009: br.s IL_000c IL_000b: ldc.i4.0 IL_000c: call ""Base..ctor(bool)"" IL_0011: nop IL_0012: nop IL_0013: ldc.i4.1 IL_0014: stloc.1 IL_0015: ret } "); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, ctor0, ctor1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true))); diff1.VerifyIL("C..ctor", @" { // Code size 15 (0xf) .maxstack 3 .locals init (int V_0, //x [int] V_1) IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: stloc.0 IL_0003: ldloc.0 IL_0004: ldc.i4.0 IL_0005: ceq IL_0007: call ""Base..ctor(bool)"" IL_000c: nop IL_000d: nop IL_000e: ret } "); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, ctor1, ctor2, GetSyntaxMapFromMarkers(source1, source0), preserveLocalVariables: true))); diff2.VerifyIL("C..ctor", @" { // Code size 22 (0x16) .maxstack 2 .locals init (int V_0, //x [int] V_1, int V_2) //y IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: stloc.0 IL_0003: ldloc.0 IL_0004: brtrue.s IL_000b IL_0006: ldarg.1 IL_0007: stloc.2 IL_0008: ldc.i4.1 IL_0009: br.s IL_000c IL_000b: ldc.i4.0 IL_000c: call ""Base..ctor(bool)"" IL_0011: nop IL_0012: nop IL_0013: ldc.i4.1 IL_0014: stloc.2 IL_0015: ret } "); } [Fact] public void PatternVariable_InFieldInitializer() { var source0 = MarkedSource(@" public class C { public static int a = 0; public bool field = a is int <N:0>x</N:0> && x == 0 && a is int <N:1>y</N:1>; }"); var source1 = MarkedSource(@" public class C { public static int a = 0; public bool field = a is int <N:0>x</N:0> && x == 0; }"); var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll); var compilation1 = compilation0.WithSource(source1.Tree); var compilation2 = compilation1.WithSource(source0.Tree); var ctor0 = compilation0.GetMember<MethodSymbol>("C..ctor"); var ctor1 = compilation1.GetMember<MethodSymbol>("C..ctor"); var ctor2 = compilation2.GetMember<MethodSymbol>("C..ctor"); var v0 = CompileAndVerify(compilation0); v0.VerifyIL("C..ctor", @" { // Code size 33 (0x21) .maxstack 2 .locals init (int V_0, //x int V_1) //y IL_0000: ldarg.0 IL_0001: ldsfld ""int C.a"" IL_0006: stloc.0 IL_0007: ldloc.0 IL_0008: brtrue.s IL_0013 IL_000a: ldsfld ""int C.a"" IL_000f: stloc.1 IL_0010: ldc.i4.1 IL_0011: br.s IL_0014 IL_0013: ldc.i4.0 IL_0014: stfld ""bool C.field"" IL_0019: ldarg.0 IL_001a: call ""object..ctor()"" IL_001f: nop IL_0020: ret } "); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, ctor0, ctor1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true))); diff1.VerifyIL("C..ctor", @" { // Code size 24 (0x18) .maxstack 3 .locals init (int V_0, //x [int] V_1) IL_0000: ldarg.0 IL_0001: ldsfld ""int C.a"" IL_0006: stloc.0 IL_0007: ldloc.0 IL_0008: ldc.i4.0 IL_0009: ceq IL_000b: stfld ""bool C.field"" IL_0010: ldarg.0 IL_0011: call ""object..ctor()"" IL_0016: nop IL_0017: ret } "); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, ctor1, ctor2, GetSyntaxMapFromMarkers(source1, source0), preserveLocalVariables: true))); diff2.VerifyIL("C..ctor", @" { // Code size 33 (0x21) .maxstack 2 .locals init (int V_0, //x [int] V_1, int V_2) //y IL_0000: ldarg.0 IL_0001: ldsfld ""int C.a"" IL_0006: stloc.0 IL_0007: ldloc.0 IL_0008: brtrue.s IL_0013 IL_000a: ldsfld ""int C.a"" IL_000f: stloc.2 IL_0010: ldc.i4.1 IL_0011: br.s IL_0014 IL_0013: ldc.i4.0 IL_0014: stfld ""bool C.field"" IL_0019: ldarg.0 IL_001a: call ""object..ctor()"" IL_001f: nop IL_0020: ret } "); } [Fact] public void PatternVariable_InQuery() { var source0 = MarkedSource(@" using System.Linq; public class Program { static void N() { var <N:0>query = from a in new int[] { 1, 2 } <N:1>select a is int <N:2>x</N:2> && x == 0 && a is int <N:3>y</N:3></N:1></N:0>; } }"); var source1 = MarkedSource(@" using System.Linq; public class Program { static int M(int x, out int y) { y = 42; return 43; } static void N() { var <N:0>query = from a in new int[] { 1, 2 } <N:1>select a is int <N:2>x</N:2> && x == 0</N:1></N:0>; } }"); var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll); var compilation1 = compilation0.WithSource(source1.Tree); var compilation2 = compilation1.WithSource(source0.Tree); var n0 = compilation0.GetMember<MethodSymbol>("Program.N"); var n1 = compilation1.GetMember<MethodSymbol>("Program.N"); var n2 = compilation2.GetMember<MethodSymbol>("Program.N"); var v0 = CompileAndVerify(compilation0); v0.VerifyIL("Program.N()", @" { // Code size 53 (0x35) .maxstack 4 .locals init (System.Collections.Generic.IEnumerable<bool> V_0) //query IL_0000: nop IL_0001: ldc.i4.2 IL_0002: newarr ""int"" IL_0007: dup IL_0008: ldc.i4.0 IL_0009: ldc.i4.1 IL_000a: stelem.i4 IL_000b: dup IL_000c: ldc.i4.1 IL_000d: ldc.i4.2 IL_000e: stelem.i4 IL_000f: ldsfld ""System.Func<int, bool> Program.<>c.<>9__0_0"" IL_0014: dup IL_0015: brtrue.s IL_002e IL_0017: pop IL_0018: ldsfld ""Program.<>c Program.<>c.<>9"" IL_001d: ldftn ""bool Program.<>c.<N>b__0_0(int)"" IL_0023: newobj ""System.Func<int, bool>..ctor(object, System.IntPtr)"" IL_0028: dup IL_0029: stsfld ""System.Func<int, bool> Program.<>c.<>9__0_0"" IL_002e: call ""System.Collections.Generic.IEnumerable<bool> System.Linq.Enumerable.Select<int, bool>(System.Collections.Generic.IEnumerable<int>, System.Func<int, bool>)"" IL_0033: stloc.0 IL_0034: ret } "); v0.VerifyIL("Program.<>c.<N>b__0_0(int)", @" { // Code size 12 (0xc) .maxstack 1 .locals init (int V_0, //x int V_1) //y IL_0000: ldarg.1 IL_0001: stloc.0 IL_0002: ldloc.0 IL_0003: brtrue.s IL_000a IL_0005: ldarg.1 IL_0006: stloc.1 IL_0007: ldc.i4.1 IL_0008: br.s IL_000b IL_000a: ldc.i4.0 IL_000b: ret } "); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, n0, n1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true))); diff1.VerifySynthesizedMembers("Program: {<>c}", "Program.<>c: {<>9__0_0, <N>b__0_0}"); diff1.VerifyIL("Program.N()", @" { // Code size 53 (0x35) .maxstack 4 .locals init (System.Collections.Generic.IEnumerable<bool> V_0) //query IL_0000: nop IL_0001: ldc.i4.2 IL_0002: newarr ""int"" IL_0007: dup IL_0008: ldc.i4.0 IL_0009: ldc.i4.1 IL_000a: stelem.i4 IL_000b: dup IL_000c: ldc.i4.1 IL_000d: ldc.i4.2 IL_000e: stelem.i4 IL_000f: ldsfld ""System.Func<int, bool> Program.<>c.<>9__0_0"" IL_0014: dup IL_0015: brtrue.s IL_002e IL_0017: pop IL_0018: ldsfld ""Program.<>c Program.<>c.<>9"" IL_001d: ldftn ""bool Program.<>c.<N>b__0_0(int)"" IL_0023: newobj ""System.Func<int, bool>..ctor(object, System.IntPtr)"" IL_0028: dup IL_0029: stsfld ""System.Func<int, bool> Program.<>c.<>9__0_0"" IL_002e: call ""System.Collections.Generic.IEnumerable<bool> System.Linq.Enumerable.Select<int, bool>(System.Collections.Generic.IEnumerable<int>, System.Func<int, bool>)"" IL_0033: stloc.0 IL_0034: ret } "); diff1.VerifyIL("Program.<>c.<N>b__0_0(int)", @" { // Code size 7 (0x7) .maxstack 2 .locals init (int V_0, //x [int] V_1) IL_0000: ldarg.1 IL_0001: stloc.0 IL_0002: ldloc.0 IL_0003: ldc.i4.0 IL_0004: ceq IL_0006: ret } "); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, n1, n2, GetSyntaxMapFromMarkers(source1, source0), preserveLocalVariables: true))); diff2.VerifySynthesizedMembers("Program: {<>c}", "Program.<>c: {<>9__0_0, <N>b__0_0}"); diff2.VerifyIL("Program.N()", @" { // Code size 53 (0x35) .maxstack 4 .locals init (System.Collections.Generic.IEnumerable<bool> V_0) //query IL_0000: nop IL_0001: ldc.i4.2 IL_0002: newarr ""int"" IL_0007: dup IL_0008: ldc.i4.0 IL_0009: ldc.i4.1 IL_000a: stelem.i4 IL_000b: dup IL_000c: ldc.i4.1 IL_000d: ldc.i4.2 IL_000e: stelem.i4 IL_000f: ldsfld ""System.Func<int, bool> Program.<>c.<>9__0_0"" IL_0014: dup IL_0015: brtrue.s IL_002e IL_0017: pop IL_0018: ldsfld ""Program.<>c Program.<>c.<>9"" IL_001d: ldftn ""bool Program.<>c.<N>b__0_0(int)"" IL_0023: newobj ""System.Func<int, bool>..ctor(object, System.IntPtr)"" IL_0028: dup IL_0029: stsfld ""System.Func<int, bool> Program.<>c.<>9__0_0"" IL_002e: call ""System.Collections.Generic.IEnumerable<bool> System.Linq.Enumerable.Select<int, bool>(System.Collections.Generic.IEnumerable<int>, System.Func<int, bool>)"" IL_0033: stloc.0 IL_0034: ret } "); diff2.VerifyIL("Program.<>c.<N>b__0_0(int)", @" { // Code size 12 (0xc) .maxstack 1 .locals init (int V_0, //x [int] V_1, int V_2) //y IL_0000: ldarg.1 IL_0001: stloc.0 IL_0002: ldloc.0 IL_0003: brtrue.s IL_000a IL_0005: ldarg.1 IL_0006: stloc.2 IL_0007: ldc.i4.1 IL_0008: br.s IL_000b IL_000a: ldc.i4.0 IL_000b: ret } "); } [Fact] public void Tuple_Parenthesized() { var source0 = MarkedSource(@" class C { static int F() { (int, (int, int)) <N:0>x</N:0> = (1, (2, 3)); return x.Item1 + x.Item2.Item1 + x.Item2.Item2; } }"); var source1 = MarkedSource(@" class C { static int F() { (int, int, int) <N:0>x</N:0> = (1, 2, 3); return x.Item1 + x.Item2 + x.Item3; } }"); var source2 = MarkedSource(@" class C { static int F() { (int, int) <N:0>x</N:0> = (1, 3); return x.Item1 + x.Item2; } }"); var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll); var compilation1 = compilation0.WithSource(source1.Tree); var compilation2 = compilation1.WithSource(source2.Tree); var f0 = compilation0.GetMember<MethodSymbol>("C.F"); var f1 = compilation1.GetMember<MethodSymbol>("C.F"); var f2 = compilation2.GetMember<MethodSymbol>("C.F"); var v0 = CompileAndVerify(compilation0); v0.VerifyIL("C.F", @" { // Code size 51 (0x33) .maxstack 4 .locals init (System.ValueTuple<int, System.ValueTuple<int, int>> V_0, //x int V_1) IL_0000: nop IL_0001: ldloca.s V_0 IL_0003: ldc.i4.1 IL_0004: ldc.i4.2 IL_0005: ldc.i4.3 IL_0006: newobj ""System.ValueTuple<int, int>..ctor(int, int)"" IL_000b: call ""System.ValueTuple<int, System.ValueTuple<int, int>>..ctor(int, System.ValueTuple<int, int>)"" IL_0010: ldloc.0 IL_0011: ldfld ""int System.ValueTuple<int, System.ValueTuple<int, int>>.Item1"" IL_0016: ldloc.0 IL_0017: ldfld ""System.ValueTuple<int, int> System.ValueTuple<int, System.ValueTuple<int, int>>.Item2"" IL_001c: ldfld ""int System.ValueTuple<int, int>.Item1"" IL_0021: add IL_0022: ldloc.0 IL_0023: ldfld ""System.ValueTuple<int, int> System.ValueTuple<int, System.ValueTuple<int, int>>.Item2"" IL_0028: ldfld ""int System.ValueTuple<int, int>.Item2"" IL_002d: add IL_002e: stloc.1 IL_002f: br.s IL_0031 IL_0031: ldloc.1 IL_0032: ret } "); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true))); diff1.VerifyIL("C.F", @" { // Code size 36 (0x24) .maxstack 4 .locals init ([unchanged] V_0, [int] V_1, System.ValueTuple<int, int, int> V_2, //x int V_3) IL_0000: nop IL_0001: ldloca.s V_2 IL_0003: ldc.i4.1 IL_0004: ldc.i4.2 IL_0005: ldc.i4.3 IL_0006: call ""System.ValueTuple<int, int, int>..ctor(int, int, int)"" IL_000b: ldloc.2 IL_000c: ldfld ""int System.ValueTuple<int, int, int>.Item1"" IL_0011: ldloc.2 IL_0012: ldfld ""int System.ValueTuple<int, int, int>.Item2"" IL_0017: add IL_0018: ldloc.2 IL_0019: ldfld ""int System.ValueTuple<int, int, int>.Item3"" IL_001e: add IL_001f: stloc.3 IL_0020: br.s IL_0022 IL_0022: ldloc.3 IL_0023: ret } "); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, f1, f2, GetSyntaxMapFromMarkers(source1, source2), preserveLocalVariables: true))); diff2.VerifyIL("C.F", @" { // Code size 32 (0x20) .maxstack 3 .locals init ([unchanged] V_0, [int] V_1, [unchanged] V_2, [int] V_3, System.ValueTuple<int, int> V_4, //x int V_5) IL_0000: nop IL_0001: ldloca.s V_4 IL_0003: ldc.i4.1 IL_0004: ldc.i4.3 IL_0005: call ""System.ValueTuple<int, int>..ctor(int, int)"" IL_000a: ldloc.s V_4 IL_000c: ldfld ""int System.ValueTuple<int, int>.Item1"" IL_0011: ldloc.s V_4 IL_0013: ldfld ""int System.ValueTuple<int, int>.Item2"" IL_0018: add IL_0019: stloc.s V_5 IL_001b: br.s IL_001d IL_001d: ldloc.s V_5 IL_001f: ret } "); } [Fact] public void Tuple_Decomposition() { var source0 = MarkedSource(@" class C { static int F() { (int <N:0>x</N:0>, int <N:1>y</N:1>, int <N:2>z</N:2>) = (1, 2, 3); return x + y + z; } }"); var source1 = MarkedSource(@" class C { static int F() { (int <N:0>x</N:0>, int <N:2>z</N:2>) = (1, 3); return x + z; } }"); var source2 = MarkedSource(@" class C { static int F() { (int <N:0>x</N:0>, int <N:1>y</N:1>, int <N:2>z</N:2>) = (1, 2, 3); return x + y + z; } }"); var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll); var compilation1 = compilation0.WithSource(source1.Tree); var compilation2 = compilation1.WithSource(source2.Tree); var f0 = compilation0.GetMember<MethodSymbol>("C.F"); var f1 = compilation1.GetMember<MethodSymbol>("C.F"); var f2 = compilation2.GetMember<MethodSymbol>("C.F"); var v0 = CompileAndVerify(compilation0); v0.VerifyIL("C.F", @" { // Code size 17 (0x11) .maxstack 2 .locals init (int V_0, //x int V_1, //y int V_2, //z int V_3) IL_0000: nop IL_0001: ldc.i4.1 IL_0002: stloc.0 IL_0003: ldc.i4.2 IL_0004: stloc.1 IL_0005: ldc.i4.3 IL_0006: stloc.2 IL_0007: ldloc.0 IL_0008: ldloc.1 IL_0009: add IL_000a: ldloc.2 IL_000b: add IL_000c: stloc.3 IL_000d: br.s IL_000f IL_000f: ldloc.3 IL_0010: ret } "); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true))); diff1.VerifyIL("C.F", @" { // Code size 15 (0xf) .maxstack 2 .locals init (int V_0, //x [int] V_1, int V_2, //z [int] V_3, int V_4) IL_0000: nop IL_0001: ldc.i4.1 IL_0002: stloc.0 IL_0003: ldc.i4.3 IL_0004: stloc.2 IL_0005: ldloc.0 IL_0006: ldloc.2 IL_0007: add IL_0008: stloc.s V_4 IL_000a: br.s IL_000c IL_000c: ldloc.s V_4 IL_000e: ret } "); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, f1, f2, GetSyntaxMapFromMarkers(source1, source2), preserveLocalVariables: true))); diff2.VerifyIL("C.F", @" { // Code size 21 (0x15) .maxstack 2 .locals init (int V_0, //x [int] V_1, int V_2, //z [int] V_3, [int] V_4, int V_5, //y int V_6) IL_0000: nop IL_0001: ldc.i4.1 IL_0002: stloc.0 IL_0003: ldc.i4.2 IL_0004: stloc.s V_5 IL_0006: ldc.i4.3 IL_0007: stloc.2 IL_0008: ldloc.0 IL_0009: ldloc.s V_5 IL_000b: add IL_000c: ldloc.2 IL_000d: add IL_000e: stloc.s V_6 IL_0010: br.s IL_0012 IL_0012: ldloc.s V_6 IL_0014: ret } "); } [Fact] public void ForeachStatement() { var source0 = MarkedSource(@" class C { public static (int, (bool, double))[] F() => new[] { (1, (true, 2.0)) }; public static void G() { foreach (var (<N:0>x</N:0>, (<N:1>y</N:1>, <N:2>z</N:2>)) in F()) { System.Console.WriteLine(x); } } }"); var source1 = MarkedSource(@" class C { public static (int, (bool, double))[] F() => new[] { (1, (true, 2.0)) }; public static void G() { foreach (var (<N:0>x1</N:0>, (<N:1>y</N:1>, <N:2>z</N:2>)) in F()) { System.Console.WriteLine(x1); } } }"); var source2 = MarkedSource(@" class C { public static (int, (bool, double))[] F() => new[] { (1, (true, 2.0)) }; public static void G() { foreach (var (<N:0>x1</N:0>, <N:1>yz</N:1>) in F()) { System.Console.WriteLine(x1); } } }"); var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll); var compilation1 = compilation0.WithSource(source1.Tree); var compilation2 = compilation1.WithSource(source2.Tree); var f0 = compilation0.GetMember<MethodSymbol>("C.G"); var f1 = compilation1.GetMember<MethodSymbol>("C.G"); var f2 = compilation2.GetMember<MethodSymbol>("C.G"); var v0 = CompileAndVerify(compilation0); v0.VerifyIL("C.G", @" { // Code size 70 (0x46) .maxstack 2 .locals init (System.ValueTuple<int, System.ValueTuple<bool, double>>[] V_0, int V_1, int V_2, //x bool V_3, //y double V_4, //z System.ValueTuple<bool, double> V_5) IL_0000: nop IL_0001: nop IL_0002: call ""System.ValueTuple<int, System.ValueTuple<bool, double>>[] C.F()"" IL_0007: stloc.0 IL_0008: ldc.i4.0 IL_0009: stloc.1 IL_000a: br.s IL_003f IL_000c: ldloc.0 IL_000d: ldloc.1 IL_000e: ldelem ""System.ValueTuple<int, System.ValueTuple<bool, double>>"" IL_0013: dup IL_0014: ldfld ""System.ValueTuple<bool, double> System.ValueTuple<int, System.ValueTuple<bool, double>>.Item2"" IL_0019: stloc.s V_5 IL_001b: ldfld ""int System.ValueTuple<int, System.ValueTuple<bool, double>>.Item1"" IL_0020: stloc.2 IL_0021: ldloc.s V_5 IL_0023: ldfld ""bool System.ValueTuple<bool, double>.Item1"" IL_0028: stloc.3 IL_0029: ldloc.s V_5 IL_002b: ldfld ""double System.ValueTuple<bool, double>.Item2"" IL_0030: stloc.s V_4 IL_0032: nop IL_0033: ldloc.2 IL_0034: call ""void System.Console.WriteLine(int)"" IL_0039: nop IL_003a: nop IL_003b: ldloc.1 IL_003c: ldc.i4.1 IL_003d: add IL_003e: stloc.1 IL_003f: ldloc.1 IL_0040: ldloc.0 IL_0041: ldlen IL_0042: conv.i4 IL_0043: blt.s IL_000c IL_0045: ret } "); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true))); diff1.VerifyIL("C.G", @" { // Code size 78 (0x4e) .maxstack 2 .locals init ([unchanged] V_0, [int] V_1, int V_2, //x1 bool V_3, //y double V_4, //z [unchanged] V_5, System.ValueTuple<int, System.ValueTuple<bool, double>>[] V_6, int V_7, System.ValueTuple<bool, double> V_8) IL_0000: nop IL_0001: nop IL_0002: call ""System.ValueTuple<int, System.ValueTuple<bool, double>>[] C.F()"" IL_0007: stloc.s V_6 IL_0009: ldc.i4.0 IL_000a: stloc.s V_7 IL_000c: br.s IL_0045 IL_000e: ldloc.s V_6 IL_0010: ldloc.s V_7 IL_0012: ldelem ""System.ValueTuple<int, System.ValueTuple<bool, double>>"" IL_0017: dup IL_0018: ldfld ""System.ValueTuple<bool, double> System.ValueTuple<int, System.ValueTuple<bool, double>>.Item2"" IL_001d: stloc.s V_8 IL_001f: ldfld ""int System.ValueTuple<int, System.ValueTuple<bool, double>>.Item1"" IL_0024: stloc.2 IL_0025: ldloc.s V_8 IL_0027: ldfld ""bool System.ValueTuple<bool, double>.Item1"" IL_002c: stloc.3 IL_002d: ldloc.s V_8 IL_002f: ldfld ""double System.ValueTuple<bool, double>.Item2"" IL_0034: stloc.s V_4 IL_0036: nop IL_0037: ldloc.2 IL_0038: call ""void System.Console.WriteLine(int)"" IL_003d: nop IL_003e: nop IL_003f: ldloc.s V_7 IL_0041: ldc.i4.1 IL_0042: add IL_0043: stloc.s V_7 IL_0045: ldloc.s V_7 IL_0047: ldloc.s V_6 IL_0049: ldlen IL_004a: conv.i4 IL_004b: blt.s IL_000e IL_004d: ret } "); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, f1, f2, GetSyntaxMapFromMarkers(source1, source2), preserveLocalVariables: true))); diff2.VerifyIL("C.G", @" { // Code size 61 (0x3d) .maxstack 2 .locals init ([unchanged] V_0, [int] V_1, int V_2, //x1 [bool] V_3, [unchanged] V_4, [unchanged] V_5, [unchanged] V_6, [int] V_7, [unchanged] V_8, System.ValueTuple<int, System.ValueTuple<bool, double>>[] V_9, int V_10, System.ValueTuple<bool, double> V_11) //yz IL_0000: nop IL_0001: nop IL_0002: call ""System.ValueTuple<int, System.ValueTuple<bool, double>>[] C.F()"" IL_0007: stloc.s V_9 IL_0009: ldc.i4.0 IL_000a: stloc.s V_10 IL_000c: br.s IL_0034 IL_000e: ldloc.s V_9 IL_0010: ldloc.s V_10 IL_0012: ldelem ""System.ValueTuple<int, System.ValueTuple<bool, double>>"" IL_0017: dup IL_0018: ldfld ""int System.ValueTuple<int, System.ValueTuple<bool, double>>.Item1"" IL_001d: stloc.2 IL_001e: ldfld ""System.ValueTuple<bool, double> System.ValueTuple<int, System.ValueTuple<bool, double>>.Item2"" IL_0023: stloc.s V_11 IL_0025: nop IL_0026: ldloc.2 IL_0027: call ""void System.Console.WriteLine(int)"" IL_002c: nop IL_002d: nop IL_002e: ldloc.s V_10 IL_0030: ldc.i4.1 IL_0031: add IL_0032: stloc.s V_10 IL_0034: ldloc.s V_10 IL_0036: ldloc.s V_9 IL_0038: ldlen IL_0039: conv.i4 IL_003a: blt.s IL_000e IL_003c: ret } "); } [Fact] public void OutVar() { var source0 = MarkedSource(@" class C { static void F(out int x, out int y) { x = 1; y = 2; } static int G() { F(out int <N:0>x</N:0>, out var <N:1>y</N:1>); return x + y; } }"); var source1 = MarkedSource(@" class C { static void F(out int x, out int y) { x = 1; y = 2; } static int G() { F(out int <N:0>x</N:0>, out var <N:1>z</N:1>); return x + z; } }"); var source2 = MarkedSource(@" class C { static void F(out int x, out int y) { x = 1; y = 2; } static int G() { F(out int <N:0>x</N:0>, out int <N:1>y</N:1>); return x + y; } }"); var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll); var compilation1 = compilation0.WithSource(source1.Tree); var compilation2 = compilation1.WithSource(source2.Tree); var f0 = compilation0.GetMember<MethodSymbol>("C.G"); var f1 = compilation1.GetMember<MethodSymbol>("C.G"); var f2 = compilation2.GetMember<MethodSymbol>("C.G"); var v0 = CompileAndVerify(compilation0); v0.VerifyIL("C.G", @" { // Code size 19 (0x13) .maxstack 2 .locals init (int V_0, //x int V_1, //y int V_2) IL_0000: nop IL_0001: ldloca.s V_0 IL_0003: ldloca.s V_1 IL_0005: call ""void C.F(out int, out int)"" IL_000a: nop IL_000b: ldloc.0 IL_000c: ldloc.1 IL_000d: add IL_000e: stloc.2 IL_000f: br.s IL_0011 IL_0011: ldloc.2 IL_0012: ret } "); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true))); diff1.VerifyIL("C.G", @" { // Code size 19 (0x13) .maxstack 2 .locals init (int V_0, //x int V_1, //z [int] V_2, int V_3) IL_0000: nop IL_0001: ldloca.s V_0 IL_0003: ldloca.s V_1 IL_0005: call ""void C.F(out int, out int)"" IL_000a: nop IL_000b: ldloc.0 IL_000c: ldloc.1 IL_000d: add IL_000e: stloc.3 IL_000f: br.s IL_0011 IL_0011: ldloc.3 IL_0012: ret } "); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, f1, f2, GetSyntaxMapFromMarkers(source1, source2), preserveLocalVariables: true))); diff2.VerifyIL("C.G", @" { // Code size 21 (0x15) .maxstack 2 .locals init (int V_0, //x int V_1, //y [int] V_2, [int] V_3, int V_4) IL_0000: nop IL_0001: ldloca.s V_0 IL_0003: ldloca.s V_1 IL_0005: call ""void C.F(out int, out int)"" IL_000a: nop IL_000b: ldloc.0 IL_000c: ldloc.1 IL_000d: add IL_000e: stloc.s V_4 IL_0010: br.s IL_0012 IL_0012: ldloc.s V_4 IL_0014: ret } "); } [Fact] public void OutVar_InConstructorInitializer() { var baseClass = "public class Base { public Base(int x) { } }"; var source0 = MarkedSource(@" public class C : Base { public C() : base(M(out int <N:0>x</N:0>) + x + M(out int <N:1>y</N:1>)) { System.Console.Write(y); } static int M(out int x) => throw null; }" + baseClass); var source1 = MarkedSource(@" public class C : Base { public C() : base(M(out int <N:0>x</N:0>) + x) { } static int M(out int x) => throw null; }" + baseClass); var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll); var compilation1 = compilation0.WithSource(source1.Tree); var compilation2 = compilation1.WithSource(source0.Tree); var ctor0 = compilation0.GetMember<MethodSymbol>("C..ctor"); var ctor1 = compilation1.GetMember<MethodSymbol>("C..ctor"); var ctor2 = compilation2.GetMember<MethodSymbol>("C..ctor"); var v0 = CompileAndVerify(compilation0); v0.VerifyIL("C..ctor", @" { // Code size 33 (0x21) .maxstack 3 .locals init (int V_0, //x int V_1) //y IL_0000: ldarg.0 IL_0001: ldloca.s V_0 IL_0003: call ""int C.M(out int)"" IL_0008: ldloc.0 IL_0009: add IL_000a: ldloca.s V_1 IL_000c: call ""int C.M(out int)"" IL_0011: add IL_0012: call ""Base..ctor(int)"" IL_0017: nop IL_0018: nop IL_0019: ldloc.1 IL_001a: call ""void System.Console.Write(int)"" IL_001f: nop IL_0020: ret } "); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, ctor0, ctor1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true))); diff1.VerifyIL("C..ctor", @" { // Code size 18 (0x12) .maxstack 3 .locals init (int V_0, //x [int] V_1) IL_0000: ldarg.0 IL_0001: ldloca.s V_0 IL_0003: call ""int C.M(out int)"" IL_0008: ldloc.0 IL_0009: add IL_000a: call ""Base..ctor(int)"" IL_000f: nop IL_0010: nop IL_0011: ret } "); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, ctor1, ctor2, GetSyntaxMapFromMarkers(source1, source0), preserveLocalVariables: true))); diff2.VerifyIL("C..ctor", @" { // Code size 33 (0x21) .maxstack 3 .locals init (int V_0, //x [int] V_1, int V_2) //y IL_0000: ldarg.0 IL_0001: ldloca.s V_0 IL_0003: call ""int C.M(out int)"" IL_0008: ldloc.0 IL_0009: add IL_000a: ldloca.s V_2 IL_000c: call ""int C.M(out int)"" IL_0011: add IL_0012: call ""Base..ctor(int)"" IL_0017: nop IL_0018: nop IL_0019: ldloc.2 IL_001a: call ""void System.Console.Write(int)"" IL_001f: nop IL_0020: ret } "); } [Fact] public void OutVar_InConstructorInitializer_WithLambda() { var baseClass = "public class Base { public Base(int x) { } }"; var source0 = MarkedSource(@" public class C : Base { <N:0>public C() : base(M(out int <N:1>x</N:1>) + M2(<N:2>() => x + 1</N:2>)) { }</N:0> static int M(out int x) => throw null; static int M2(System.Func<int> x) => throw null; }" + baseClass); var source1 = MarkedSource(@" public class C : Base { <N:0>public C() : base(M(out int <N:1>x</N:1>) + M2(<N:2>() => x - 1</N:2>)) { }</N:0> static int M(out int x) => throw null; static int M2(System.Func<int> x) => throw null; }" + baseClass); var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll); var compilation1 = compilation0.WithSource(source1.Tree); var compilation2 = compilation1.WithSource(source0.Tree); var ctor0 = compilation0.GetMember<MethodSymbol>("C..ctor"); var ctor1 = compilation1.GetMember<MethodSymbol>("C..ctor"); var ctor2 = compilation2.GetMember<MethodSymbol>("C..ctor"); var v0 = CompileAndVerify(compilation0); v0.VerifyIL("C..ctor", @" { // Code size 44 (0x2c) .maxstack 4 .locals init (C.<>c__DisplayClass0_0 V_0) //CS$<>8__locals0 IL_0000: newobj ""C.<>c__DisplayClass0_0..ctor()"" IL_0005: stloc.0 IL_0006: ldarg.0 IL_0007: ldloc.0 IL_0008: ldflda ""int C.<>c__DisplayClass0_0.x"" IL_000d: call ""int C.M(out int)"" IL_0012: ldloc.0 IL_0013: ldftn ""int C.<>c__DisplayClass0_0.<.ctor>b__0()"" IL_0019: newobj ""System.Func<int>..ctor(object, System.IntPtr)"" IL_001e: call ""int C.M2(System.Func<int>)"" IL_0023: add IL_0024: call ""Base..ctor(int)"" IL_0029: nop IL_002a: nop IL_002b: ret } "); v0.VerifyIL("C.<>c__DisplayClass0_0.<.ctor>b__0()", @" { // Code size 9 (0x9) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldfld ""int C.<>c__DisplayClass0_0.x"" IL_0006: ldc.i4.1 IL_0007: add IL_0008: ret } "); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var reader0 = md0.MetadataReader; var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, ctor0, ctor1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true))); using var md1 = diff1.GetMetadata(); var reader1 = md1.Reader; var readers = new[] { reader0, reader1 }; CheckNames(readers, diff1.EmitResult.ChangedTypes, "C", "<>c__DisplayClass0_0"); diff1.VerifySynthesizedMembers( "C: {<>c__DisplayClass0_0}", "C.<>c__DisplayClass0_0: {x, <.ctor>b__0}"); diff1.VerifyIL("C..ctor", @" { // Code size 44 (0x2c) .maxstack 4 .locals init (C.<>c__DisplayClass0_0 V_0) //CS$<>8__locals0 IL_0000: newobj ""C.<>c__DisplayClass0_0..ctor()"" IL_0005: stloc.0 IL_0006: ldarg.0 IL_0007: ldloc.0 IL_0008: ldflda ""int C.<>c__DisplayClass0_0.x"" IL_000d: call ""int C.M(out int)"" IL_0012: ldloc.0 IL_0013: ldftn ""int C.<>c__DisplayClass0_0.<.ctor>b__0()"" IL_0019: newobj ""System.Func<int>..ctor(object, System.IntPtr)"" IL_001e: call ""int C.M2(System.Func<int>)"" IL_0023: add IL_0024: call ""Base..ctor(int)"" IL_0029: nop IL_002a: nop IL_002b: ret } "); diff1.VerifyIL("C.<>c__DisplayClass0_0.<.ctor>b__0()", @" { // Code size 9 (0x9) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldfld ""int C.<>c__DisplayClass0_0.x"" IL_0006: ldc.i4.1 IL_0007: sub IL_0008: ret } "); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, ctor1, ctor2, GetSyntaxMapFromMarkers(source1, source0), preserveLocalVariables: true))); using var md2 = diff2.GetMetadata(); var reader2 = md2.Reader; readers = new[] { reader0, reader1, reader2 }; CheckNames(readers, diff2.EmitResult.ChangedTypes, "C", "<>c__DisplayClass0_0"); diff2.VerifySynthesizedMembers( "C: {<>c__DisplayClass0_0}", "C.<>c__DisplayClass0_0: {x, <.ctor>b__0}"); diff2.VerifyIL("C..ctor", @" { // Code size 44 (0x2c) .maxstack 4 .locals init (C.<>c__DisplayClass0_0 V_0) //CS$<>8__locals0 IL_0000: newobj ""C.<>c__DisplayClass0_0..ctor()"" IL_0005: stloc.0 IL_0006: ldarg.0 IL_0007: ldloc.0 IL_0008: ldflda ""int C.<>c__DisplayClass0_0.x"" IL_000d: call ""int C.M(out int)"" IL_0012: ldloc.0 IL_0013: ldftn ""int C.<>c__DisplayClass0_0.<.ctor>b__0()"" IL_0019: newobj ""System.Func<int>..ctor(object, System.IntPtr)"" IL_001e: call ""int C.M2(System.Func<int>)"" IL_0023: add IL_0024: call ""Base..ctor(int)"" IL_0029: nop IL_002a: nop IL_002b: ret } "); diff2.VerifyIL("C.<>c__DisplayClass0_0.<.ctor>b__0()", @" { // Code size 9 (0x9) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldfld ""int C.<>c__DisplayClass0_0.x"" IL_0006: ldc.i4.1 IL_0007: add IL_0008: ret } "); } [Fact] public void OutVar_InMethodBody_WithLambda() { var source0 = MarkedSource(@" public class C { public void Method() <N:0>{ int _ = M(out int <N:1>x</N:1>) + M2(<N:2>() => x + 1</N:2>); }</N:0> static int M(out int x) => throw null; static int M2(System.Func<int> x) => throw null; }"); var source1 = MarkedSource(@" public class C { public void Method() <N:0>{ int _ = M(out int <N:1>x</N:1>) + M2(<N:2>() => x - 1</N:2>); }</N:0> static int M(out int x) => throw null; static int M2(System.Func<int> x) => throw null; }"); var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll); var compilation1 = compilation0.WithSource(source1.Tree); var compilation2 = compilation1.WithSource(source0.Tree); var ctor0 = compilation0.GetMember<MethodSymbol>("C.Method"); var ctor1 = compilation1.GetMember<MethodSymbol>("C.Method"); var ctor2 = compilation2.GetMember<MethodSymbol>("C.Method"); var v0 = CompileAndVerify(compilation0); v0.VerifyIL("C.Method", @" { // Code size 38 (0x26) .maxstack 3 .locals init (C.<>c__DisplayClass0_0 V_0, //CS$<>8__locals0 int V_1) //_ IL_0000: newobj ""C.<>c__DisplayClass0_0..ctor()"" IL_0005: stloc.0 IL_0006: nop IL_0007: ldloc.0 IL_0008: ldflda ""int C.<>c__DisplayClass0_0.x"" IL_000d: call ""int C.M(out int)"" IL_0012: ldloc.0 IL_0013: ldftn ""int C.<>c__DisplayClass0_0.<Method>b__0()"" IL_0019: newobj ""System.Func<int>..ctor(object, System.IntPtr)"" IL_001e: call ""int C.M2(System.Func<int>)"" IL_0023: add IL_0024: stloc.1 IL_0025: ret } "); v0.VerifyIL("C.<>c__DisplayClass0_0.<Method>b__0()", @" { // Code size 9 (0x9) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldfld ""int C.<>c__DisplayClass0_0.x"" IL_0006: ldc.i4.1 IL_0007: add IL_0008: ret } "); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, ctor0, ctor1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true))); diff1.VerifySynthesizedMembers("C: {<>c__DisplayClass0_0}", "C.<>c__DisplayClass0_0: {x, <Method>b__0}"); diff1.VerifyIL("C.Method", @" { // Code size 38 (0x26) .maxstack 3 .locals init (C.<>c__DisplayClass0_0 V_0, //CS$<>8__locals0 [int] V_1, int V_2) //_ IL_0000: newobj ""C.<>c__DisplayClass0_0..ctor()"" IL_0005: stloc.0 IL_0006: nop IL_0007: ldloc.0 IL_0008: ldflda ""int C.<>c__DisplayClass0_0.x"" IL_000d: call ""int C.M(out int)"" IL_0012: ldloc.0 IL_0013: ldftn ""int C.<>c__DisplayClass0_0.<Method>b__0()"" IL_0019: newobj ""System.Func<int>..ctor(object, System.IntPtr)"" IL_001e: call ""int C.M2(System.Func<int>)"" IL_0023: add IL_0024: stloc.2 IL_0025: ret } "); diff1.VerifyIL("C.<>c__DisplayClass0_0.<Method>b__0()", @" { // Code size 9 (0x9) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldfld ""int C.<>c__DisplayClass0_0.x"" IL_0006: ldc.i4.1 IL_0007: sub IL_0008: ret } "); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, ctor1, ctor2, GetSyntaxMapFromMarkers(source1, source0), preserveLocalVariables: true))); diff2.VerifySynthesizedMembers("C: {<>c__DisplayClass0_0}", "C.<>c__DisplayClass0_0: {x, <Method>b__0}"); diff2.VerifyIL("C.Method", @" { // Code size 38 (0x26) .maxstack 3 .locals init (C.<>c__DisplayClass0_0 V_0, //CS$<>8__locals0 [int] V_1, [int] V_2, int V_3) //_ IL_0000: newobj ""C.<>c__DisplayClass0_0..ctor()"" IL_0005: stloc.0 IL_0006: nop IL_0007: ldloc.0 IL_0008: ldflda ""int C.<>c__DisplayClass0_0.x"" IL_000d: call ""int C.M(out int)"" IL_0012: ldloc.0 IL_0013: ldftn ""int C.<>c__DisplayClass0_0.<Method>b__0()"" IL_0019: newobj ""System.Func<int>..ctor(object, System.IntPtr)"" IL_001e: call ""int C.M2(System.Func<int>)"" IL_0023: add IL_0024: stloc.3 IL_0025: ret } "); diff2.VerifyIL("C.<>c__DisplayClass0_0.<Method>b__0()", @" { // Code size 9 (0x9) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldfld ""int C.<>c__DisplayClass0_0.x"" IL_0006: ldc.i4.1 IL_0007: add IL_0008: ret } "); } [Fact] public void OutVar_InFieldInitializer() { var source0 = MarkedSource(@" public class C { public int field = M(out int <N:0>x</N:0>) + x + M(out int <N:1>y</N:1>); static int M(out int x) => throw null; }"); var source1 = MarkedSource(@" public class C { public int field = M(out int <N:0>x</N:0>) + x; static int M(out int x) => throw null; }"); var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll); var compilation1 = compilation0.WithSource(source1.Tree); var compilation2 = compilation1.WithSource(source0.Tree); var ctor0 = compilation0.GetMember<MethodSymbol>("C..ctor"); var ctor1 = compilation1.GetMember<MethodSymbol>("C..ctor"); var ctor2 = compilation2.GetMember<MethodSymbol>("C..ctor"); var v0 = CompileAndVerify(compilation0); v0.VerifyIL("C..ctor", @" { // Code size 31 (0x1f) .maxstack 3 .locals init (int V_0, //x int V_1) //y IL_0000: ldarg.0 IL_0001: ldloca.s V_0 IL_0003: call ""int C.M(out int)"" IL_0008: ldloc.0 IL_0009: add IL_000a: ldloca.s V_1 IL_000c: call ""int C.M(out int)"" IL_0011: add IL_0012: stfld ""int C.field"" IL_0017: ldarg.0 IL_0018: call ""object..ctor()"" IL_001d: nop IL_001e: ret } "); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, ctor0, ctor1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true))); diff1.VerifyIL("C..ctor", @" { // Code size 23 (0x17) .maxstack 3 .locals init (int V_0, //x [int] V_1) IL_0000: ldarg.0 IL_0001: ldloca.s V_0 IL_0003: call ""int C.M(out int)"" IL_0008: ldloc.0 IL_0009: add IL_000a: stfld ""int C.field"" IL_000f: ldarg.0 IL_0010: call ""object..ctor()"" IL_0015: nop IL_0016: ret } "); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, ctor1, ctor2, GetSyntaxMapFromMarkers(source1, source0), preserveLocalVariables: true))); diff2.VerifyIL("C..ctor", @" { // Code size 31 (0x1f) .maxstack 3 .locals init (int V_0, //x [int] V_1, int V_2) //y IL_0000: ldarg.0 IL_0001: ldloca.s V_0 IL_0003: call ""int C.M(out int)"" IL_0008: ldloc.0 IL_0009: add IL_000a: ldloca.s V_2 IL_000c: call ""int C.M(out int)"" IL_0011: add IL_0012: stfld ""int C.field"" IL_0017: ldarg.0 IL_0018: call ""object..ctor()"" IL_001d: nop IL_001e: ret } "); } [Fact] public void OutVar_InFieldInitializer_WithLambda() { var source0 = MarkedSource(@" public class C { int field = <N:0>M(out int <N:1>x</N:1>) + M2(<N:2>() => x + 1</N:2>)</N:0>; static int M(out int x) => throw null; static int M2(System.Func<int> x) => throw null; }"); var source1 = MarkedSource(@" public class C { int field = <N:0>M(out int <N:1>x</N:1>) + M2(<N:2>() => x - 1</N:2>)</N:0>; static int M(out int x) => throw null; static int M2(System.Func<int> x) => throw null; }"); var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll); var compilation1 = compilation0.WithSource(source1.Tree); var compilation2 = compilation1.WithSource(source0.Tree); var ctor0 = compilation0.GetMember<MethodSymbol>("C..ctor"); var ctor1 = compilation1.GetMember<MethodSymbol>("C..ctor"); var ctor2 = compilation2.GetMember<MethodSymbol>("C..ctor"); var v0 = CompileAndVerify(compilation0); v0.VerifyIL("C..ctor", @" { // Code size 49 (0x31) .maxstack 4 .locals init (C.<>c__DisplayClass3_0 V_0) //CS$<>8__locals0 IL_0000: newobj ""C.<>c__DisplayClass3_0..ctor()"" IL_0005: stloc.0 IL_0006: ldarg.0 IL_0007: ldloc.0 IL_0008: ldflda ""int C.<>c__DisplayClass3_0.x"" IL_000d: call ""int C.M(out int)"" IL_0012: ldloc.0 IL_0013: ldftn ""int C.<>c__DisplayClass3_0.<.ctor>b__0()"" IL_0019: newobj ""System.Func<int>..ctor(object, System.IntPtr)"" IL_001e: call ""int C.M2(System.Func<int>)"" IL_0023: add IL_0024: stfld ""int C.field"" IL_0029: ldarg.0 IL_002a: call ""object..ctor()"" IL_002f: nop IL_0030: ret } "); v0.VerifyIL("C.<>c__DisplayClass3_0.<.ctor>b__0()", @" { // Code size 9 (0x9) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldfld ""int C.<>c__DisplayClass3_0.x"" IL_0006: ldc.i4.1 IL_0007: add IL_0008: ret } "); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, ctor0, ctor1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true))); diff1.VerifySynthesizedMembers( "C.<>c__DisplayClass3_0: {x, <.ctor>b__0}", "C: {<>c__DisplayClass3_0}"); diff1.VerifyIL("C..ctor", @" { // Code size 49 (0x31) .maxstack 4 .locals init (C.<>c__DisplayClass3_0 V_0) //CS$<>8__locals0 IL_0000: newobj ""C.<>c__DisplayClass3_0..ctor()"" IL_0005: stloc.0 IL_0006: ldarg.0 IL_0007: ldloc.0 IL_0008: ldflda ""int C.<>c__DisplayClass3_0.x"" IL_000d: call ""int C.M(out int)"" IL_0012: ldloc.0 IL_0013: ldftn ""int C.<>c__DisplayClass3_0.<.ctor>b__0()"" IL_0019: newobj ""System.Func<int>..ctor(object, System.IntPtr)"" IL_001e: call ""int C.M2(System.Func<int>)"" IL_0023: add IL_0024: stfld ""int C.field"" IL_0029: ldarg.0 IL_002a: call ""object..ctor()"" IL_002f: nop IL_0030: ret } "); diff1.VerifyIL("C.<>c__DisplayClass3_0.<.ctor>b__0()", @" { // Code size 9 (0x9) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldfld ""int C.<>c__DisplayClass3_0.x"" IL_0006: ldc.i4.1 IL_0007: sub IL_0008: ret } "); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, ctor1, ctor2, GetSyntaxMapFromMarkers(source1, source0), preserveLocalVariables: true))); diff2.VerifySynthesizedMembers( "C.<>c__DisplayClass3_0: {x, <.ctor>b__0}", "C: {<>c__DisplayClass3_0}"); diff2.VerifyIL("C..ctor", @" { // Code size 49 (0x31) .maxstack 4 .locals init (C.<>c__DisplayClass3_0 V_0) //CS$<>8__locals0 IL_0000: newobj ""C.<>c__DisplayClass3_0..ctor()"" IL_0005: stloc.0 IL_0006: ldarg.0 IL_0007: ldloc.0 IL_0008: ldflda ""int C.<>c__DisplayClass3_0.x"" IL_000d: call ""int C.M(out int)"" IL_0012: ldloc.0 IL_0013: ldftn ""int C.<>c__DisplayClass3_0.<.ctor>b__0()"" IL_0019: newobj ""System.Func<int>..ctor(object, System.IntPtr)"" IL_001e: call ""int C.M2(System.Func<int>)"" IL_0023: add IL_0024: stfld ""int C.field"" IL_0029: ldarg.0 IL_002a: call ""object..ctor()"" IL_002f: nop IL_0030: ret } "); diff2.VerifyIL("C.<>c__DisplayClass3_0.<.ctor>b__0()", @" { // Code size 9 (0x9) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldfld ""int C.<>c__DisplayClass3_0.x"" IL_0006: ldc.i4.1 IL_0007: add IL_0008: ret } "); } [Fact] public void OutVar_InQuery() { var source0 = MarkedSource(@" using System.Linq; public class Program { static int M(int x, out int y) { y = 42; return 43; } static void N() { var <N:0>query = from a in new int[] { 1, 2 } <N:1>select M(a, out int <N:2>x</N:2>) + x + M(a, out int <N:3>y</N:3></N:1>)</N:0>; } }"); var source1 = MarkedSource(@" using System.Linq; public class Program { static int M(int x, out int y) { y = 42; return 43; } static void N() { var <N:0>query = from a in new int[] { 1, 2 } <N:1>select M(a, out int <N:2>x</N:2>) + x</N:1></N:0>; } }"); var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll); var compilation1 = compilation0.WithSource(source1.Tree); var compilation2 = compilation1.WithSource(source0.Tree); var n0 = compilation0.GetMember<MethodSymbol>("Program.N"); var n1 = compilation1.GetMember<MethodSymbol>("Program.N"); var n2 = compilation2.GetMember<MethodSymbol>("Program.N"); var v0 = CompileAndVerify(compilation0); v0.VerifyIL("Program.N()", @" { // Code size 53 (0x35) .maxstack 4 .locals init (System.Collections.Generic.IEnumerable<int> V_0) //query IL_0000: nop IL_0001: ldc.i4.2 IL_0002: newarr ""int"" IL_0007: dup IL_0008: ldc.i4.0 IL_0009: ldc.i4.1 IL_000a: stelem.i4 IL_000b: dup IL_000c: ldc.i4.1 IL_000d: ldc.i4.2 IL_000e: stelem.i4 IL_000f: ldsfld ""System.Func<int, int> Program.<>c.<>9__1_0"" IL_0014: dup IL_0015: brtrue.s IL_002e IL_0017: pop IL_0018: ldsfld ""Program.<>c Program.<>c.<>9"" IL_001d: ldftn ""int Program.<>c.<N>b__1_0(int)"" IL_0023: newobj ""System.Func<int, int>..ctor(object, System.IntPtr)"" IL_0028: dup IL_0029: stsfld ""System.Func<int, int> Program.<>c.<>9__1_0"" IL_002e: call ""System.Collections.Generic.IEnumerable<int> System.Linq.Enumerable.Select<int, int>(System.Collections.Generic.IEnumerable<int>, System.Func<int, int>)"" IL_0033: stloc.0 IL_0034: ret } "); v0.VerifyIL("Program.<>c.<N>b__1_0(int)", @" { // Code size 20 (0x14) .maxstack 3 .locals init (int V_0, //x int V_1) //y IL_0000: ldarg.1 IL_0001: ldloca.s V_0 IL_0003: call ""int Program.M(int, out int)"" IL_0008: ldloc.0 IL_0009: add IL_000a: ldarg.1 IL_000b: ldloca.s V_1 IL_000d: call ""int Program.M(int, out int)"" IL_0012: add IL_0013: ret } "); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, n0, n1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true))); diff1.VerifySynthesizedMembers( "Program: {<>c}", "Program.<>c: {<>9__1_0, <N>b__1_0}"); diff1.VerifyIL("Program.N()", @" { // Code size 53 (0x35) .maxstack 4 .locals init (System.Collections.Generic.IEnumerable<int> V_0) //query IL_0000: nop IL_0001: ldc.i4.2 IL_0002: newarr ""int"" IL_0007: dup IL_0008: ldc.i4.0 IL_0009: ldc.i4.1 IL_000a: stelem.i4 IL_000b: dup IL_000c: ldc.i4.1 IL_000d: ldc.i4.2 IL_000e: stelem.i4 IL_000f: ldsfld ""System.Func<int, int> Program.<>c.<>9__1_0"" IL_0014: dup IL_0015: brtrue.s IL_002e IL_0017: pop IL_0018: ldsfld ""Program.<>c Program.<>c.<>9"" IL_001d: ldftn ""int Program.<>c.<N>b__1_0(int)"" IL_0023: newobj ""System.Func<int, int>..ctor(object, System.IntPtr)"" IL_0028: dup IL_0029: stsfld ""System.Func<int, int> Program.<>c.<>9__1_0"" IL_002e: call ""System.Collections.Generic.IEnumerable<int> System.Linq.Enumerable.Select<int, int>(System.Collections.Generic.IEnumerable<int>, System.Func<int, int>)"" IL_0033: stloc.0 IL_0034: ret } "); diff1.VerifyIL("Program.<>c.<N>b__1_0(int)", @" { // Code size 11 (0xb) .maxstack 2 .locals init (int V_0, //x [int] V_1) IL_0000: ldarg.1 IL_0001: ldloca.s V_0 IL_0003: call ""int Program.M(int, out int)"" IL_0008: ldloc.0 IL_0009: add IL_000a: ret } "); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, n1, n2, GetSyntaxMapFromMarkers(source1, source0), preserveLocalVariables: true))); diff2.VerifySynthesizedMembers( "Program: {<>c}", "Program.<>c: {<>9__1_0, <N>b__1_0}"); diff2.VerifyIL("Program.N()", @" { // Code size 53 (0x35) .maxstack 4 .locals init (System.Collections.Generic.IEnumerable<int> V_0) //query IL_0000: nop IL_0001: ldc.i4.2 IL_0002: newarr ""int"" IL_0007: dup IL_0008: ldc.i4.0 IL_0009: ldc.i4.1 IL_000a: stelem.i4 IL_000b: dup IL_000c: ldc.i4.1 IL_000d: ldc.i4.2 IL_000e: stelem.i4 IL_000f: ldsfld ""System.Func<int, int> Program.<>c.<>9__1_0"" IL_0014: dup IL_0015: brtrue.s IL_002e IL_0017: pop IL_0018: ldsfld ""Program.<>c Program.<>c.<>9"" IL_001d: ldftn ""int Program.<>c.<N>b__1_0(int)"" IL_0023: newobj ""System.Func<int, int>..ctor(object, System.IntPtr)"" IL_0028: dup IL_0029: stsfld ""System.Func<int, int> Program.<>c.<>9__1_0"" IL_002e: call ""System.Collections.Generic.IEnumerable<int> System.Linq.Enumerable.Select<int, int>(System.Collections.Generic.IEnumerable<int>, System.Func<int, int>)"" IL_0033: stloc.0 IL_0034: ret } "); diff2.VerifyIL("Program.<>c.<N>b__1_0(int)", @" { // Code size 20 (0x14) .maxstack 3 .locals init (int V_0, //x [int] V_1, int V_2) //y IL_0000: ldarg.1 IL_0001: ldloca.s V_0 IL_0003: call ""int Program.M(int, out int)"" IL_0008: ldloc.0 IL_0009: add IL_000a: ldarg.1 IL_000b: ldloca.s V_2 IL_000d: call ""int Program.M(int, out int)"" IL_0012: add IL_0013: ret } "); } [Fact] public void OutVar_InQuery_WithLambda() { var source0 = MarkedSource(@" using System.Linq; public class Program { static int M(int x, out int y) { y = 42; return 43; } static int M2(System.Func<int> x) => throw null; static void N() { var <N:0>query = from a in new int[] { 1, 2 } <N:1>select <N:2>M(a, out int <N:3>x</N:3>) + M2(<N:4>() => x + 1</N:4>)</N:2></N:1></N:0>; } }"); var source1 = MarkedSource(@" using System.Linq; public class Program { static int M(int x, out int y) { y = 42; return 43; } static int M2(System.Func<int> x) => throw null; static void N() { var <N:0>query = from a in new int[] { 1, 2 } <N:1>select <N:2>M(a, out int <N:3>x</N:3>) + M2(<N:4>() => x - 1</N:4>)</N:2></N:1></N:0>; } }"); var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll); var compilation1 = compilation0.WithSource(source1.Tree); var compilation2 = compilation1.WithSource(source0.Tree); var n0 = compilation0.GetMember<MethodSymbol>("Program.N"); var n1 = compilation1.GetMember<MethodSymbol>("Program.N"); var n2 = compilation2.GetMember<MethodSymbol>("Program.N"); var v0 = CompileAndVerify(compilation0); v0.VerifyIL("Program.N()", @" { // Code size 53 (0x35) .maxstack 4 .locals init (System.Collections.Generic.IEnumerable<int> V_0) //query IL_0000: nop IL_0001: ldc.i4.2 IL_0002: newarr ""int"" IL_0007: dup IL_0008: ldc.i4.0 IL_0009: ldc.i4.1 IL_000a: stelem.i4 IL_000b: dup IL_000c: ldc.i4.1 IL_000d: ldc.i4.2 IL_000e: stelem.i4 IL_000f: ldsfld ""System.Func<int, int> Program.<>c.<>9__2_0"" IL_0014: dup IL_0015: brtrue.s IL_002e IL_0017: pop IL_0018: ldsfld ""Program.<>c Program.<>c.<>9"" IL_001d: ldftn ""int Program.<>c.<N>b__2_0(int)"" IL_0023: newobj ""System.Func<int, int>..ctor(object, System.IntPtr)"" IL_0028: dup IL_0029: stsfld ""System.Func<int, int> Program.<>c.<>9__2_0"" IL_002e: call ""System.Collections.Generic.IEnumerable<int> System.Linq.Enumerable.Select<int, int>(System.Collections.Generic.IEnumerable<int>, System.Func<int, int>)"" IL_0033: stloc.0 IL_0034: ret } "); v0.VerifyIL("Program.<>c.<N>b__2_0(int)", @" { // Code size 37 (0x25) .maxstack 3 .locals init (Program.<>c__DisplayClass2_0 V_0) //CS$<>8__locals0 IL_0000: newobj ""Program.<>c__DisplayClass2_0..ctor()"" IL_0005: stloc.0 IL_0006: ldarg.1 IL_0007: ldloc.0 IL_0008: ldflda ""int Program.<>c__DisplayClass2_0.x"" IL_000d: call ""int Program.M(int, out int)"" IL_0012: ldloc.0 IL_0013: ldftn ""int Program.<>c__DisplayClass2_0.<N>b__1()"" IL_0019: newobj ""System.Func<int>..ctor(object, System.IntPtr)"" IL_001e: call ""int Program.M2(System.Func<int>)"" IL_0023: add IL_0024: ret } "); v0.VerifyIL("Program.<>c__DisplayClass2_0.<N>b__1()", @" { // Code size 9 (0x9) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldfld ""int Program.<>c__DisplayClass2_0.x"" IL_0006: ldc.i4.1 IL_0007: add IL_0008: ret } "); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, n0, n1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true))); diff1.VerifySynthesizedMembers( "Program: {<>c__DisplayClass2_0, <>c}", "Program.<>c__DisplayClass2_0: {x, <N>b__1}", "Program.<>c: {<>9__2_0, <N>b__2_0}"); diff1.VerifyIL("Program.N()", @" { // Code size 53 (0x35) .maxstack 4 .locals init (System.Collections.Generic.IEnumerable<int> V_0) //query IL_0000: nop IL_0001: ldc.i4.2 IL_0002: newarr ""int"" IL_0007: dup IL_0008: ldc.i4.0 IL_0009: ldc.i4.1 IL_000a: stelem.i4 IL_000b: dup IL_000c: ldc.i4.1 IL_000d: ldc.i4.2 IL_000e: stelem.i4 IL_000f: ldsfld ""System.Func<int, int> Program.<>c.<>9__2_0"" IL_0014: dup IL_0015: brtrue.s IL_002e IL_0017: pop IL_0018: ldsfld ""Program.<>c Program.<>c.<>9"" IL_001d: ldftn ""int Program.<>c.<N>b__2_0(int)"" IL_0023: newobj ""System.Func<int, int>..ctor(object, System.IntPtr)"" IL_0028: dup IL_0029: stsfld ""System.Func<int, int> Program.<>c.<>9__2_0"" IL_002e: call ""System.Collections.Generic.IEnumerable<int> System.Linq.Enumerable.Select<int, int>(System.Collections.Generic.IEnumerable<int>, System.Func<int, int>)"" IL_0033: stloc.0 IL_0034: ret } "); diff1.VerifyIL("Program.<>c.<N>b__2_0(int)", @" { // Code size 37 (0x25) .maxstack 3 .locals init (Program.<>c__DisplayClass2_0 V_0) //CS$<>8__locals0 IL_0000: newobj ""Program.<>c__DisplayClass2_0..ctor()"" IL_0005: stloc.0 IL_0006: ldarg.1 IL_0007: ldloc.0 IL_0008: ldflda ""int Program.<>c__DisplayClass2_0.x"" IL_000d: call ""int Program.M(int, out int)"" IL_0012: ldloc.0 IL_0013: ldftn ""int Program.<>c__DisplayClass2_0.<N>b__1()"" IL_0019: newobj ""System.Func<int>..ctor(object, System.IntPtr)"" IL_001e: call ""int Program.M2(System.Func<int>)"" IL_0023: add IL_0024: ret } "); diff1.VerifyIL("Program.<>c__DisplayClass2_0.<N>b__1()", @" { // Code size 9 (0x9) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldfld ""int Program.<>c__DisplayClass2_0.x"" IL_0006: ldc.i4.1 IL_0007: sub IL_0008: ret } "); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, n1, n2, GetSyntaxMapFromMarkers(source1, source0), preserveLocalVariables: true))); diff2.VerifySynthesizedMembers( "Program.<>c__DisplayClass2_0: {x, <N>b__1}", "Program: {<>c__DisplayClass2_0, <>c}", "Program.<>c: {<>9__2_0, <N>b__2_0}"); diff2.VerifyIL("Program.N()", @" { // Code size 53 (0x35) .maxstack 4 .locals init (System.Collections.Generic.IEnumerable<int> V_0) //query IL_0000: nop IL_0001: ldc.i4.2 IL_0002: newarr ""int"" IL_0007: dup IL_0008: ldc.i4.0 IL_0009: ldc.i4.1 IL_000a: stelem.i4 IL_000b: dup IL_000c: ldc.i4.1 IL_000d: ldc.i4.2 IL_000e: stelem.i4 IL_000f: ldsfld ""System.Func<int, int> Program.<>c.<>9__2_0"" IL_0014: dup IL_0015: brtrue.s IL_002e IL_0017: pop IL_0018: ldsfld ""Program.<>c Program.<>c.<>9"" IL_001d: ldftn ""int Program.<>c.<N>b__2_0(int)"" IL_0023: newobj ""System.Func<int, int>..ctor(object, System.IntPtr)"" IL_0028: dup IL_0029: stsfld ""System.Func<int, int> Program.<>c.<>9__2_0"" IL_002e: call ""System.Collections.Generic.IEnumerable<int> System.Linq.Enumerable.Select<int, int>(System.Collections.Generic.IEnumerable<int>, System.Func<int, int>)"" IL_0033: stloc.0 IL_0034: ret } "); diff2.VerifyIL("Program.<>c.<N>b__2_0(int)", @" { // Code size 37 (0x25) .maxstack 3 .locals init (Program.<>c__DisplayClass2_0 V_0) //CS$<>8__locals0 IL_0000: newobj ""Program.<>c__DisplayClass2_0..ctor()"" IL_0005: stloc.0 IL_0006: ldarg.1 IL_0007: ldloc.0 IL_0008: ldflda ""int Program.<>c__DisplayClass2_0.x"" IL_000d: call ""int Program.M(int, out int)"" IL_0012: ldloc.0 IL_0013: ldftn ""int Program.<>c__DisplayClass2_0.<N>b__1()"" IL_0019: newobj ""System.Func<int>..ctor(object, System.IntPtr)"" IL_001e: call ""int Program.M2(System.Func<int>)"" IL_0023: add IL_0024: ret } "); diff2.VerifyIL("Program.<>c__DisplayClass2_0.<N>b__1()", @" { // Code size 9 (0x9) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldfld ""int Program.<>c__DisplayClass2_0.x"" IL_0006: ldc.i4.1 IL_0007: add IL_0008: ret } "); } [Fact] public void OutVar_InSwitchExpression() { var source0 = MarkedSource(@" public class Program { static object G(int i) { return i switch { 0 => 0, _ => 1 }; } static object N(out int x) { x = 1; return null; } }"); var source1 = MarkedSource(@" public class Program { static object G(int i) { return i + N(out var x) switch { 0 => 0, _ => 1 }; } static int N(out int x) { x = 1; return 0; } }"); var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll); var compilation1 = compilation0.WithSource(source1.Tree); var compilation2 = compilation1.WithSource(source0.Tree); var n0 = compilation0.GetMember<MethodSymbol>("Program.G"); var n1 = compilation1.GetMember<MethodSymbol>("Program.G"); var n2 = compilation2.GetMember<MethodSymbol>("Program.G"); var v0 = CompileAndVerify(compilation0); v0.VerifyIL("Program.G(int)", @" { // Code size 33 (0x21) .maxstack 1 .locals init (int V_0, object V_1) IL_0000: nop IL_0001: ldc.i4.1 IL_0002: brtrue.s IL_0005 IL_0004: nop IL_0005: ldarg.0 IL_0006: brfalse.s IL_000a IL_0008: br.s IL_000e IL_000a: ldc.i4.0 IL_000b: stloc.0 IL_000c: br.s IL_0012 IL_000e: ldc.i4.1 IL_000f: stloc.0 IL_0010: br.s IL_0012 IL_0012: ldc.i4.1 IL_0013: brtrue.s IL_0016 IL_0015: nop IL_0016: ldloc.0 IL_0017: box ""int"" IL_001c: stloc.1 IL_001d: br.s IL_001f IL_001f: ldloc.1 IL_0020: ret } "); v0.VerifyIL("Program.N(out int)", @" { // Code size 10 (0xa) .maxstack 2 .locals init (object V_0) IL_0000: nop IL_0001: ldarg.0 IL_0002: ldc.i4.1 IL_0003: stind.i4 IL_0004: ldnull IL_0005: stloc.0 IL_0006: br.s IL_0008 IL_0008: ldloc.0 IL_0009: ret } "); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, n0, n1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true))); diff1.VerifySynthesizedMembers(); diff1.VerifyIL("Program.G(int)", @" { // Code size 52 (0x34) .maxstack 2 .locals init ([int] V_0, [object] V_1, int V_2, //x int V_3, int V_4, int V_5, object V_6) IL_0000: nop IL_0001: ldarg.0 IL_0002: stloc.3 IL_0003: ldloca.s V_2 IL_0005: call ""int Program.N(out int)"" IL_000a: stloc.s V_5 IL_000c: ldc.i4.1 IL_000d: brtrue.s IL_0010 IL_000f: nop IL_0010: ldloc.s V_5 IL_0012: brfalse.s IL_0016 IL_0014: br.s IL_001b IL_0016: ldc.i4.0 IL_0017: stloc.s V_4 IL_0019: br.s IL_0020 IL_001b: ldc.i4.1 IL_001c: stloc.s V_4 IL_001e: br.s IL_0020 IL_0020: ldc.i4.1 IL_0021: brtrue.s IL_0024 IL_0023: nop IL_0024: ldloc.3 IL_0025: ldloc.s V_4 IL_0027: add IL_0028: box ""int"" IL_002d: stloc.s V_6 IL_002f: br.s IL_0031 IL_0031: ldloc.s V_6 IL_0033: ret } "); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, n1, n2, GetSyntaxMapFromMarkers(source1, source0), preserveLocalVariables: true))); diff2.VerifySynthesizedMembers(); diff2.VerifyIL("Program.G(int)", @" { // Code size 38 (0x26) .maxstack 1 .locals init ([int] V_0, [object] V_1, [int] V_2, [int] V_3, [int] V_4, [int] V_5, [object] V_6, int V_7, object V_8) IL_0000: nop IL_0001: ldc.i4.1 IL_0002: brtrue.s IL_0005 IL_0004: nop IL_0005: ldarg.0 IL_0006: brfalse.s IL_000a IL_0008: br.s IL_000f IL_000a: ldc.i4.0 IL_000b: stloc.s V_7 IL_000d: br.s IL_0014 IL_000f: ldc.i4.1 IL_0010: stloc.s V_7 IL_0012: br.s IL_0014 IL_0014: ldc.i4.1 IL_0015: brtrue.s IL_0018 IL_0017: nop IL_0018: ldloc.s V_7 IL_001a: box ""int"" IL_001f: stloc.s V_8 IL_0021: br.s IL_0023 IL_0023: ldloc.s V_8 IL_0025: ret } "); } [Fact] public void AddUsing_AmbiguousCode() { var source0 = MarkedSource(@" using System.Threading; class C { static void E() { var t = new Timer(s => System.Console.WriteLine(s)); } }"); var source1 = MarkedSource(@" using System.Threading; using System.Timers; class C { static void E() { var t = new Timer(s => System.Console.WriteLine(s)); } static void G() { System.Console.WriteLine(new TimersDescriptionAttribute("""")); } }"); var compilation0 = CreateCompilation(source0.Tree, targetFramework: TargetFramework.NetStandard20, options: ComSafeDebugDll); var compilation1 = compilation0.WithSource(source1.Tree); var e0 = compilation0.GetMember<MethodSymbol>("C.E"); var e1 = compilation1.GetMember<MethodSymbol>("C.E"); var g1 = compilation1.GetMember<MethodSymbol>("C.G"); var v0 = CompileAndVerify(compilation0); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); // Pretend there was an update to C.E to ensure we haven't invalidated the test var diffError = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, e0, e1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true))); diffError.EmitResult.Diagnostics.Verify( // (9,21): error CS0104: 'Timer' is an ambiguous reference between 'System.Threading.Timer' and 'System.Timers.Timer' // var t = new Timer(s => System.Console.WriteLine(s)); Diagnostic(ErrorCode.ERR_AmbigContext, "Timer").WithArguments("Timer", "System.Threading.Timer", "System.Timers.Timer").WithLocation(9, 21)); // Semantic errors are reported only for the bodies of members being emitted so we shouldn't see any var diff = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Insert, null, g1))); diff.EmitResult.Diagnostics.Verify(); diff.VerifyIL(@"C.G", @" { // Code size 18 (0x12) .maxstack 1 IL_0000: nop IL_0001: ldstr """" IL_0006: newobj ""System.Timers.TimersDescriptionAttribute..ctor(string)"" IL_000b: call ""void System.Console.WriteLine(object)"" IL_0010: nop IL_0011: ret } "); } [Fact] public void Records_AddWellKnownMember() { var source0 = @" #nullable enable namespace N { record R(int X) { } } "; var source1 = @" #nullable enable namespace N { record R(int X) { protected virtual bool PrintMembers(System.Text.StringBuilder builder) { return true; } } } "; var compilation0 = CreateCompilation(new[] { source0, IsExternalInitTypeDefinition }, options: ComSafeDebugDll); var compilation1 = compilation0.WithSource(new[] { source1, IsExternalInitTypeDefinition }); var printMembers0 = compilation0.GetMember<MethodSymbol>("N.R.PrintMembers"); var printMembers1 = compilation1.GetMember<MethodSymbol>("N.R.PrintMembers"); var v0 = CompileAndVerify(compilation0, verify: Verification.Skipped); using var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); // Verify full metadata contains expected rows. var reader0 = md0.MetadataReader; CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "EmbeddedAttribute", "NullableAttribute", "NullableContextAttribute", "IsExternalInit", "R"); CheckNames(reader0, reader0.GetMethodDefNames(), /* EmbeddedAttribute */".ctor", /* NullableAttribute */ ".ctor", /* NullableContextAttribute */".ctor", /* IsExternalInit */".ctor", /* R: */ ".ctor", "get_EqualityContract", "get_X", "set_X", "ToString", "PrintMembers", "op_Inequality", "op_Equality", "GetHashCode", "Equals", "Equals", "<Clone>$", ".ctor", "Deconstruct"); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, printMembers0, printMembers1))); diff1.VerifySynthesizedMembers( "<global namespace>: {Microsoft}", "Microsoft: {CodeAnalysis}", "Microsoft.CodeAnalysis: {EmbeddedAttribute}", "System.Runtime.CompilerServices: {NullableAttribute, NullableContextAttribute}"); // Verify delta metadata contains expected rows. using var md1 = diff1.GetMetadata(); var reader1 = md1.Reader; var readers = new[] { reader0, reader1 }; EncValidation.VerifyModuleMvid(1, reader0, reader1); CheckNames(readers, reader1.GetTypeDefNames()); CheckNames(readers, reader1.GetMethodDefNames(), "PrintMembers"); CheckEncLog(reader1, Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default), Row(20, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(21, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(22, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(4, TableIndex.TypeSpec, EditAndContinueOperation.Default), Row(3, TableIndex.StandAloneSig, EditAndContinueOperation.Default), Row(10, TableIndex.MethodDef, EditAndContinueOperation.Default), // R.PrintMembers Row(3, TableIndex.Param, EditAndContinueOperation.Default)); CheckEncMap(reader1, Handle(20, TableIndex.TypeRef), Handle(21, TableIndex.TypeRef), Handle(22, TableIndex.TypeRef), Handle(10, TableIndex.MethodDef), Handle(3, TableIndex.Param), Handle(3, TableIndex.StandAloneSig), Handle(4, TableIndex.TypeSpec), Handle(2, TableIndex.AssemblyRef)); } [Fact] public void Records_RemoveWellKnownMember() { var source0 = @" namespace N { record R(int X) { protected virtual bool PrintMembers(System.Text.StringBuilder builder) { return true; } } } "; var source1 = @" namespace N { record R(int X) { } } "; var compilation0 = CreateCompilation(new[] { source0, IsExternalInitTypeDefinition }, options: ComSafeDebugDll); var compilation1 = compilation0.WithSource(new[] { source1, IsExternalInitTypeDefinition }); var method0 = compilation0.GetMember<MethodSymbol>("N.R.PrintMembers"); var method1 = compilation1.GetMember<MethodSymbol>("N.R.PrintMembers"); var v0 = CompileAndVerify(compilation0, verify: Verification.Skipped); using var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, method0, method1))); diff1.VerifySynthesizedMembers( "<global namespace>: {Microsoft}", "Microsoft: {CodeAnalysis}", "Microsoft.CodeAnalysis: {EmbeddedAttribute}", "System.Runtime.CompilerServices: {NullableAttribute, NullableContextAttribute}"); } [Fact] public void TopLevelStatement_Update() { var source0 = @" using System; Console.WriteLine(""Hello""); "; var source1 = @" using System; Console.WriteLine(""Hello World""); "; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugExe); var compilation1 = compilation0.WithSource(source1); var method0 = compilation0.GetMember<MethodSymbol>("Program.<Main>$"); var method1 = compilation1.GetMember<MethodSymbol>("Program.<Main>$"); // Verify full metadata contains expected rows. var bytes0 = compilation0.EmitToArray(); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var reader0 = md0.MetadataReader; CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "Program"); CheckNames(reader0, reader0.GetMethodDefNames(), "<Main>$", ".ctor"); CheckNames(reader0, reader0.GetMemberRefNames(), /*CompilationRelaxationsAttribute.*/".ctor", /*RuntimeCompatibilityAttribute.*/".ctor", /*Object.*/".ctor", /*DebuggableAttribute*/".ctor", /*Console.*/"WriteLine", /*Program.*/".ctor"); var generation0 = EmitBaseline.CreateInitialBaseline( md0, EmptyLocalsProvider); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1))); // Verify delta metadata contains expected rows. using var md1 = diff1.GetMetadata(); var reader1 = md1.Reader; var readers = new[] { reader0, reader1 }; EncValidation.VerifyModuleMvid(1, reader0, reader1); CheckNames(readers, reader1.GetTypeDefNames()); CheckNames(readers, reader1.GetMethodDefNames(), "<Main>$"); CheckNames(readers, reader1.GetMemberRefNames(), /*CompilerGenerated*/".ctor", /*Console.*/"WriteLine"); CheckEncLog(reader1, Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default), Row(7, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(8, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(8, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(9, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(10, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(1, TableIndex.MethodDef, EditAndContinueOperation.Default), // Synthesized Main method Row(1, TableIndex.Param, EditAndContinueOperation.Default)); CheckEncMap(reader1, Handle(8, TableIndex.TypeRef), Handle(9, TableIndex.TypeRef), Handle(10, TableIndex.TypeRef), Handle(1, TableIndex.MethodDef), Handle(1, TableIndex.Param), Handle(7, TableIndex.MemberRef), Handle(8, TableIndex.MemberRef), Handle(2, TableIndex.AssemblyRef)); } [Fact] public void LambdaParameterToDiscard() { var source0 = MarkedSource(@" using System; class C { void M() { var x = new Func<int, int, int>(<N:0>(a, b) => a + b + 1</N:0>); Console.WriteLine(x(1, 2)); } }"); var source1 = MarkedSource(@" using System; class C { void M() { var x = new Func<int, int, int>(<N:0>(_, _) => 10</N:0>); Console.WriteLine(x(1, 2)); } }"); var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll); var compilation1 = compilation0.WithSource(source1.Tree); var method0 = compilation0.GetMember<MethodSymbol>("C.M"); var method1 = compilation1.GetMember<MethodSymbol>("C.M"); var v0 = CompileAndVerify(compilation0, verify: Verification.Skipped); using var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); var diff = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true))); // There should be no diagnostics from rude edits diff.EmitResult.Diagnostics.Verify(); diff.VerifySynthesizedMembers( "C: {<>c}", "C.<>c: {<>9__0_0, <M>b__0_0}"); diff.VerifyIL("C.M", @" { // Code size 48 (0x30) .maxstack 3 .locals init ([unchanged] V_0, System.Func<int, int, int> V_1) //x IL_0000: nop IL_0001: ldsfld ""System.Func<int, int, int> C.<>c.<>9__0_0"" IL_0006: dup IL_0007: brtrue.s IL_0020 IL_0009: pop IL_000a: ldsfld ""C.<>c C.<>c.<>9"" IL_000f: ldftn ""int C.<>c.<M>b__0_0(int, int)"" IL_0015: newobj ""System.Func<int, int, int>..ctor(object, System.IntPtr)"" IL_001a: dup IL_001b: stsfld ""System.Func<int, int, int> C.<>c.<>9__0_0"" IL_0020: stloc.1 IL_0021: ldloc.1 IL_0022: ldc.i4.1 IL_0023: ldc.i4.2 IL_0024: callvirt ""int System.Func<int, int, int>.Invoke(int, int)"" IL_0029: call ""void System.Console.WriteLine(int)"" IL_002e: nop IL_002f: ret }"); diff.VerifyIL("C.<>c.<M>b__0_0(int, int)", @" { // Code size 3 (0x3) .maxstack 1 IL_0000: ldc.i4.s 10 IL_0002: ret }"); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.IO; using System.Linq; using System.Reflection.Metadata; using System.Reflection.Metadata.Ecma335; using Microsoft.CodeAnalysis.CodeGen; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.CSharp.UnitTests; using Microsoft.CodeAnalysis.Emit; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.EditAndContinue.UnitTests { /// <summary> /// Tip: debug EncVariableSlotAllocator.TryGetPreviousClosure or other TryGet methods to figure out missing markers in your test. /// </summary> public class EditAndContinueTests : EditAndContinueTestBase { private static IEnumerable<string> DumpTypeRefs(MetadataReader[] readers) { var currentGenerationReader = readers.Last(); foreach (var typeRefHandle in currentGenerationReader.TypeReferences) { var typeRef = currentGenerationReader.GetTypeReference(typeRefHandle); yield return $"[0x{MetadataTokens.GetToken(typeRef.ResolutionScope):x8}] {readers.GetString(typeRef.Namespace)}.{readers.GetString(typeRef.Name)}"; } } [Fact] public void DeltaHeapsStartWithEmptyItem() { var source0 = @"class C { static string F() { return null; } }"; var source1 = @"class C { static string F() { return ""a""; } }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var method0 = compilation0.GetMember<MethodSymbol>("C.F"); var method1 = compilation1.GetMember<MethodSymbol>("C.F"); var bytes0 = compilation0.EmitToArray(); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var reader0 = md0.MetadataReader; var diff1 = compilation1.EmitDifference( EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider), ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1))); using var md1 = diff1.GetMetadata(); var reader1 = md1.Reader; var s = MetadataTokens.StringHandle(0); Assert.Equal("", reader1.GetString(s)); var b = MetadataTokens.BlobHandle(0); Assert.Equal(0, reader1.GetBlobBytes(b).Length); var us = MetadataTokens.UserStringHandle(0); Assert.Equal("", reader1.GetUserString(us)); } [Fact] public void Delta_AssemblyDefTable() { var source0 = @"public class C { public static void F() { System.Console.WriteLine(1); } }"; var source1 = @"public class C { public static void F() { System.Console.WriteLine(2); } }"; var compilation0 = CreateCompilationWithMscorlib45(source0, options: ComSafeDebugDll); var compilation1 = compilation0.WithSource(source1); var f0 = compilation0.GetMember<MethodSymbol>("C.F"); var f1 = compilation1.GetMember<MethodSymbol>("C.F"); var v0 = CompileAndVerify(compilation0); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, f0, f1, preserveLocalVariables: true))); // AssemblyDef record is not emitted to delta since changes in assembly identity are not allowed: Assert.True(md0.MetadataReader.IsAssembly); Assert.False(diff1.GetMetadata().Reader.IsAssembly); } [Fact] public void SemanticErrors_MethodBody() { var source0 = MarkedSource(@" class C { static void E() { int x = 1; System.Console.WriteLine(x); } static void G() { System.Console.WriteLine(1); } }"); var source1 = MarkedSource(@" class C { static void E() { int x = Unknown(2); System.Console.WriteLine(x); } static void G() { System.Console.WriteLine(2); } }"); var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll); var compilation1 = compilation0.WithSource(source1.Tree); var e0 = compilation0.GetMember<MethodSymbol>("C.E"); var e1 = compilation1.GetMember<MethodSymbol>("C.E"); var g0 = compilation0.GetMember<MethodSymbol>("C.G"); var g1 = compilation1.GetMember<MethodSymbol>("C.G"); var v0 = CompileAndVerify(compilation0); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); // Semantic errors are reported only for the bodies of members being emitted. var diffError = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, e0, e1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true))); diffError.EmitResult.Diagnostics.Verify( // (6,17): error CS0103: The name 'Unknown' does not exist in the current context // int x = Unknown(2); Diagnostic(ErrorCode.ERR_NameNotInContext, "Unknown").WithArguments("Unknown").WithLocation(6, 17)); var diffGood = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, g0, g1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true))); diffGood.EmitResult.Diagnostics.Verify(); diffGood.VerifyIL(@"C.G", @" { // Code size 9 (0x9) .maxstack 1 IL_0000: nop IL_0001: ldc.i4.2 IL_0002: call ""void System.Console.WriteLine(int)"" IL_0007: nop IL_0008: ret } "); } [Fact] public void SemanticErrors_Declaration() { var source0 = MarkedSource(@" class C { static void G() { System.Console.WriteLine(1); } } "); var source1 = MarkedSource(@" class C { static void G() { System.Console.WriteLine(2); } } class Bad : Bad { } "); var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll); var compilation1 = compilation0.WithSource(source1.Tree); var g0 = compilation0.GetMember<MethodSymbol>("C.G"); var g1 = compilation1.GetMember<MethodSymbol>("C.G"); var v0 = CompileAndVerify(compilation0); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); var diff = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, g0, g1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true))); // All declaration errors are reported regardless of what member do we emit. diff.EmitResult.Diagnostics.Verify( // (10,7): error CS0146: Circular base type dependency involving 'Bad' and 'Bad' // class Bad : Bad Diagnostic(ErrorCode.ERR_CircularBase, "Bad").WithArguments("Bad", "Bad").WithLocation(10, 7)); } [Fact] public void ModifyMethod() { var source0 = @"class C { static void Main() { } static string F() { return null; } }"; var source1 = @"class C { static void Main() { } static string F() { return string.Empty; } }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugExe); var compilation1 = compilation0.WithSource(source1); var method0 = compilation0.GetMember<MethodSymbol>("C.F"); // Verify full metadata contains expected rows. var bytes0 = compilation0.EmitToArray(); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var reader0 = md0.MetadataReader; CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "C"); CheckNames(reader0, reader0.GetMethodDefNames(), "Main", "F", ".ctor"); CheckNames(reader0, reader0.GetMemberRefNames(), /*CompilationRelaxationsAttribute.*/".ctor", /*RuntimeCompatibilityAttribute.*/".ctor", /*Object.*/".ctor", /*DebuggableAttribute*/".ctor"); var generation0 = EmitBaseline.CreateInitialBaseline( md0, EmptyLocalsProvider); var method1 = compilation1.GetMember<MethodSymbol>("C.F"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1))); // Verify delta metadata contains expected rows. using var md1 = diff1.GetMetadata(); var reader1 = md1.Reader; var readers = new[] { reader0, reader1 }; EncValidation.VerifyModuleMvid(1, reader0, reader1); CheckNames(readers, reader1.GetTypeDefNames()); CheckNames(readers, reader1.GetMethodDefNames(), "F"); CheckNames(readers, reader1.GetMemberRefNames(), /*String.*/"Empty"); CheckEncLog(reader1, Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default), Row(5, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(6, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(7, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(2, TableIndex.StandAloneSig, EditAndContinueOperation.Default), Row(2, TableIndex.MethodDef, EditAndContinueOperation.Default)); // C.F CheckEncMap(reader1, Handle(6, TableIndex.TypeRef), Handle(7, TableIndex.TypeRef), Handle(2, TableIndex.MethodDef), Handle(5, TableIndex.MemberRef), Handle(2, TableIndex.StandAloneSig), Handle(2, TableIndex.AssemblyRef)); } [Fact] public void ModifyMethod_RenameParameter() { var source0 = @"class C { static string F(int a) { return a.ToString(); } }"; var source1 = @"class C { static string F(int x) { return x.ToString(); } }"; var source2 = @"class C { static string F(int b) { return b.ToString(); } }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var compilation2 = compilation1.WithSource(source2); var method0 = compilation0.GetMember<MethodSymbol>("C.F"); // Verify full metadata contains expected rows. var bytes0 = compilation0.EmitToArray(EmitOptions.Default.WithDebugInformationFormat(DebugInformationFormat.PortablePdb)); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var reader0 = md0.MetadataReader; CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "C"); CheckNames(reader0, reader0.GetMethodDefNames(), "F", ".ctor"); CheckNames(reader0, reader0.GetParameterDefNames(), "a"); var generation0 = EmitBaseline.CreateInitialBaseline( md0, EmptyLocalsProvider); var method1 = compilation1.GetMember<MethodSymbol>("C.F"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1))); // Verify delta metadata contains expected rows. using var md1 = diff1.GetMetadata(); var reader1 = md1.Reader; var readers = new[] { reader0, reader1 }; EncValidation.VerifyModuleMvid(1, reader0, reader1); CheckNames(readers, reader1.GetTypeDefNames()); CheckNames(readers, reader1.GetMethodDefNames(), "F"); CheckNames(readers, reader1.GetParameterDefNames(), "x"); CheckEncLogDefinitions(reader1, Row(2, TableIndex.StandAloneSig, EditAndContinueOperation.Default), Row(1, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(1, TableIndex.Param, EditAndContinueOperation.Default)); CheckEncMapDefinitions(reader1, Handle(1, TableIndex.MethodDef), Handle(1, TableIndex.Param), Handle(2, TableIndex.StandAloneSig)); var method2 = compilation2.GetMember<MethodSymbol>("C.F"); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method1, method2))); // Verify delta metadata contains expected rows. using var md2 = diff2.GetMetadata(); var reader2 = md2.Reader; readers = new[] { reader0, reader1, reader2 }; CheckNames(readers, reader2.GetTypeDefNames()); CheckNames(readers, reader2.GetMethodDefNames(), "F"); CheckNames(readers, reader2.GetMemberRefNames(), "ToString"); CheckNames(readers, reader2.GetParameterDefNames(), "b"); CheckEncLogDefinitions(reader2, Row(3, TableIndex.StandAloneSig, EditAndContinueOperation.Default), Row(1, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(1, TableIndex.Param, EditAndContinueOperation.Default)); CheckEncMapDefinitions(reader2, Handle(1, TableIndex.MethodDef), Handle(1, TableIndex.Param), Handle(3, TableIndex.StandAloneSig)); } [CompilerTrait(CompilerFeature.Tuples)] [Fact] public void ModifyMethod_WithTuples() { var source0 = @"class C { static void Main() { } static (int, int) F() { return (1, 2); } }"; var source1 = @"class C { static void Main() { } static (int, int) F() { return (2, 3); } }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugExe, targetFramework: TargetFramework.NetStandard20); var compilation1 = compilation0.WithSource(source1); var bytes0 = compilation0.EmitToArray(); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var reader0 = md0.MetadataReader; var method0 = compilation0.GetMember<MethodSymbol>("C.F"); var generation0 = EmitBaseline.CreateInitialBaseline( md0, EmptyLocalsProvider); var method1 = compilation1.GetMember<MethodSymbol>("C.F"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1))); // Verify delta metadata contains expected rows. using var md1 = diff1.GetMetadata(); var reader1 = md1.Reader; var readers = new[] { reader0, reader1 }; EncValidation.VerifyModuleMvid(1, reader0, reader1); CheckNames(readers, reader1.GetTypeDefNames()); CheckNames(readers, reader1.GetMethodDefNames(), "F"); CheckNames(readers, reader1.GetMemberRefNames(), /*System.ValueTuple.*/".ctor"); CheckEncLog(reader1, Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default), Row(6, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(7, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(8, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(2, TableIndex.TypeSpec, EditAndContinueOperation.Default), Row(2, TableIndex.StandAloneSig, EditAndContinueOperation.Default), Row(2, TableIndex.MethodDef, EditAndContinueOperation.Default)); // C.F CheckEncMap(reader1, Handle(7, TableIndex.TypeRef), Handle(8, TableIndex.TypeRef), Handle(2, TableIndex.MethodDef), Handle(6, TableIndex.MemberRef), Handle(2, TableIndex.StandAloneSig), Handle(2, TableIndex.TypeSpec), Handle(2, TableIndex.AssemblyRef)); } [Fact] public void ModifyMethod_WithAttributes1() { var source0 = @"class C { static void Main() { } [System.ComponentModel.Description(""The F method"")] static string F() { return null; } }"; var source1 = @"class C { static void Main() { } [System.ComponentModel.Description(""The F method"")] static string F() { return string.Empty; } }"; var source2 = @"[System.ComponentModel.Browsable(false)] class C { static void Main() { } [System.ComponentModel.Description(""The F method""), System.ComponentModel.Category(""Methods"")] static string F() { return string.Empty; } }"; var source3 = @"[System.ComponentModel.Browsable(false)] class C { static void Main() { } [System.ComponentModel.Browsable(false), System.ComponentModel.Description(""The F method""), System.ComponentModel.Category(""Methods"")] static string F() { return string.Empty; } }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugExe, targetFramework: TargetFramework.NetStandard20); var compilation1 = compilation0.WithSource(source1); var compilation2 = compilation1.WithSource(source2); var compilation3 = compilation2.WithSource(source3); var method0 = compilation0.GetMember<MethodSymbol>("C.F"); // Verify full metadata contains expected rows. var bytes0 = compilation0.EmitToArray(); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var reader0 = md0.MetadataReader; CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "C"); CheckNames(reader0, reader0.GetMethodDefNames(), "Main", "F", ".ctor"); CheckNames(reader0, reader0.GetMemberRefNames(), /*CompilationRelaxationsAttribute.*/".ctor", /*RuntimeCompatibilityAttribute.*/".ctor", /*Object.*/".ctor", /*DebuggableAttribute*/".ctor", /*DescriptionAttribute*/".ctor"); Assert.Equal(4, reader0.CustomAttributes.Count); var generation0 = EmitBaseline.CreateInitialBaseline( md0, EmptyLocalsProvider); var method1 = compilation1.GetMember<MethodSymbol>("C.F"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1))); // Verify delta metadata contains expected rows. using var md1 = diff1.GetMetadata(); var reader1 = md1.Reader; var readers = new[] { reader0, reader1 }; EncValidation.VerifyModuleMvid(1, reader0, reader1); CheckNames(readers, reader1.GetTypeDefNames()); CheckNames(readers, reader1.GetMethodDefNames(), "F"); CheckNames(readers, reader1.GetMemberRefNames(), /*DescriptionAttribute*/".ctor", /*String.*/"Empty"); Assert.Equal(1, reader1.CustomAttributes.Count); CheckEncLog(reader1, Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default), Row(6, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(7, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(7, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(8, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(9, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(2, TableIndex.StandAloneSig, EditAndContinueOperation.Default), Row(2, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(4, TableIndex.CustomAttribute, EditAndContinueOperation.Default)); // Row 4, so updating existing CustomAttribute CheckEncMap(reader1, Handle(7, TableIndex.TypeRef), Handle(8, TableIndex.TypeRef), Handle(9, TableIndex.TypeRef), Handle(2, TableIndex.MethodDef), Handle(6, TableIndex.MemberRef), Handle(7, TableIndex.MemberRef), Handle(4, TableIndex.CustomAttribute), Handle(2, TableIndex.StandAloneSig), Handle(2, TableIndex.AssemblyRef)); var method2 = compilation2.GetMember<MethodSymbol>("C.F"); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, compilation1.GetMember("C"), compilation2.GetMember("C")), SemanticEdit.Create(SemanticEditKind.Update, method1, method2))); // Verify delta metadata contains expected rows. using var md2 = diff2.GetMetadata(); var reader2 = md2.Reader; readers = new[] { reader0, reader1, reader2 }; CheckNames(readers, reader2.GetTypeDefNames(), "C"); CheckNames(readers, reader2.GetMethodDefNames(), "F"); CheckNames(readers, reader2.GetMemberRefNames(), /*DescriptionAttribute*/".ctor", /*BrowsableAttribute*/".ctor", /*CategoryAttribute*/".ctor", /*String.*/"Empty"); Assert.Equal(3, reader2.CustomAttributes.Count); CheckEncLog(reader2, Row(3, TableIndex.AssemblyRef, EditAndContinueOperation.Default), Row(8, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(9, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(10, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(11, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(10, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(11, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(12, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(13, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(14, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(3, TableIndex.StandAloneSig, EditAndContinueOperation.Default), Row(2, TableIndex.TypeDef, EditAndContinueOperation.Default), Row(2, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(4, TableIndex.CustomAttribute, EditAndContinueOperation.Default), // Row 4, updating the existing custom attribute Row(5, TableIndex.CustomAttribute, EditAndContinueOperation.Default), // Row 5, adding a new CustomAttribute Row(6, TableIndex.CustomAttribute, EditAndContinueOperation.Default)); // Row 6 adding a new CustomAttribute CheckEncMap(reader2, Handle(10, TableIndex.TypeRef), Handle(11, TableIndex.TypeRef), Handle(12, TableIndex.TypeRef), Handle(13, TableIndex.TypeRef), Handle(14, TableIndex.TypeRef), Handle(2, TableIndex.TypeDef), Handle(2, TableIndex.MethodDef), Handle(8, TableIndex.MemberRef), Handle(9, TableIndex.MemberRef), Handle(10, TableIndex.MemberRef), Handle(11, TableIndex.MemberRef), Handle(4, TableIndex.CustomAttribute), Handle(5, TableIndex.CustomAttribute), Handle(6, TableIndex.CustomAttribute), Handle(3, TableIndex.StandAloneSig), Handle(3, TableIndex.AssemblyRef)); var method3 = compilation3.GetMember<MethodSymbol>("C.F"); var diff3 = compilation3.EmitDifference( diff2.NextGeneration, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method2, method3))); // Verify delta metadata contains expected rows. using var md3 = diff3.GetMetadata(); var reader3 = md3.Reader; readers = new[] { reader0, reader1, reader2, reader3 }; CheckNames(readers, reader3.GetTypeDefNames()); CheckNames(readers, reader3.GetMethodDefNames(), "F"); CheckNames(readers, reader3.GetMemberRefNames(), /*BrowsableAttribute*/".ctor", /*DescriptionAttribute*/".ctor", /*CategoryAttribute*/".ctor", /*String.*/"Empty"); CheckEncLog(reader3, Row(4, TableIndex.AssemblyRef, EditAndContinueOperation.Default), Row(12, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(13, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(14, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(15, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(15, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(16, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(17, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(18, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(19, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(4, TableIndex.StandAloneSig, EditAndContinueOperation.Default), Row(2, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(4, TableIndex.CustomAttribute, EditAndContinueOperation.Default), // Row 4, updating the existing custom attribute Row(5, TableIndex.CustomAttribute, EditAndContinueOperation.Default), // Row 5, updating a row that was new in Generation 2 Row(7, TableIndex.CustomAttribute, EditAndContinueOperation.Default)); // Row 7, adding a new CustomAttribute, and skipping row 6 which is not for the method being emitted CheckEncMap(reader3, Handle(15, TableIndex.TypeRef), Handle(16, TableIndex.TypeRef), Handle(17, TableIndex.TypeRef), Handle(18, TableIndex.TypeRef), Handle(19, TableIndex.TypeRef), Handle(2, TableIndex.MethodDef), Handle(12, TableIndex.MemberRef), Handle(13, TableIndex.MemberRef), Handle(14, TableIndex.MemberRef), Handle(15, TableIndex.MemberRef), Handle(4, TableIndex.CustomAttribute), Handle(5, TableIndex.CustomAttribute), Handle(7, TableIndex.CustomAttribute), Handle(4, TableIndex.StandAloneSig), Handle(4, TableIndex.AssemblyRef)); } [Fact] public void ModifyMethod_WithAttributes2() { var source0 = @"[System.ComponentModel.Browsable(false)] class C { static void Main() { } [System.ComponentModel.Description(""The F method"")] static string F() { return null; } } [System.ComponentModel.Browsable(false)] class D { [System.ComponentModel.Description(""A"")] static string A() { return null; } } "; var source1 = @" [System.ComponentModel.Browsable(false)] class C { static void Main() { } [System.ComponentModel.Description(""The F method""), System.ComponentModel.Browsable(false), System.ComponentModel.Category(""Methods"")] static string F() { return null; } } [System.ComponentModel.Browsable(false)] class D { [System.ComponentModel.Description(""A""), System.ComponentModel.Category(""Methods"")] static string A() { return null; } } "; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugExe, targetFramework: TargetFramework.NetStandard20); var compilation1 = compilation0.WithSource(source1); var method0_1 = compilation0.GetMember<MethodSymbol>("C.F"); var method0_2 = compilation0.GetMember<MethodSymbol>("D.A"); // Verify full metadata contains expected rows. var bytes0 = compilation0.EmitToArray(); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var reader0 = md0.MetadataReader; CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "C", "D"); CheckNames(reader0, reader0.GetMethodDefNames(), "Main", "F", ".ctor", "A", ".ctor"); CheckNames(reader0, reader0.GetMemberRefNames(), /*CompilationRelaxationsAttribute.*/".ctor", /*RuntimeCompatibilityAttribute.*/".ctor", /*Object.*/".ctor", /*DebuggableAttribute*/".ctor", /*DescriptionAttribute*/".ctor", /*BrowsableAttribute*/".ctor"); CheckAttributes(reader0, new CustomAttributeRow(Handle(1, TableIndex.Assembly), Handle(1, TableIndex.MemberRef)), new CustomAttributeRow(Handle(1, TableIndex.Assembly), Handle(2, TableIndex.MemberRef)), new CustomAttributeRow(Handle(1, TableIndex.Assembly), Handle(3, TableIndex.MemberRef)), new CustomAttributeRow(Handle(2, TableIndex.MethodDef), Handle(5, TableIndex.MemberRef)), new CustomAttributeRow(Handle(2, TableIndex.TypeDef), Handle(4, TableIndex.MemberRef)), new CustomAttributeRow(Handle(3, TableIndex.TypeDef), Handle(4, TableIndex.MemberRef)), new CustomAttributeRow(Handle(4, TableIndex.MethodDef), Handle(5, TableIndex.MemberRef))); var generation0 = EmitBaseline.CreateInitialBaseline( md0, EmptyLocalsProvider); var method1_1 = compilation1.GetMember<MethodSymbol>("C.F"); var method1_2 = compilation1.GetMember<MethodSymbol>("D.A"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, method0_1, method1_1), SemanticEdit.Create(SemanticEditKind.Update, method0_2, method1_2))); // Verify delta metadata contains expected rows. using var md1 = diff1.GetMetadata(); var reader1 = md1.Reader; var readers = new[] { reader0, reader1 }; EncValidation.VerifyModuleMvid(1, reader0, reader1); CheckNames(readers, reader1.GetTypeDefNames()); CheckNames(readers, reader1.GetMethodDefNames(), "F", "A"); CheckNames(readers, reader1.GetMemberRefNames(), /*BrowsableAttribute*/".ctor", /*CategoryAttribute*/".ctor", /*DescriptionAttribute*/".ctor"); CheckAttributes(reader1, new CustomAttributeRow(Handle(2, TableIndex.MethodDef), Handle(8, TableIndex.MemberRef)), new CustomAttributeRow(Handle(2, TableIndex.MethodDef), Handle(7, TableIndex.MemberRef)), new CustomAttributeRow(Handle(2, TableIndex.MethodDef), Handle(9, TableIndex.MemberRef)), new CustomAttributeRow(Handle(4, TableIndex.MethodDef), Handle(8, TableIndex.MemberRef)), new CustomAttributeRow(Handle(4, TableIndex.MethodDef), Handle(9, TableIndex.MemberRef))); CheckEncLog(reader1, Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default), Row(7, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(8, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(9, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(8, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(9, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(10, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(11, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(2, TableIndex.StandAloneSig, EditAndContinueOperation.Default), Row(2, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(4, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(4, TableIndex.CustomAttribute, EditAndContinueOperation.Default), // update existing row Row(8, TableIndex.CustomAttribute, EditAndContinueOperation.Default), // add new row Row(9, TableIndex.CustomAttribute, EditAndContinueOperation.Default), // add new row Row(7, TableIndex.CustomAttribute, EditAndContinueOperation.Default), // update existing row Row(10, TableIndex.CustomAttribute, EditAndContinueOperation.Default)); // add new row CheckEncMap(reader1, Handle(8, TableIndex.TypeRef), Handle(9, TableIndex.TypeRef), Handle(10, TableIndex.TypeRef), Handle(11, TableIndex.TypeRef), Handle(2, TableIndex.MethodDef), Handle(4, TableIndex.MethodDef), Handle(7, TableIndex.MemberRef), Handle(8, TableIndex.MemberRef), Handle(9, TableIndex.MemberRef), Handle(4, TableIndex.CustomAttribute), Handle(7, TableIndex.CustomAttribute), Handle(8, TableIndex.CustomAttribute), Handle(9, TableIndex.CustomAttribute), Handle(10, TableIndex.CustomAttribute), Handle(2, TableIndex.StandAloneSig), Handle(2, TableIndex.AssemblyRef)); } [Fact] public void ModifyMethod_DeleteAttributes1() { var source0 = @"class C { static void Main() { } [System.ComponentModel.Description(""The F method"")] static string F() { return null; } }"; var source1 = @"class C { static void Main() { } static string F() { return string.Empty; } }"; var source2 = @"class C { static void Main() { } [System.ComponentModel.Description(""The F method"")] static string F() { return string.Empty; } }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugExe, targetFramework: TargetFramework.NetStandard20); var compilation1 = compilation0.WithSource(source1); var compilation2 = compilation1.WithSource(source2); var method0 = compilation0.GetMember<MethodSymbol>("C.F"); // Verify full metadata contains expected rows. var bytes0 = compilation0.EmitToArray(); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var reader0 = md0.MetadataReader; CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "C"); CheckNames(reader0, reader0.GetMethodDefNames(), "Main", "F", ".ctor"); CheckNames(reader0, reader0.GetMemberRefNames(), /*CompilationRelaxationsAttribute.*/".ctor", /*RuntimeCompatibilityAttribute.*/".ctor", /*Object.*/".ctor", /*DebuggableAttribute*/".ctor", /*DescriptionAttribute*/".ctor"); CheckAttributes(reader0, new CustomAttributeRow(Handle(1, TableIndex.Assembly), Handle(1, TableIndex.MemberRef)), new CustomAttributeRow(Handle(1, TableIndex.Assembly), Handle(2, TableIndex.MemberRef)), new CustomAttributeRow(Handle(1, TableIndex.Assembly), Handle(3, TableIndex.MemberRef)), new CustomAttributeRow(Handle(2, TableIndex.MethodDef), Handle(4, TableIndex.MemberRef))); var generation0 = EmitBaseline.CreateInitialBaseline( md0, EmptyLocalsProvider); var method1 = compilation1.GetMember<MethodSymbol>("C.F"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1))); // Verify delta metadata contains expected rows. using var md1 = diff1.GetMetadata(); var reader1 = md1.Reader; var readers = new[] { reader0, reader1 }; EncValidation.VerifyModuleMvid(1, reader0, reader1); CheckNames(readers, reader1.GetTypeDefNames()); CheckNames(readers, reader1.GetMethodDefNames(), "F"); CheckNames(readers, reader1.GetMemberRefNames(), /*String.*/"Empty"); CheckAttributes(reader1, new CustomAttributeRow(Handle(0, TableIndex.MethodDef), Handle(0, TableIndex.MemberRef))); // Parent row id is 0, signifying a delete CheckEncLog(reader1, Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default), Row(6, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(7, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(8, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(2, TableIndex.StandAloneSig, EditAndContinueOperation.Default), Row(2, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(4, TableIndex.CustomAttribute, EditAndContinueOperation.Default)); // Row 4, so updating existing CustomAttribute CheckEncMap(reader1, Handle(7, TableIndex.TypeRef), Handle(8, TableIndex.TypeRef), Handle(2, TableIndex.MethodDef), Handle(6, TableIndex.MemberRef), Handle(4, TableIndex.CustomAttribute), Handle(2, TableIndex.StandAloneSig), Handle(2, TableIndex.AssemblyRef)); var method2 = compilation2.GetMember<MethodSymbol>("C.F"); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method1, method2))); // Verify delta metadata contains expected rows. using var md2 = diff2.GetMetadata(); var reader2 = md2.Reader; readers = new[] { reader0, reader1, reader2 }; EncValidation.VerifyModuleMvid(2, reader1, reader2); CheckNames(readers, reader2.GetTypeDefNames()); CheckNames(readers, reader2.GetMethodDefNames(), "F"); CheckNames(readers, reader2.GetMemberRefNames(), /*DescriptionAttribute*/".ctor", /*String.*/"Empty"); CheckAttributes(reader2, new CustomAttributeRow(Handle(2, TableIndex.MethodDef), Handle(7, TableIndex.MemberRef))); CheckEncLog(reader2, Row(3, TableIndex.AssemblyRef, EditAndContinueOperation.Default), Row(7, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(8, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(9, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(10, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(11, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(3, TableIndex.StandAloneSig, EditAndContinueOperation.Default), Row(2, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(4, TableIndex.CustomAttribute, EditAndContinueOperation.Default)); // Row 4, updating the original row back to a real one CheckEncMap(reader2, Handle(9, TableIndex.TypeRef), Handle(10, TableIndex.TypeRef), Handle(11, TableIndex.TypeRef), Handle(2, TableIndex.MethodDef), Handle(7, TableIndex.MemberRef), Handle(8, TableIndex.MemberRef), Handle(4, TableIndex.CustomAttribute), Handle(3, TableIndex.StandAloneSig), Handle(3, TableIndex.AssemblyRef)); } [Fact] public void ModifyMethod_DeleteAttributes2() { var source0 = @"class C { static void Main() { } static string F() { return null; } }"; var source1 = @"class C { static void Main() { } [System.ComponentModel.Description(""The F method"")] static string F() { return string.Empty; } }"; var source2 = source0; // Remove the attribute we just added var source3 = source1; // Add the attribute back again var compilation0 = CreateCompilation(source0, options: TestOptions.DebugExe, targetFramework: TargetFramework.NetStandard20); var compilation1 = compilation0.WithSource(source1); var compilation2 = compilation1.WithSource(source2); var compilation3 = compilation1.WithSource(source3); var method0 = compilation0.GetMember<MethodSymbol>("C.F"); // Verify full metadata contains expected rows. var bytes0 = compilation0.EmitToArray(); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var reader0 = md0.MetadataReader; CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "C"); CheckNames(reader0, reader0.GetMethodDefNames(), "Main", "F", ".ctor"); CheckNames(reader0, reader0.GetMemberRefNames(), /*CompilationRelaxationsAttribute.*/".ctor", /*RuntimeCompatibilityAttribute.*/".ctor", /*Object.*/".ctor", /*DebuggableAttribute*/".ctor"); CheckAttributes(reader0, new CustomAttributeRow(Handle(1, TableIndex.Assembly), Handle(1, TableIndex.MemberRef)), new CustomAttributeRow(Handle(1, TableIndex.Assembly), Handle(2, TableIndex.MemberRef)), new CustomAttributeRow(Handle(1, TableIndex.Assembly), Handle(3, TableIndex.MemberRef))); var generation0 = EmitBaseline.CreateInitialBaseline( md0, EmptyLocalsProvider); var method1 = compilation1.GetMember<MethodSymbol>("C.F"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1))); // Verify delta metadata contains expected rows. using var md1 = diff1.GetMetadata(); var reader1 = md1.Reader; var readers = new[] { reader0, reader1 }; EncValidation.VerifyModuleMvid(1, reader0, reader1); CheckNames(readers, reader1.GetTypeDefNames()); CheckNames(readers, reader1.GetMethodDefNames(), "F"); CheckNames(readers, reader1.GetMemberRefNames(), /*DescriptionAttribute*/".ctor", /*String.*/"Empty"); CheckAttributes(reader1, new CustomAttributeRow(Handle(2, TableIndex.MethodDef), Handle(5, TableIndex.MemberRef))); CheckEncLog(reader1, Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default), Row(5, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(6, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(6, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(7, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(8, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(2, TableIndex.StandAloneSig, EditAndContinueOperation.Default), Row(2, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(4, TableIndex.CustomAttribute, EditAndContinueOperation.Default)); // Row 4, so adding a new CustomAttribute CheckEncMap(reader1, Handle(6, TableIndex.TypeRef), Handle(7, TableIndex.TypeRef), Handle(8, TableIndex.TypeRef), Handle(2, TableIndex.MethodDef), Handle(5, TableIndex.MemberRef), Handle(6, TableIndex.MemberRef), Handle(4, TableIndex.CustomAttribute), Handle(2, TableIndex.StandAloneSig), Handle(2, TableIndex.AssemblyRef)); var method2 = compilation2.GetMember<MethodSymbol>("C.F"); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, method1, method2))); // Verify delta metadata contains expected rows. using var md2 = diff2.GetMetadata(); var reader2 = md2.Reader; readers = new[] { reader0, reader1, reader2 }; CheckNames(readers, reader2.GetTypeDefNames()); CheckNames(readers, reader2.GetMethodDefNames(), "F"); CheckNames(readers, reader2.GetMemberRefNames()); CheckAttributes(reader2, new CustomAttributeRow(Handle(0, TableIndex.MethodDef), Handle(0, TableIndex.MemberRef))); // 0, delete CheckEncLog(reader2, Row(3, TableIndex.AssemblyRef, EditAndContinueOperation.Default), Row(9, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(3, TableIndex.StandAloneSig, EditAndContinueOperation.Default), Row(2, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(4, TableIndex.CustomAttribute, EditAndContinueOperation.Default)); // Row 4, so updating existing CustomAttribute CheckEncMap(reader2, Handle(9, TableIndex.TypeRef), Handle(2, TableIndex.MethodDef), Handle(4, TableIndex.CustomAttribute), Handle(3, TableIndex.StandAloneSig), Handle(3, TableIndex.AssemblyRef)); var method3 = compilation3.GetMember<MethodSymbol>("C.F"); var diff3 = compilation3.EmitDifference( diff2.NextGeneration, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, method2, method3))); // Verify delta metadata contains expected rows. using var md3 = diff3.GetMetadata(); var reader3 = md3.Reader; readers = new[] { reader0, reader1, reader2, reader3 }; CheckNames(readers, reader3.GetTypeDefNames()); CheckNames(readers, reader3.GetMethodDefNames(), "F"); CheckNames(readers, reader3.GetMemberRefNames(), /*DescriptionAttribute*/".ctor", /*String.*/"Empty"); CheckAttributes(reader3, new CustomAttributeRow(Handle(2, TableIndex.MethodDef), Handle(7, TableIndex.MemberRef))); CheckEncLog(reader3, Row(4, TableIndex.AssemblyRef, EditAndContinueOperation.Default), Row(7, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(8, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(10, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(11, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(12, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(4, TableIndex.StandAloneSig, EditAndContinueOperation.Default), Row(2, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(4, TableIndex.CustomAttribute, EditAndContinueOperation.Default)); // Row 4, update the previously deleted row CheckEncMap(reader3, Handle(10, TableIndex.TypeRef), Handle(11, TableIndex.TypeRef), Handle(12, TableIndex.TypeRef), Handle(2, TableIndex.MethodDef), Handle(7, TableIndex.MemberRef), Handle(8, TableIndex.MemberRef), Handle(4, TableIndex.CustomAttribute), Handle(4, TableIndex.StandAloneSig), Handle(4, TableIndex.AssemblyRef)); } [WorkItem(962219, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/962219")] [Fact] public void PartialMethod() { var source = @"partial class C { static partial void M1(); static partial void M2(); static partial void M3(); static partial void M1() { } static partial void M2() { } }"; var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source); var bytes0 = compilation0.EmitToArray(); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var reader0 = md0.MetadataReader; CheckNames(reader0, reader0.GetMethodDefNames(), "M1", "M2", ".ctor"); var method0 = compilation0.GetMember<MethodSymbol>("C.M2").PartialImplementationPart; var method1 = compilation1.GetMember<MethodSymbol>("C.M2").PartialImplementationPart; var generation0 = EmitBaseline.CreateInitialBaseline( md0, EmptyLocalsProvider); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1))); var methods = diff1.TestData.GetMethodsByName(); Assert.Equal(1, methods.Count); Assert.True(methods.ContainsKey("C.M2()")); using var md1 = diff1.GetMetadata(); var reader1 = md1.Reader; var readers = new[] { reader0, reader1 }; EncValidation.VerifyModuleMvid(1, reader0, reader1); CheckNames(readers, reader1.GetMethodDefNames(), "M2"); CheckEncLog(reader1, Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default), Row(6, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(2, TableIndex.MethodDef, EditAndContinueOperation.Default)); CheckEncMap(reader1, Handle(6, TableIndex.TypeRef), Handle(2, TableIndex.MethodDef), Handle(2, TableIndex.AssemblyRef)); } [Fact] public void Method_WithAttributes_Add() { var source0 = @"class C { static void Main() { } }"; var source1 = @"class C { static void Main() { } [System.ComponentModel.Description(""The F method"")] static string F() { return string.Empty; } }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugExe, targetFramework: TargetFramework.NetStandard20); var compilation1 = compilation0.WithSource(source1); // Verify full metadata contains expected rows. var bytes0 = compilation0.EmitToArray(); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var reader0 = md0.MetadataReader; CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "C"); CheckNames(reader0, reader0.GetMethodDefNames(), "Main", ".ctor"); CheckNames(reader0, reader0.GetMemberRefNames(), /*CompilationRelaxationsAttribute.*/".ctor", /*RuntimeCompatibilityAttribute.*/".ctor", /*Object.*/".ctor", /*DebuggableAttribute*/".ctor"); Assert.Equal(3, reader0.CustomAttributes.Count); var generation0 = EmitBaseline.CreateInitialBaseline( md0, EmptyLocalsProvider); var method1 = compilation1.GetMember<MethodSymbol>("C.F"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Insert, null, method1))); // Verify delta metadata contains expected rows. using var md1 = diff1.GetMetadata(); var reader1 = md1.Reader; var readers = new[] { reader0, reader1 }; EncValidation.VerifyModuleMvid(1, reader0, reader1); CheckNames(readers, reader1.GetTypeDefNames()); CheckNames(readers, reader1.GetMethodDefNames(), "F"); CheckNames(readers, reader1.GetMemberRefNames(), /*DescriptionAttribute*/".ctor", /*String.*/"Empty"); Assert.Equal(1, reader1.CustomAttributes.Count); CheckEncLog(reader1, Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default), Row(5, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(6, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(6, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(7, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(8, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(1, TableIndex.StandAloneSig, EditAndContinueOperation.Default), Row(2, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(3, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(4, TableIndex.CustomAttribute, EditAndContinueOperation.Default)); // Row 4, a new attribute CheckEncMap(reader1, Handle(6, TableIndex.TypeRef), Handle(7, TableIndex.TypeRef), Handle(8, TableIndex.TypeRef), Handle(3, TableIndex.MethodDef), Handle(5, TableIndex.MemberRef), Handle(6, TableIndex.MemberRef), Handle(4, TableIndex.CustomAttribute), Handle(1, TableIndex.StandAloneSig), Handle(2, TableIndex.AssemblyRef)); } [Fact] public void ModifyMethod_ParameterAttributes() { var source0 = @"class C { static void Main() { } static string F(string input, int a) { return input; } }"; var source1 = @"class C { static void Main() { } static string F([System.ComponentModel.Description(""input"")]string input, int a) { return input; } static void G(string input) { } }"; var source2 = @"class C { static void Main() { } static string F([System.ComponentModel.Description(""input"")]string input, int a) { return input; } static void G([System.ComponentModel.Description(""input"")]string input) { } }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugExe, targetFramework: TargetFramework.NetStandard20); var compilation1 = compilation0.WithSource(source1); var compilation2 = compilation1.WithSource(source2); var methodF0 = compilation0.GetMember<MethodSymbol>("C.F"); var methodF1 = compilation1.GetMember<MethodSymbol>("C.F"); var methodG1 = compilation1.GetMember<MethodSymbol>("C.G"); var methodG2 = compilation2.GetMember<MethodSymbol>("C.G"); // Verify full metadata contains expected rows. var bytes0 = compilation0.EmitToArray(); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var reader0 = md0.MetadataReader; CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "C"); CheckNames(reader0, reader0.GetMethodDefNames(), "Main", "F", ".ctor"); CheckNames(reader0, reader0.GetMemberRefNames(), /*CompilationRelaxationsAttribute.*/".ctor", /*RuntimeCompatibilityAttribute.*/".ctor", /*Object.*/".ctor", /*DebuggableAttribute*/".ctor"); CheckNames(reader0, reader0.GetParameterDefNames(), "input", "a"); CheckAttributes(reader0, new CustomAttributeRow(Handle(1, TableIndex.Assembly), Handle(1, TableIndex.MemberRef)), new CustomAttributeRow(Handle(1, TableIndex.Assembly), Handle(2, TableIndex.MemberRef)), new CustomAttributeRow(Handle(1, TableIndex.Assembly), Handle(3, TableIndex.MemberRef))); var generation0 = EmitBaseline.CreateInitialBaseline( md0, EmptyLocalsProvider); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, methodF0, methodF1), SemanticEdit.Create(SemanticEditKind.Insert, null, methodG1))); // Verify delta metadata contains expected rows. using var md1 = diff1.GetMetadata(); var reader1 = md1.Reader; var readers = new[] { reader0, reader1 }; EncValidation.VerifyModuleMvid(1, reader0, reader1); CheckNames(readers, reader1.GetTypeDefNames()); CheckNames(readers, reader1.GetMethodDefNames(), "F", "G"); CheckNames(readers, reader1.GetMemberRefNames(), /*DescriptionAttribute*/".ctor"); CheckNames(readers, reader1.GetParameterDefNames(), "input", "a", "input"); CheckAttributes(reader1, new CustomAttributeRow(Handle(1, TableIndex.Param), Handle(5, TableIndex.MemberRef))); CheckEncLog(reader1, Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default), Row(5, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(6, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(7, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(2, TableIndex.StandAloneSig, EditAndContinueOperation.Default), Row(2, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(2, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(4, TableIndex.MethodDef, EditAndContinueOperation.Default), // New method, G Row(1, TableIndex.Param, EditAndContinueOperation.Default), // Update existing param Row(2, TableIndex.Param, EditAndContinueOperation.Default), // Update existing param Row(4, TableIndex.MethodDef, EditAndContinueOperation.AddParameter), // New param on method, G Row(3, TableIndex.Param, EditAndContinueOperation.Default), // Support for the above Row(4, TableIndex.CustomAttribute, EditAndContinueOperation.Default)); CheckEncMap(reader1, Handle(6, TableIndex.TypeRef), Handle(7, TableIndex.TypeRef), Handle(2, TableIndex.MethodDef), Handle(4, TableIndex.MethodDef), Handle(1, TableIndex.Param), Handle(2, TableIndex.Param), Handle(3, TableIndex.Param), Handle(5, TableIndex.MemberRef), Handle(4, TableIndex.CustomAttribute), Handle(2, TableIndex.StandAloneSig), Handle(2, TableIndex.AssemblyRef)); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, methodG1, methodG2))); using var md2 = diff2.GetMetadata(); var reader2 = md2.Reader; readers = new[] { reader0, reader1, reader2 }; EncValidation.VerifyModuleMvid(2, reader1, reader2); CheckNames(readers, reader2.GetTypeDefNames()); CheckNames(readers, reader2.GetMethodDefNames(), "G"); CheckNames(readers, reader2.GetMemberRefNames(), /*DescriptionAttribute*/".ctor"); CheckNames(readers, reader2.GetParameterDefNames(), "input"); CheckAttributes(reader2, new CustomAttributeRow(Handle(3, TableIndex.Param), Handle(6, TableIndex.MemberRef))); CheckEncLog(reader2, Row(3, TableIndex.AssemblyRef, EditAndContinueOperation.Default), Row(6, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(8, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(9, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(4, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(3, TableIndex.Param, EditAndContinueOperation.Default), // Update existing param, from the first delta Row(5, TableIndex.CustomAttribute, EditAndContinueOperation.Default)); CheckEncMap(reader2, Handle(8, TableIndex.TypeRef), Handle(9, TableIndex.TypeRef), Handle(4, TableIndex.MethodDef), Handle(3, TableIndex.Param), Handle(6, TableIndex.MemberRef), Handle(5, TableIndex.CustomAttribute), Handle(3, TableIndex.AssemblyRef)); } [Fact] public void ModifyDelegateInvokeMethod_AddAttributes() { var source0 = @" class A : System.Attribute { } delegate void D(int x); "; var source1 = @" class A : System.Attribute { } delegate void D([A]int x); "; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll, targetFramework: TargetFramework.NetStandard20); var compilation1 = compilation0.WithSource(source1); var invoke0 = compilation0.GetMember<MethodSymbol>("D.Invoke"); var beginInvoke0 = compilation0.GetMember<MethodSymbol>("D.BeginInvoke"); var invoke1 = compilation1.GetMember<MethodSymbol>("D.Invoke"); var beginInvoke1 = compilation1.GetMember<MethodSymbol>("D.BeginInvoke"); // Verify full metadata contains expected rows. var bytes0 = compilation0.EmitToArray(); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var reader0 = md0.MetadataReader; var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, invoke0, invoke1), SemanticEdit.Create(SemanticEditKind.Update, beginInvoke0, beginInvoke1))); // Verify delta metadata contains expected rows. using var md1 = diff1.GetMetadata(); var reader1 = md1.Reader; var readers = new[] { reader0, reader1 }; CheckNames(readers, reader1.GetMethodDefNames(), "Invoke", "BeginInvoke"); CheckNames(readers, reader1.GetParameterDefNames(), "x", "x", "callback", "object"); CheckAttributes(reader1, new CustomAttributeRow(Handle(3, TableIndex.Param), Handle(1, TableIndex.MethodDef)), new CustomAttributeRow(Handle(4, TableIndex.Param), Handle(1, TableIndex.MethodDef))); CheckEncLog(reader1, Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default), Row(10, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(11, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(12, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(13, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(3, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(4, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(3, TableIndex.Param, EditAndContinueOperation.Default), // Updating existing parameter defs Row(4, TableIndex.Param, EditAndContinueOperation.Default), Row(5, TableIndex.Param, EditAndContinueOperation.Default), Row(6, TableIndex.Param, EditAndContinueOperation.Default), Row(4, TableIndex.CustomAttribute, EditAndContinueOperation.Default), // Adding new custom attribute rows Row(5, TableIndex.CustomAttribute, EditAndContinueOperation.Default)); CheckEncMap(reader1, Handle(10, TableIndex.TypeRef), Handle(11, TableIndex.TypeRef), Handle(12, TableIndex.TypeRef), Handle(13, TableIndex.TypeRef), Handle(3, TableIndex.MethodDef), Handle(4, TableIndex.MethodDef), Handle(3, TableIndex.Param), Handle(4, TableIndex.Param), Handle(5, TableIndex.Param), Handle(6, TableIndex.Param), Handle(4, TableIndex.CustomAttribute), Handle(5, TableIndex.CustomAttribute), Handle(2, TableIndex.AssemblyRef)); } /// <summary> /// Add a method that requires entries in the ParameterDefs table. /// Specifically, normal parameters or return types with attributes. /// Add the method in the first edit, then modify the method in the second. /// </summary> [Fact] public void Method_WithParameterAttributes_AddThenUpdate() { var source0 = @"class A : System.Attribute { } class C { }"; var source1 = @"class A : System.Attribute { } class C { [return:A]static object F(int arg = 1) => arg; }"; var source2 = @"class A : System.Attribute { } class C { [return:A]static object F(int arg = 1) => null; }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var compilation2 = compilation0.WithSource(source2); var f1 = compilation1.GetMember<MethodSymbol>("C.F"); var f2 = compilation2.GetMember<MethodSymbol>("C.F"); var bytes0 = compilation0.EmitToArray(); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var reader0 = md0.MetadataReader; CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "A", "C"); CheckNames(reader0, reader0.GetMethodDefNames(), ".ctor", ".ctor"); var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider); // gen 1 var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Insert, null, f1))); using var md1 = diff1.GetMetadata(); var reader1 = md1.Reader; var readers = new List<MetadataReader> { reader0, reader1 }; EncValidation.VerifyModuleMvid(1, reader0, reader1); CheckNames(readers, reader1.GetTypeDefNames()); CheckNames(readers, reader1.GetMethodDefNames(), "F"); CheckNames(readers, reader1.GetParameterDefNames(), "", "arg"); CheckNames(readers, diff1.EmitResult.ChangedTypes, "C"); CheckNames(readers, diff1.EmitResult.UpdatedMethods); CheckEncLogDefinitions(reader1, Row(3, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(3, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(3, TableIndex.MethodDef, EditAndContinueOperation.AddParameter), Row(1, TableIndex.Param, EditAndContinueOperation.Default), Row(3, TableIndex.MethodDef, EditAndContinueOperation.AddParameter), Row(2, TableIndex.Param, EditAndContinueOperation.Default), Row(1, TableIndex.Constant, EditAndContinueOperation.Default), Row(4, TableIndex.CustomAttribute, EditAndContinueOperation.Default)); CheckEncMapDefinitions(reader1, Handle(3, TableIndex.MethodDef), Handle(1, TableIndex.Param), Handle(2, TableIndex.Param), Handle(1, TableIndex.Constant), Handle(4, TableIndex.CustomAttribute)); // gen 2 var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, f1, f2))); using var md2 = diff2.GetMetadata(); var reader2 = md2.Reader; readers.Add(reader2); EncValidation.VerifyModuleMvid(2, reader1, reader2); CheckNames(readers, reader2.GetTypeDefNames()); CheckNames(readers, reader2.GetMethodDefNames(), "F"); CheckNames(readers, reader2.GetParameterDefNames(), "", "arg"); CheckNames(readers, diff2.EmitResult.ChangedTypes, "C"); CheckNames(readers, diff2.EmitResult.UpdatedMethods, "F"); CheckEncLogDefinitions(reader2, Row(3, TableIndex.MethodDef, EditAndContinueOperation.Default), // C.F2 Row(1, TableIndex.Param, EditAndContinueOperation.Default), Row(2, TableIndex.Param, EditAndContinueOperation.Default), Row(2, TableIndex.Constant, EditAndContinueOperation.Default), Row(4, TableIndex.CustomAttribute, EditAndContinueOperation.Default)); CheckEncMapDefinitions(reader2, Handle(3, TableIndex.MethodDef), Handle(1, TableIndex.Param), Handle(2, TableIndex.Param), Handle(2, TableIndex.Constant), Handle(4, TableIndex.CustomAttribute)); } [Fact] public void Method_WithEmbeddedAttributes_AndThenUpdate() { var source0 = @" namespace System.Runtime.CompilerServices { class X { } } namespace N { class C { static void Main() { } } } "; var source1 = @" namespace System.Runtime.CompilerServices { class X { } } namespace N { struct C { static void Main() { Id(in G()); } static ref readonly int Id(in int x) => ref x; static ref readonly int G() => ref new int[1] { 1 }[0]; } }"; var source2 = @" namespace System.Runtime.CompilerServices { class X { } } namespace N { struct C { static void Main() { Id(in G()); } static ref readonly int Id(in int x) => ref x; static ref readonly int G() => ref new int[1] { 2 }[0]; static void H(string? s) {} } }"; var source3 = @" namespace System.Runtime.CompilerServices { class X { } } namespace N { struct C { static void Main() { Id(in G()); } static ref readonly int Id(in int x) => ref x; static ref readonly int G() => ref new int[1] { 2 }[0]; static void H(string? s) {} readonly ref readonly string?[]? F() => throw null; } }"; var compilation0 = CreateCompilation(source0, options: ComSafeDebugDll); var compilation1 = compilation0.WithSource(source1); var compilation2 = compilation1.WithSource(source2); var compilation3 = compilation2.WithSource(source3); var main0 = compilation0.GetMember<MethodSymbol>("N.C.Main"); var main1 = compilation1.GetMember<MethodSymbol>("N.C.Main"); var id1 = compilation1.GetMember<MethodSymbol>("N.C.Id"); var g1 = compilation1.GetMember<MethodSymbol>("N.C.G"); var g2 = compilation2.GetMember<MethodSymbol>("N.C.G"); var h2 = compilation2.GetMember<MethodSymbol>("N.C.H"); var f3 = compilation3.GetMember<MethodSymbol>("N.C.F"); // Verify full metadata contains expected rows. using var md0 = ModuleMetadata.CreateFromImage(compilation0.EmitToArray()); var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, main0, main1), SemanticEdit.Create(SemanticEditKind.Insert, null, id1), SemanticEdit.Create(SemanticEditKind.Insert, null, g1))); diff1.VerifySynthesizedMembers( "<global namespace>: {Microsoft}", "Microsoft: {CodeAnalysis}", "Microsoft.CodeAnalysis: {EmbeddedAttribute}", "System.Runtime.CompilerServices: {IsReadOnlyAttribute}"); diff1.VerifyIL("N.C.Main", @" { // Code size 13 (0xd) .maxstack 1 IL_0000: nop IL_0001: call ""ref readonly int N.C.G()"" IL_0006: call ""ref readonly int N.C.Id(in int)"" IL_000b: pop IL_000c: ret } "); diff1.VerifyIL("N.C.Id", @" { // Code size 2 (0x2) .maxstack 1 IL_0000: ldarg.0 IL_0001: ret } "); diff1.VerifyIL("N.C.G", @" { // Code size 17 (0x11) .maxstack 4 IL_0000: ldc.i4.1 IL_0001: newarr ""int"" IL_0006: dup IL_0007: ldc.i4.0 IL_0008: ldc.i4.1 IL_0009: stelem.i4 IL_000a: ldc.i4.0 IL_000b: ldelema ""int"" IL_0010: ret } "); // Verify delta metadata contains expected rows. using var md1 = diff1.GetMetadata(); var reader0 = md0.MetadataReader; var reader1 = md1.Reader; var readers = new List<MetadataReader>() { reader0, reader1 }; CheckNames(readers, reader1.GetTypeDefFullNames(), "Microsoft.CodeAnalysis.EmbeddedAttribute", "System.Runtime.CompilerServices.IsReadOnlyAttribute"); CheckNames(readers, reader1.GetMethodDefNames(), "Main", ".ctor", ".ctor", "Id", "G"); CheckEncLog(reader1, Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default), Row(5, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(6, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(6, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(7, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(8, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(9, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(10, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(4, TableIndex.TypeDef, EditAndContinueOperation.Default), Row(5, TableIndex.TypeDef, EditAndContinueOperation.Default), Row(1, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(4, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(4, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(5, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(5, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(2, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(6, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(2, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(7, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(6, TableIndex.MethodDef, EditAndContinueOperation.AddParameter), Row(1, TableIndex.Param, EditAndContinueOperation.Default), Row(6, TableIndex.MethodDef, EditAndContinueOperation.AddParameter), Row(2, TableIndex.Param, EditAndContinueOperation.Default), Row(7, TableIndex.MethodDef, EditAndContinueOperation.AddParameter), Row(3, TableIndex.Param, EditAndContinueOperation.Default), Row(4, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(5, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(6, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(7, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(8, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(9, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(10, TableIndex.CustomAttribute, EditAndContinueOperation.Default)); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, g1, g2), SemanticEdit.Create(SemanticEditKind.Insert, null, h2))); // synthesized member for nullable annotations added: diff2.VerifySynthesizedMembers( "<global namespace>: {Microsoft}", "Microsoft: {CodeAnalysis}", "Microsoft.CodeAnalysis: {EmbeddedAttribute}", "System.Runtime.CompilerServices: {IsReadOnlyAttribute, NullableAttribute, NullableContextAttribute}"); // Verify delta metadata contains expected rows. using var md2 = diff2.GetMetadata(); var reader2 = md2.Reader; readers.Add(reader2); // note: NullableAttribute has 2 ctors, NullableContextAttribute has one CheckNames(readers, reader2.GetTypeDefFullNames(), "System.Runtime.CompilerServices.NullableAttribute", "System.Runtime.CompilerServices.NullableContextAttribute"); CheckNames(readers, reader2.GetMethodDefNames(), "G", ".ctor", ".ctor", ".ctor", "H"); // two new TypeDefs emitted for the attributes: CheckEncLog(reader2, Row(3, TableIndex.AssemblyRef, EditAndContinueOperation.Default), Row(7, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(8, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(9, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(11, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(12, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(13, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(14, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(15, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(16, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(17, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(18, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(6, TableIndex.TypeDef, EditAndContinueOperation.Default), // NullableAttribute Row(7, TableIndex.TypeDef, EditAndContinueOperation.Default), // NullableContextAttribute Row(6, TableIndex.TypeDef, EditAndContinueOperation.AddField), Row(1, TableIndex.Field, EditAndContinueOperation.Default), Row(7, TableIndex.TypeDef, EditAndContinueOperation.AddField), Row(2, TableIndex.Field, EditAndContinueOperation.Default), Row(7, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(6, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(8, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(6, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(9, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(7, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(10, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(2, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(11, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(3, TableIndex.Param, EditAndContinueOperation.Default), Row(11, TableIndex.MethodDef, EditAndContinueOperation.AddParameter), Row(4, TableIndex.Param, EditAndContinueOperation.Default), Row(6, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(11, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(12, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(13, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(14, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(15, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(16, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(17, TableIndex.CustomAttribute, EditAndContinueOperation.Default)); CheckEncMap(reader2, Handle(11, TableIndex.TypeRef), Handle(12, TableIndex.TypeRef), Handle(13, TableIndex.TypeRef), Handle(14, TableIndex.TypeRef), Handle(15, TableIndex.TypeRef), Handle(16, TableIndex.TypeRef), Handle(17, TableIndex.TypeRef), Handle(18, TableIndex.TypeRef), Handle(6, TableIndex.TypeDef), Handle(7, TableIndex.TypeDef), Handle(1, TableIndex.Field), Handle(2, TableIndex.Field), Handle(7, TableIndex.MethodDef), Handle(8, TableIndex.MethodDef), Handle(9, TableIndex.MethodDef), Handle(10, TableIndex.MethodDef), Handle(11, TableIndex.MethodDef), Handle(3, TableIndex.Param), Handle(4, TableIndex.Param), Handle(7, TableIndex.MemberRef), Handle(8, TableIndex.MemberRef), Handle(9, TableIndex.MemberRef), Handle(6, TableIndex.CustomAttribute), Handle(11, TableIndex.CustomAttribute), Handle(12, TableIndex.CustomAttribute), Handle(13, TableIndex.CustomAttribute), Handle(14, TableIndex.CustomAttribute), Handle(15, TableIndex.CustomAttribute), Handle(16, TableIndex.CustomAttribute), Handle(17, TableIndex.CustomAttribute), Handle(3, TableIndex.AssemblyRef)); var diff3 = compilation3.EmitDifference( diff2.NextGeneration, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Insert, null, f3))); // no change in synthesized members: diff3.VerifySynthesizedMembers( "<global namespace>: {Microsoft}", "Microsoft: {CodeAnalysis}", "Microsoft.CodeAnalysis: {EmbeddedAttribute}", "System.Runtime.CompilerServices: {IsReadOnlyAttribute, NullableAttribute, NullableContextAttribute}"); // Verify delta metadata contains expected rows. using var md3 = diff3.GetMetadata(); var reader3 = md3.Reader; readers.Add(reader3); // no new type defs: CheckNames(readers, reader3.GetTypeDefFullNames()); CheckNames(readers, reader3.GetMethodDefNames(), "F"); CheckEncLog(reader3, Row(4, TableIndex.AssemblyRef, EditAndContinueOperation.Default), Row(19, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(20, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(2, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(12, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(12, TableIndex.MethodDef, EditAndContinueOperation.AddParameter), Row(5, TableIndex.Param, EditAndContinueOperation.Default), Row(18, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(19, TableIndex.CustomAttribute, EditAndContinueOperation.Default)); } [Fact] public void Field_Add() { var source0 = @"class C { string F = ""F""; }"; var source1 = @"class C { string F = ""F""; string G = ""G""; }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); // Verify full metadata contains expected rows. var bytes0 = compilation0.EmitToArray(); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var reader0 = md0.MetadataReader; CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "C"); CheckNames(reader0, reader0.GetFieldDefNames(), "F"); CheckNames(reader0, reader0.GetMethodDefNames(), ".ctor"); var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider); var method0 = compilation0.GetMember<MethodSymbol>("C..ctor"); var method1 = compilation1.GetMember<MethodSymbol>("C..ctor"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Insert, null, compilation1.GetMember<FieldSymbol>("C.G")), SemanticEdit.Create(SemanticEditKind.Update, method0, method1))); // Verify delta metadata contains expected rows. using var md1 = diff1.GetMetadata(); var reader1 = md1.Reader; var readers = new[] { reader0, reader1 }; CheckNames(readers, diff1.EmitResult.ChangedTypes, "C"); CheckNames(readers, reader1.GetTypeDefNames()); CheckNames(readers, reader1.GetFieldDefNames(), "G"); CheckNames(readers, reader1.GetMethodDefNames(), ".ctor"); CheckEncLog(reader1, Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default), Row(5, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(6, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(2, TableIndex.TypeDef, EditAndContinueOperation.AddField), Row(2, TableIndex.Field, EditAndContinueOperation.Default), Row(1, TableIndex.MethodDef, EditAndContinueOperation.Default)); CheckEncMap(reader1, Handle(6, TableIndex.TypeRef), Handle(2, TableIndex.Field), Handle(1, TableIndex.MethodDef), Handle(5, TableIndex.MemberRef), Handle(2, TableIndex.AssemblyRef)); } [Fact] public void Property_Accessor_Update() { var source0 = @"class C { object P { get { return 1; } } }"; var source1 = @"class C { object P { get { return 2; } } }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var getP0 = compilation0.GetMember<MethodSymbol>("C.get_P"); var getP1 = compilation1.GetMember<MethodSymbol>("C.get_P"); var bytes0 = compilation0.EmitToArray(); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var reader0 = md0.MetadataReader; CheckNames(reader0, reader0.GetPropertyDefNames(), "P"); CheckNames(reader0, reader0.GetMethodDefNames(), "get_P", ".ctor"); var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, getP0, getP1))); using var md1 = diff1.GetMetadata(); var reader1 = md1.Reader; var readers = new[] { reader0, reader1 }; CheckNames(readers, reader1.GetPropertyDefNames(), "P"); CheckNames(readers, reader1.GetMethodDefNames(), "get_P"); CheckEncLog(reader1, Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default), Row(7, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(8, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(2, TableIndex.StandAloneSig, EditAndContinueOperation.Default), Row(1, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(1, TableIndex.Property, EditAndContinueOperation.Default), Row(2, TableIndex.MethodSemantics, EditAndContinueOperation.Default)); CheckEncMap(reader1, Handle(7, TableIndex.TypeRef), Handle(8, TableIndex.TypeRef), Handle(1, TableIndex.MethodDef), Handle(2, TableIndex.StandAloneSig), Handle(1, TableIndex.Property), Handle(2, TableIndex.MethodSemantics), Handle(2, TableIndex.AssemblyRef)); } [Fact] public void Property_Add() { var source0 = @" class C { } "; var source1 = @" class C { object R { get { return null; } } } "; var source2 = @" class C { object R { get { return null; } } object Q { get; set; } } "; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var compilation2 = compilation0.WithSource(source2); var r1 = compilation1.GetMember<PropertySymbol>("C.R"); var q2 = compilation2.GetMember<PropertySymbol>("C.Q"); var bytes0 = compilation0.EmitToArray(); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var reader0 = md0.MetadataReader; CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "C"); var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider); // gen 1 var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Insert, null, r1))); using var md1 = diff1.GetMetadata(); var reader1 = md1.Reader; var readers = new List<MetadataReader> { reader0, reader1 }; CheckNames(readers, reader1.GetTypeDefNames()); CheckNames(readers, reader1.GetFieldDefNames()); CheckNames(readers, reader1.GetPropertyDefNames(), "R"); CheckNames(readers, reader1.GetMethodDefNames(), "get_R"); CheckNames(readers, diff1.EmitResult.UpdatedMethods); CheckNames(readers, diff1.EmitResult.ChangedTypes, "C"); CheckEncLogDefinitions(reader1, Row(1, TableIndex.StandAloneSig, EditAndContinueOperation.Default), Row(1, TableIndex.PropertyMap, EditAndContinueOperation.Default), Row(2, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(2, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(1, TableIndex.PropertyMap, EditAndContinueOperation.AddProperty), Row(1, TableIndex.Property, EditAndContinueOperation.Default), Row(1, TableIndex.MethodSemantics, EditAndContinueOperation.Default)); CheckEncMapDefinitions(reader1, Handle(2, TableIndex.MethodDef), Handle(1, TableIndex.StandAloneSig), Handle(1, TableIndex.PropertyMap), Handle(1, TableIndex.Property), Handle(1, TableIndex.MethodSemantics)); // gen 2 var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Insert, null, q2))); using var md2 = diff2.GetMetadata(); var reader2 = md2.Reader; readers.Add(reader2); CheckNames(readers, reader2.GetTypeDefNames()); CheckNames(readers, reader2.GetFieldDefNames(), "<Q>k__BackingField"); CheckNames(readers, reader2.GetPropertyDefNames(), "Q"); CheckNames(readers, reader2.GetMethodDefNames(), "get_Q", "set_Q"); CheckNames(readers, diff1.EmitResult.UpdatedMethods); CheckNames(readers, diff1.EmitResult.ChangedTypes, "C"); CheckEncLogDefinitions(reader2, Row(2, TableIndex.TypeDef, EditAndContinueOperation.AddField), Row(1, TableIndex.Field, EditAndContinueOperation.Default), Row(2, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(3, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(2, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(4, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(1, TableIndex.PropertyMap, EditAndContinueOperation.AddProperty), Row(2, TableIndex.Property, EditAndContinueOperation.Default), Row(4, TableIndex.MethodDef, EditAndContinueOperation.AddParameter), Row(1, TableIndex.Param, EditAndContinueOperation.Default), Row(4, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(5, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(6, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(7, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(2, TableIndex.MethodSemantics, EditAndContinueOperation.Default), Row(3, TableIndex.MethodSemantics, EditAndContinueOperation.Default)); CheckEncMapDefinitions(reader2, Handle(1, TableIndex.Field), Handle(3, TableIndex.MethodDef), Handle(4, TableIndex.MethodDef), Handle(1, TableIndex.Param), Handle(4, TableIndex.CustomAttribute), Handle(5, TableIndex.CustomAttribute), Handle(6, TableIndex.CustomAttribute), Handle(7, TableIndex.CustomAttribute), Handle(2, TableIndex.Property), Handle(2, TableIndex.MethodSemantics), Handle(3, TableIndex.MethodSemantics)); } [Fact] public void Event_Add() { var source0 = @" class C { }"; var source1 = @" class C { event System.Action E; }"; var source2 = @" class C { event System.Action E; event System.Action G; }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var compilation2 = compilation0.WithSource(source2); var e1 = compilation1.GetMember<EventSymbol>("C.E"); var g2 = compilation2.GetMember<EventSymbol>("C.G"); var bytes0 = compilation0.EmitToArray(); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var reader0 = md0.MetadataReader; var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider); // gen 1 var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Insert, null, e1))); using var md1 = diff1.GetMetadata(); var reader1 = md1.Reader; var readers = new List<MetadataReader> { reader0, reader1 }; CheckNames(readers, reader1.GetTypeDefNames()); CheckNames(readers, reader1.GetFieldDefNames(), "E"); CheckNames(readers, reader1.GetMethodDefNames(), "add_E", "remove_E"); CheckNames(readers, diff1.EmitResult.UpdatedMethods); CheckNames(readers, diff1.EmitResult.ChangedTypes, "C"); CheckEncLogDefinitions(reader1, Row(1, TableIndex.StandAloneSig, EditAndContinueOperation.Default), Row(1, TableIndex.EventMap, EditAndContinueOperation.Default), Row(1, TableIndex.EventMap, EditAndContinueOperation.AddEvent), Row(1, TableIndex.Event, EditAndContinueOperation.Default), Row(2, TableIndex.TypeDef, EditAndContinueOperation.AddField), Row(1, TableIndex.Field, EditAndContinueOperation.Default), Row(2, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(2, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(2, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(3, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(2, TableIndex.MethodDef, EditAndContinueOperation.AddParameter), Row(1, TableIndex.Param, EditAndContinueOperation.Default), Row(3, TableIndex.MethodDef, EditAndContinueOperation.AddParameter), Row(2, TableIndex.Param, EditAndContinueOperation.Default), Row(4, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(5, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(6, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(7, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(1, TableIndex.MethodSemantics, EditAndContinueOperation.Default), Row(2, TableIndex.MethodSemantics, EditAndContinueOperation.Default)); CheckEncMapDefinitions(reader1, Handle(1, TableIndex.Field), Handle(2, TableIndex.MethodDef), Handle(3, TableIndex.MethodDef), Handle(1, TableIndex.Param), Handle(2, TableIndex.Param), Handle(4, TableIndex.CustomAttribute), Handle(5, TableIndex.CustomAttribute), Handle(6, TableIndex.CustomAttribute), Handle(7, TableIndex.CustomAttribute), Handle(1, TableIndex.StandAloneSig), Handle(1, TableIndex.EventMap), Handle(1, TableIndex.Event), Handle(1, TableIndex.MethodSemantics), Handle(2, TableIndex.MethodSemantics)); // gen 2 var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Insert, null, g2))); using var md2 = diff2.GetMetadata(); var reader2 = md2.Reader; readers.Add(reader2); CheckNames(readers, reader2.GetTypeDefNames()); CheckNames(readers, reader2.GetFieldDefNames(), "G"); CheckNames(readers, reader2.GetMethodDefNames(), "add_G", "remove_G"); CheckNames(readers, diff1.EmitResult.UpdatedMethods); CheckNames(readers, diff1.EmitResult.ChangedTypes, "C"); CheckEncLogDefinitions(reader2, Row(2, TableIndex.StandAloneSig, EditAndContinueOperation.Default), Row(1, TableIndex.EventMap, EditAndContinueOperation.AddEvent), Row(2, TableIndex.Event, EditAndContinueOperation.Default), Row(2, TableIndex.TypeDef, EditAndContinueOperation.AddField), Row(2, TableIndex.Field, EditAndContinueOperation.Default), Row(2, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(4, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(2, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(5, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(4, TableIndex.MethodDef, EditAndContinueOperation.AddParameter), Row(3, TableIndex.Param, EditAndContinueOperation.Default), Row(5, TableIndex.MethodDef, EditAndContinueOperation.AddParameter), Row(4, TableIndex.Param, EditAndContinueOperation.Default), Row(8, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(9, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(10, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(11, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(3, TableIndex.MethodSemantics, EditAndContinueOperation.Default), Row(4, TableIndex.MethodSemantics, EditAndContinueOperation.Default)); CheckEncMapDefinitions(reader2, Handle(2, TableIndex.Field), Handle(4, TableIndex.MethodDef), Handle(5, TableIndex.MethodDef), Handle(3, TableIndex.Param), Handle(4, TableIndex.Param), Handle(8, TableIndex.CustomAttribute), Handle(9, TableIndex.CustomAttribute), Handle(10, TableIndex.CustomAttribute), Handle(11, TableIndex.CustomAttribute), Handle(2, TableIndex.StandAloneSig), Handle(2, TableIndex.Event), Handle(3, TableIndex.MethodSemantics), Handle(4, TableIndex.MethodSemantics)); } [WorkItem(1175704, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1175704")] [Fact] public void EventFields() { var source0 = MarkedSource(@" using System; class C { static event EventHandler handler; static int F() { handler(null, null); return 1; } } "); var source1 = MarkedSource(@" using System; class C { static event EventHandler handler; static int F() { handler(null, null); return 10; } } "); var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll); var compilation1 = compilation0.WithSource(source1.Tree); var f0 = compilation0.GetMember<MethodSymbol>("C.F"); var f1 = compilation1.GetMember<MethodSymbol>("C.F"); var v0 = CompileAndVerify(compilation0); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, f0, f1, preserveLocalVariables: true))); diff1.VerifyIL("C.F", @" { // Code size 21 (0x15) .maxstack 3 .locals init (int V_0) IL_0000: nop IL_0001: ldsfld ""System.EventHandler C.handler"" IL_0006: ldnull IL_0007: ldnull IL_0008: callvirt ""void System.EventHandler.Invoke(object, System.EventArgs)"" IL_000d: nop IL_000e: ldc.i4.s 10 IL_0010: stloc.0 IL_0011: br.s IL_0013 IL_0013: ldloc.0 IL_0014: ret } "); } [Fact] public void UpdateType_AddAttributes() { var source0 = @" class C { }"; var source1 = @" [System.ComponentModel.Description(""C"")] class C { }"; var source2 = @" [System.ComponentModel.Description(""C"")] [System.ObsoleteAttribute] class C { }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll, targetFramework: TargetFramework.NetStandard20); var compilation1 = compilation0.WithSource(source1); var compilation2 = compilation1.WithSource(source2); var c0 = compilation0.GetMember<NamedTypeSymbol>("C"); var c1 = compilation1.GetMember<NamedTypeSymbol>("C"); var c2 = compilation2.GetMember<NamedTypeSymbol>("C"); // Verify full metadata contains expected rows. var bytes0 = compilation0.EmitToArray(); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var reader0 = md0.MetadataReader; CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "C"); Assert.Equal(3, reader0.CustomAttributes.Count); var generation0 = EmitBaseline.CreateInitialBaseline( md0, EmptyLocalsProvider); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, c0, c1))); // Verify delta metadata contains expected rows. using var md1 = diff1.GetMetadata(); var reader1 = md1.Reader; var readers = new[] { reader0, reader1 }; CheckNames(readers, reader1.GetTypeDefNames(), "C"); Assert.Equal(1, reader1.CustomAttributes.Count); CheckEncLogDefinitions(reader1, Row(2, TableIndex.TypeDef, EditAndContinueOperation.Default), Row(4, TableIndex.CustomAttribute, EditAndContinueOperation.Default)); CheckEncMapDefinitions(reader1, Handle(2, TableIndex.TypeDef), Handle(4, TableIndex.CustomAttribute)); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, c1, c2))); // Verify delta metadata contains expected rows. using var md2 = diff2.GetMetadata(); var reader2 = md2.Reader; readers = new[] { reader0, reader1, reader2 }; CheckNames(readers, reader2.GetTypeDefNames(), "C"); Assert.Equal(2, reader2.CustomAttributes.Count); CheckEncLogDefinitions(reader2, Row(2, TableIndex.TypeDef, EditAndContinueOperation.Default), Row(4, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(5, TableIndex.CustomAttribute, EditAndContinueOperation.Default)); CheckEncMapDefinitions(reader2, Handle(2, TableIndex.TypeDef), Handle(4, TableIndex.CustomAttribute), Handle(5, TableIndex.CustomAttribute)); } [Fact] public void ReplaceType() { var source0 = @" class C { void F(int x) {} } "; var source1 = @" class C { void F(int x, int y) { } }"; var source2 = @" class C { void F(int x, int y) { System.Console.WriteLine(1); } }"; var source3 = @" [System.Obsolete] class C { void F(int x, int y) { System.Console.WriteLine(2); } }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll, targetFramework: TargetFramework.NetStandard20); var compilation1 = compilation0.WithSource(source1); var compilation2 = compilation1.WithSource(source2); var compilation3 = compilation2.WithSource(source3); var c0 = compilation0.GetMember<NamedTypeSymbol>("C"); var c1 = compilation1.GetMember<NamedTypeSymbol>("C"); var c2 = compilation2.GetMember<NamedTypeSymbol>("C"); var c3 = compilation3.GetMember<NamedTypeSymbol>("C"); var f2 = c2.GetMember<MethodSymbol>("F"); var f3 = c3.GetMember<MethodSymbol>("F"); // Verify full metadata contains expected rows. var bytes0 = compilation0.EmitToArray(); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var reader0 = md0.MetadataReader; CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "C"); var generation0 = EmitBaseline.CreateInitialBaseline( md0, EmptyLocalsProvider); // This update emulates "Reloadable" type behavior - a new type is generated instead of updating the existing one. var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Replace, null, c1))); // Verify delta metadata contains expected rows. using var md1 = diff1.GetMetadata(); var reader1 = md1.Reader; var readers = new[] { reader0, reader1 }; CheckNames(readers, reader1.GetTypeDefNames(), "C#1"); CheckNames(readers, diff1.EmitResult.ChangedTypes, "C#1"); CheckEncLogDefinitions(reader1, Row(3, TableIndex.TypeDef, EditAndContinueOperation.Default), Row(3, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(3, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(3, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(4, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(3, TableIndex.MethodDef, EditAndContinueOperation.AddParameter), Row(2, TableIndex.Param, EditAndContinueOperation.Default), Row(3, TableIndex.MethodDef, EditAndContinueOperation.AddParameter), Row(3, TableIndex.Param, EditAndContinueOperation.Default)); CheckEncMapDefinitions(reader1, Handle(3, TableIndex.TypeDef), Handle(3, TableIndex.MethodDef), Handle(4, TableIndex.MethodDef), Handle(2, TableIndex.Param), Handle(3, TableIndex.Param)); // This update emulates "Reloadable" type behavior - a new type is generated instead of updating the existing one. var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Replace, null, c2))); // Verify delta metadata contains expected rows. using var md2 = diff2.GetMetadata(); var reader2 = md2.Reader; readers = new[] { reader0, reader1, reader2 }; CheckNames(readers, reader2.GetTypeDefNames(), "C#2"); CheckNames(readers, diff2.EmitResult.ChangedTypes, "C#2"); CheckEncLogDefinitions(reader2, Row(4, TableIndex.TypeDef, EditAndContinueOperation.Default), Row(4, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(5, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(4, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(6, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(5, TableIndex.MethodDef, EditAndContinueOperation.AddParameter), Row(4, TableIndex.Param, EditAndContinueOperation.Default), Row(5, TableIndex.MethodDef, EditAndContinueOperation.AddParameter), Row(5, TableIndex.Param, EditAndContinueOperation.Default)); CheckEncMapDefinitions(reader2, Handle(4, TableIndex.TypeDef), Handle(5, TableIndex.MethodDef), Handle(6, TableIndex.MethodDef), Handle(4, TableIndex.Param), Handle(5, TableIndex.Param)); // This update is an EnC update - even reloadable types are update in-place var diff3 = compilation3.EmitDifference( diff2.NextGeneration, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, c2, c3), SemanticEdit.Create(SemanticEditKind.Update, f2, f3))); // Verify delta metadata contains expected rows. using var md3 = diff3.GetMetadata(); var reader3 = md3.Reader; readers = new[] { reader0, reader1, reader2, reader3 }; CheckNames(readers, reader3.GetTypeDefNames(), "C#2"); CheckNames(readers, diff3.EmitResult.ChangedTypes, "C#2"); CheckEncLogDefinitions(reader3, Row(4, TableIndex.TypeDef, EditAndContinueOperation.Default), Row(5, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(4, TableIndex.Param, EditAndContinueOperation.Default), Row(5, TableIndex.Param, EditAndContinueOperation.Default), Row(4, TableIndex.CustomAttribute, EditAndContinueOperation.Default)); CheckEncMapDefinitions(reader3, Handle(4, TableIndex.TypeDef), Handle(5, TableIndex.MethodDef), Handle(4, TableIndex.Param), Handle(5, TableIndex.Param), Handle(4, TableIndex.CustomAttribute)); } [Fact] public void EventFields_Attributes() { var source0 = MarkedSource(@" using System; class C { static event EventHandler E; } "); var source1 = MarkedSource(@" using System; class C { [System.Obsolete] static event EventHandler E; }"); var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll); var compilation1 = compilation0.WithSource(source1.Tree); var event0 = compilation0.GetMember<EventSymbol>("C.E"); var event1 = compilation1.GetMember<EventSymbol>("C.E"); var v0 = CompileAndVerify(compilation0); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var reader0 = md0.MetadataReader; var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "C"); CheckNames(reader0, reader0.GetMethodDefNames(), "add_E", "remove_E", ".ctor"); CheckAttributes(reader0, new CustomAttributeRow(Handle(1, TableIndex.MethodDef), Handle(4, TableIndex.MemberRef)), new CustomAttributeRow(Handle(1, TableIndex.Field), Handle(4, TableIndex.MemberRef)), new CustomAttributeRow(Handle(1, TableIndex.Field), Handle(5, TableIndex.MemberRef)), new CustomAttributeRow(Handle(1, TableIndex.Assembly), Handle(1, TableIndex.MemberRef)), new CustomAttributeRow(Handle(1, TableIndex.Assembly), Handle(2, TableIndex.MemberRef)), new CustomAttributeRow(Handle(1, TableIndex.Assembly), Handle(3, TableIndex.MemberRef)), new CustomAttributeRow(Handle(2, TableIndex.MethodDef), Handle(4, TableIndex.MemberRef))); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, event0, event1))); // Verify delta metadata contains expected rows. using var md1 = diff1.GetMetadata(); var reader1 = md1.Reader; var readers = new[] { reader0, reader1 }; EncValidation.VerifyModuleMvid(1, reader0, reader1); CheckNames(readers, reader1.GetTypeDefNames()); CheckNames(readers, reader1.GetMethodDefNames()); CheckNames(readers, reader1.GetEventDefNames(), "E"); CheckAttributes(reader1, new CustomAttributeRow(Handle(1, TableIndex.Event), Handle(10, TableIndex.MemberRef))); CheckEncLogDefinitions(reader1, Row(1, TableIndex.Event, EditAndContinueOperation.Default), Row(8, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(3, TableIndex.MethodSemantics, EditAndContinueOperation.Default), Row(4, TableIndex.MethodSemantics, EditAndContinueOperation.Default)); CheckEncMapDefinitions(reader1, Handle(8, TableIndex.CustomAttribute), Handle(1, TableIndex.Event), Handle(3, TableIndex.MethodSemantics), Handle(4, TableIndex.MethodSemantics)); } [Fact] public void ReplaceType_AsyncLambda() { var source0 = @" using System.Threading.Tasks; class C { void F(int x) { Task.Run(async() => {}); } } "; var source1 = @" using System.Threading.Tasks; class C { void F(bool y) { Task.Run(async() => {}); } } "; var source2 = @" using System.Threading.Tasks; class C { void F(uint z) { Task.Run(async() => {}); } } "; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll, targetFramework: TargetFramework.NetStandard20); var compilation1 = compilation0.WithSource(source1); var compilation2 = compilation1.WithSource(source2); var c0 = compilation0.GetMember<NamedTypeSymbol>("C"); var c1 = compilation1.GetMember<NamedTypeSymbol>("C"); var c2 = compilation2.GetMember<NamedTypeSymbol>("C"); var f2 = c2.GetMember<MethodSymbol>("F"); // Verify full metadata contains expected rows. var bytes0 = compilation0.EmitToArray(); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var reader0 = md0.MetadataReader; CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "C", "<>c", "<<F>b__0_0>d"); var generation0 = EmitBaseline.CreateInitialBaseline( md0, EmptyLocalsProvider); // This update emulates "Reloadable" type behavior - a new type is generated instead of updating the existing one. var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Replace, null, c1))); // Verify delta metadata contains expected rows. using var md1 = diff1.GetMetadata(); var reader1 = md1.Reader; var readers = new[] { reader0, reader1 }; // A new nested type <>c is generated in C#1 CheckNames(readers, reader1.GetTypeDefNames(), "C#1", "<>c", "<<F>b__0#1_0#1>d"); CheckNames(readers, diff1.EmitResult.ChangedTypes, "C#1", "<>c", "<<F>b__0#1_0#1>d"); // This update emulates "Reloadable" type behavior - a new type is generated instead of updating the existing one. var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Replace, null, c2))); // Verify delta metadata contains expected rows. using var md2 = diff2.GetMetadata(); var reader2 = md2.Reader; readers = new[] { reader0, reader1, reader2 }; // A new nested type <>c is generated in C#2 CheckNames(readers, reader2.GetTypeDefNames(), "C#2", "<>c", "<<F>b__0#2_0#2>d"); CheckNames(readers, diff2.EmitResult.ChangedTypes, "C#2", "<>c", "<<F>b__0#2_0#2>d"); } [Fact] public void ReplaceType_AsyncLambda_InNestedType() { var source0 = @" using System.Threading.Tasks; class C { class D { void F(int x) { Task.Run(async() => {}); } } } "; var source1 = @" using System.Threading.Tasks; class C { class D { void F(bool y) { Task.Run(async() => {}); } } } "; var source2 = @" using System.Threading.Tasks; class C { class D { void F(uint z) { Task.Run(async() => {}); } } } "; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll, targetFramework: TargetFramework.NetStandard20); var compilation1 = compilation0.WithSource(source1); var compilation2 = compilation1.WithSource(source2); var c0 = compilation0.GetMember<NamedTypeSymbol>("C"); var c1 = compilation1.GetMember<NamedTypeSymbol>("C"); var c2 = compilation2.GetMember<NamedTypeSymbol>("C"); var f2 = c2.GetMember<MethodSymbol>("F"); // Verify full metadata contains expected rows. var bytes0 = compilation0.EmitToArray(); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var reader0 = md0.MetadataReader; CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "C", "D", "<>c", "<<F>b__0_0>d"); var generation0 = EmitBaseline.CreateInitialBaseline( md0, EmptyLocalsProvider); // This update emulates "Reloadable" type behavior - a new type is generated instead of updating the existing one. var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Replace, null, c1))); // Verify delta metadata contains expected rows. using var md1 = diff1.GetMetadata(); var reader1 = md1.Reader; var readers = new[] { reader0, reader1 }; // A new nested type <>c is generated in C#1 CheckNames(readers, reader1.GetTypeDefNames(), "C#1", "D", "<>c", "<<F>b__0#1_0#1>d"); CheckNames(readers, diff1.EmitResult.ChangedTypes, "C#1", "D", "<>c", "<<F>b__0#1_0#1>d"); // This update emulates "Reloadable" type behavior - a new type is generated instead of updating the existing one. var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Replace, null, c2))); // Verify delta metadata contains expected rows. using var md2 = diff2.GetMetadata(); var reader2 = md2.Reader; readers = new[] { reader0, reader1, reader2 }; // A new nested type <>c is generated in C#2 CheckNames(readers, reader2.GetTypeDefNames(), "C#2", "D", "<>c", "<<F>b__0#2_0#2>d"); CheckNames(readers, diff2.EmitResult.ChangedTypes, "C#2", "D", "<>c", "<<F>b__0#2_0#2>d"); } [Fact] public void AddNestedTypeAndMembers() { var source0 = @"class A { class B { } static object F() { return new B(); } }"; var source1 = @"class A { class B { } class C { class D { } static object F; internal static object G() { return F; } } static object F() { return C.G(); } }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var c1 = compilation1.GetMember<NamedTypeSymbol>("A.C"); var f0 = compilation0.GetMember<MethodSymbol>("A.F"); var f1 = compilation1.GetMember<MethodSymbol>("A.F"); // Verify full metadata contains expected rows. var bytes0 = compilation0.EmitToArray(); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var reader0 = md0.MetadataReader; CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "A", "B"); CheckNames(reader0, reader0.GetMethodDefNames(), "F", ".ctor", ".ctor"); Assert.Equal(1, reader0.GetTableRowCount(TableIndex.NestedClass)); var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Insert, null, c1), SemanticEdit.Create(SemanticEditKind.Update, f0, f1))); // Verify delta metadata contains expected rows. using var md1 = diff1.GetMetadata(); var reader1 = md1.Reader; var readers = new[] { reader0, reader1 }; CheckNames(readers, reader1.GetTypeDefNames(), "C", "D"); CheckNames(readers, reader1.GetMethodDefNames(), "F", "G", ".ctor", ".ctor"); CheckNames(readers, diff1.EmitResult.UpdatedMethods, "F"); CheckNames(readers, diff1.EmitResult.ChangedTypes, "A", "C", "D"); Assert.Equal(2, reader1.GetTableRowCount(TableIndex.NestedClass)); CheckEncLog(reader1, Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default), Row(5, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(6, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(2, TableIndex.StandAloneSig, EditAndContinueOperation.Default), Row(4, TableIndex.TypeDef, EditAndContinueOperation.Default), Row(5, TableIndex.TypeDef, EditAndContinueOperation.Default), Row(4, TableIndex.TypeDef, EditAndContinueOperation.AddField), Row(1, TableIndex.Field, EditAndContinueOperation.Default), Row(1, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(4, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(4, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(4, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(5, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(5, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(6, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(2, TableIndex.NestedClass, EditAndContinueOperation.Default), Row(3, TableIndex.NestedClass, EditAndContinueOperation.Default)); CheckEncMap(reader1, Handle(6, TableIndex.TypeRef), Handle(4, TableIndex.TypeDef), Handle(5, TableIndex.TypeDef), Handle(1, TableIndex.Field), Handle(1, TableIndex.MethodDef), Handle(4, TableIndex.MethodDef), Handle(5, TableIndex.MethodDef), Handle(6, TableIndex.MethodDef), Handle(5, TableIndex.MemberRef), Handle(2, TableIndex.StandAloneSig), Handle(2, TableIndex.AssemblyRef), Handle(2, TableIndex.NestedClass), Handle(3, TableIndex.NestedClass)); } /// <summary> /// Nested types should be emitted in the /// same order as full emit. /// </summary> [Fact] public void AddNestedTypesOrder() { var source0 = @"class A { class B1 { class C1 { } } class B2 { class C2 { } } }"; var source1 = @"class A { class B1 { class C1 { } } class B2 { class C2 { } } class B3 { class C3 { } } class B4 { class C4 { } } }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var bytes0 = compilation0.EmitToArray(); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var reader0 = md0.MetadataReader; CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "A", "B1", "B2", "C1", "C2"); Assert.Equal(4, reader0.GetTableRowCount(TableIndex.NestedClass)); var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Insert, null, compilation1.GetMember<NamedTypeSymbol>("A.B3")), SemanticEdit.Create(SemanticEditKind.Insert, null, compilation1.GetMember<NamedTypeSymbol>("A.B4")))); using var md1 = diff1.GetMetadata(); var reader1 = md1.Reader; var readers = new[] { reader0, reader1 }; CheckNames(readers, reader1.GetTypeDefNames(), "B3", "B4", "C3", "C4"); Assert.Equal(4, reader1.GetTableRowCount(TableIndex.NestedClass)); } [Fact] public void AddNestedGenericType() { var source0 = @"class A { class B<T> { } static object F() { return null; } }"; var source1 = @"class A { class B<T> { internal class C<U> { internal object F<V>() where V : T, new() { return new C<V>(); } } } static object F() { return new B<A>.C<B<object>>().F<A>(); } }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var f0 = compilation0.GetMember<MethodSymbol>("A.F"); var f1 = compilation1.GetMember<MethodSymbol>("A.F"); var c1 = compilation1.GetMember<NamedTypeSymbol>("A.B.C"); // Verify full metadata contains expected rows. var bytes0 = compilation0.EmitToArray(); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var reader0 = md0.MetadataReader; CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "A", "B`1"); Assert.Equal(1, reader0.GetTableRowCount(TableIndex.NestedClass)); var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Insert, null, c1), SemanticEdit.Create(SemanticEditKind.Update, f0, f1))); // Verify delta metadata contains expected rows. using var md1 = diff1.GetMetadata(); var reader1 = md1.Reader; var readers = new[] { reader0, reader1 }; CheckNames(readers, diff1.EmitResult.ChangedTypes, "A", "B`1", "C`1"); CheckNames(readers, reader1.GetTypeDefNames(), "C`1"); Assert.Equal(1, reader1.GetTableRowCount(TableIndex.NestedClass)); CheckEncLog(reader1, Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default), Row(5, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(6, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(7, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(8, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(1, TableIndex.MethodSpec, EditAndContinueOperation.Default), Row(6, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(1, TableIndex.TypeSpec, EditAndContinueOperation.Default), Row(2, TableIndex.TypeSpec, EditAndContinueOperation.Default), Row(3, TableIndex.TypeSpec, EditAndContinueOperation.Default), Row(2, TableIndex.StandAloneSig, EditAndContinueOperation.Default), Row(4, TableIndex.TypeDef, EditAndContinueOperation.Default), Row(1, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(4, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(4, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(4, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(5, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(2, TableIndex.NestedClass, EditAndContinueOperation.Default), Row(2, TableIndex.GenericParam, EditAndContinueOperation.Default), Row(3, TableIndex.GenericParam, EditAndContinueOperation.Default), Row(4, TableIndex.GenericParam, EditAndContinueOperation.Default), Row(1, TableIndex.GenericParamConstraint, EditAndContinueOperation.Default)); CheckEncMap(reader1, Handle(6, TableIndex.TypeRef), Handle(4, TableIndex.TypeDef), Handle(1, TableIndex.MethodDef), Handle(4, TableIndex.MethodDef), Handle(5, TableIndex.MethodDef), Handle(5, TableIndex.MemberRef), Handle(6, TableIndex.MemberRef), Handle(7, TableIndex.MemberRef), Handle(8, TableIndex.MemberRef), Handle(2, TableIndex.StandAloneSig), Handle(1, TableIndex.TypeSpec), Handle(2, TableIndex.TypeSpec), Handle(3, TableIndex.TypeSpec), Handle(2, TableIndex.AssemblyRef), Handle(2, TableIndex.NestedClass), Handle(2, TableIndex.GenericParam), Handle(3, TableIndex.GenericParam), Handle(4, TableIndex.GenericParam), Handle(1, TableIndex.MethodSpec), Handle(1, TableIndex.GenericParamConstraint)); } [Fact] [WorkItem(54939, "https://github.com/dotnet/roslyn/issues/54939")] public void AddNamespace() { var source0 = @" class C { static void Main() { } }"; var source1 = @" namespace N1.N2 { class D { public static void F() { } } } class C { static void Main() => N1.N2.D.F(); }"; var source2 = @" namespace N1.N2 { class D { public static void F() { } } namespace M1.M2 { class E { public static void G() { } } } } class C { static void Main() => N1.N2.M1.M2.E.G(); }"; var compilation0 = CreateCompilation(source0, options: ComSafeDebugDll); var compilation1 = compilation0.WithSource(source1); var compilation2 = compilation1.WithSource(source2); var main0 = compilation0.GetMember<MethodSymbol>("C.Main"); var main1 = compilation1.GetMember<MethodSymbol>("C.Main"); var main2 = compilation2.GetMember<MethodSymbol>("C.Main"); var d1 = compilation1.GetMember<NamedTypeSymbol>("N1.N2.D"); var e2 = compilation2.GetMember<NamedTypeSymbol>("N1.N2.M1.M2.E"); using var md0 = ModuleMetadata.CreateFromImage(compilation0.EmitToArray()); var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, main0, main1), SemanticEdit.Create(SemanticEditKind.Insert, null, d1))); diff1.VerifyIL("C.Main", @" { // Code size 7 (0x7) .maxstack 0 IL_0000: call ""void N1.N2.D.F()"" IL_0005: nop IL_0006: ret }"); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, main1, main2), SemanticEdit.Create(SemanticEditKind.Insert, null, e2))); diff2.VerifyIL("C.Main", @" { // Code size 7 (0x7) .maxstack 0 IL_0000: call ""void N1.N2.M1.M2.E.G()"" IL_0005: nop IL_0006: ret }"); } [Fact] public void ModifyExplicitImplementation() { var source = @"interface I { void M(); } class C : I { void I.M() { } }"; var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source); var method0 = compilation0.GetMember<NamedTypeSymbol>("C").GetMethod("I.M"); var method1 = compilation1.GetMember<NamedTypeSymbol>("C").GetMethod("I.M"); // Verify full metadata contains expected rows. var bytes0 = compilation0.EmitToArray(); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var reader0 = md0.MetadataReader; CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "I", "C"); CheckNames(reader0, reader0.GetMethodDefNames(), "M", "I.M", ".ctor"); var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1))); // Verify delta metadata contains expected rows. using var block1 = diff1.GetMetadata(); var reader1 = block1.Reader; var readers = new[] { reader0, reader1 }; EncValidation.VerifyModuleMvid(1, reader0, reader1); CheckNames(readers, reader1.GetTypeDefNames()); CheckNames(readers, reader1.GetMethodDefNames(), "I.M"); CheckEncLog(reader1, Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default), Row(6, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(2, TableIndex.MethodDef, EditAndContinueOperation.Default)); CheckEncMap(reader1, Handle(6, TableIndex.TypeRef), Handle(2, TableIndex.MethodDef), Handle(2, TableIndex.AssemblyRef)); } [Fact] public void AddThenModifyExplicitImplementation() { var source0 = @"interface I { void M(); } class A : I { void I.M() { } } class B : I { public void M() { } }"; var source1 = @"interface I { void M(); } class A : I { void I.M() { } } class B : I { public void M() { } void I.M() { } }"; var source2 = source1; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var compilation2 = compilation0.WithSource(source2); var method1 = compilation1.GetMember<NamedTypeSymbol>("B").GetMethod("I.M"); var method2 = compilation2.GetMember<NamedTypeSymbol>("B").GetMethod("I.M"); var bytes0 = compilation0.EmitToArray(); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var reader0 = md0.MetadataReader; var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Insert, null, method1))); using var block1 = diff1.GetMetadata(); var reader1 = block1.Reader; var readers = new List<MetadataReader> { reader0, reader1 }; EncValidation.VerifyModuleMvid(1, reader0, reader1); CheckNames(readers, reader1.GetMethodDefNames(), "I.M"); CheckEncLog(reader1, Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default), Row(6, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(4, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(6, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(2, TableIndex.MethodImpl, EditAndContinueOperation.Default)); CheckEncMap(reader1, Handle(6, TableIndex.TypeRef), Handle(6, TableIndex.MethodDef), Handle(2, TableIndex.MethodImpl), Handle(2, TableIndex.AssemblyRef)); var generation1 = diff1.NextGeneration; var diff2 = compilation2.EmitDifference( generation1, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method1, method2))); using var md2 = diff2.GetMetadata(); var reader2 = md2.Reader; readers.Add(reader2); EncValidation.VerifyModuleMvid(2, reader1, reader2); CheckNames(readers, reader2.GetMethodDefNames(), "I.M"); CheckEncLog(reader2, Row(3, TableIndex.AssemblyRef, EditAndContinueOperation.Default), Row(7, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(6, TableIndex.MethodDef, EditAndContinueOperation.Default)); CheckEncMap(reader2, Handle(7, TableIndex.TypeRef), Handle(6, TableIndex.MethodDef), Handle(3, TableIndex.AssemblyRef)); } [WorkItem(930065, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/930065")] [Fact] public void ModifyConstructorBodyInPresenceOfExplicitInterfaceImplementation() { var source = @" interface I { void M(); } class C : I { public C() { } void I.M() { } } "; var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source); var method0 = compilation0.GetMember<NamedTypeSymbol>("C").InstanceConstructors.Single(); var method1 = compilation1.GetMember<NamedTypeSymbol>("C").InstanceConstructors.Single(); var bytes0 = compilation0.EmitToArray(); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var reader0 = md0.MetadataReader; var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1))); using var block1 = diff1.GetMetadata(); var reader1 = block1.Reader; var readers = new[] { reader0, reader1 }; EncValidation.VerifyModuleMvid(1, reader0, reader1); CheckNames(readers, reader1.GetTypeDefNames()); CheckNames(readers, reader1.GetMethodDefNames(), ".ctor"); CheckEncLog(reader1, Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default), Row(5, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(6, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(2, TableIndex.MethodDef, EditAndContinueOperation.Default)); CheckEncMap(reader1, Handle(6, TableIndex.TypeRef), Handle(2, TableIndex.MethodDef), Handle(5, TableIndex.MemberRef), Handle(2, TableIndex.AssemblyRef)); } [Fact] public void AddAndModifyInterfaceMembers() { var source0 = @" using System; interface I { }"; var source1 = @" using System; interface I { static int X = 10; static event Action Y; static void M() { } void N() { } static int P { get => 1; set { } } int Q { get => 1; set { } } static event Action E { add { } remove { } } event Action F { add { } remove { } } interface J { } }"; var source2 = @" using System; interface I { static int X = 2; static event Action Y; static I() { X--; } static void M() { X++; } void N() { X++; } static int P { get => 3; set { X++; } } int Q { get => 3; set { X++; } } static event Action E { add { X++; } remove { X++; } } event Action F { add { X++; } remove { X++; } } interface J { } }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll, targetFramework: TargetFramework.NetCoreApp); var compilation1 = compilation0.WithSource(source1); var compilation2 = compilation1.WithSource(source2); var x1 = compilation1.GetMember<FieldSymbol>("I.X"); var y1 = compilation1.GetMember<EventSymbol>("I.Y"); var m1 = compilation1.GetMember<MethodSymbol>("I.M"); var n1 = compilation1.GetMember<MethodSymbol>("I.N"); var p1 = compilation1.GetMember<PropertySymbol>("I.P"); var q1 = compilation1.GetMember<PropertySymbol>("I.Q"); var e1 = compilation1.GetMember<EventSymbol>("I.E"); var f1 = compilation1.GetMember<EventSymbol>("I.F"); var j1 = compilation1.GetMember<NamedTypeSymbol>("I.J"); var getP1 = compilation1.GetMember<MethodSymbol>("I.get_P"); var setP1 = compilation1.GetMember<MethodSymbol>("I.set_P"); var getQ1 = compilation1.GetMember<MethodSymbol>("I.get_Q"); var setQ1 = compilation1.GetMember<MethodSymbol>("I.set_Q"); var addE1 = compilation1.GetMember<MethodSymbol>("I.add_E"); var removeE1 = compilation1.GetMember<MethodSymbol>("I.remove_E"); var addF1 = compilation1.GetMember<MethodSymbol>("I.add_F"); var removeF1 = compilation1.GetMember<MethodSymbol>("I.remove_F"); var cctor1 = compilation1.GetMember<NamedTypeSymbol>("I").StaticConstructors.Single(); var x2 = compilation2.GetMember<FieldSymbol>("I.X"); var m2 = compilation2.GetMember<MethodSymbol>("I.M"); var n2 = compilation2.GetMember<MethodSymbol>("I.N"); var getP2 = compilation2.GetMember<MethodSymbol>("I.get_P"); var setP2 = compilation2.GetMember<MethodSymbol>("I.set_P"); var getQ2 = compilation2.GetMember<MethodSymbol>("I.get_Q"); var setQ2 = compilation2.GetMember<MethodSymbol>("I.set_Q"); var addE2 = compilation2.GetMember<MethodSymbol>("I.add_E"); var removeE2 = compilation2.GetMember<MethodSymbol>("I.remove_E"); var addF2 = compilation2.GetMember<MethodSymbol>("I.add_F"); var removeF2 = compilation2.GetMember<MethodSymbol>("I.remove_F"); var cctor2 = compilation2.GetMember<NamedTypeSymbol>("I").StaticConstructors.Single(); var bytes0 = compilation0.EmitToArray(); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var reader0 = md0.MetadataReader; var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Insert, null, x1), SemanticEdit.Create(SemanticEditKind.Insert, null, y1), SemanticEdit.Create(SemanticEditKind.Insert, null, m1), SemanticEdit.Create(SemanticEditKind.Insert, null, n1), SemanticEdit.Create(SemanticEditKind.Insert, null, p1), SemanticEdit.Create(SemanticEditKind.Insert, null, q1), SemanticEdit.Create(SemanticEditKind.Insert, null, e1), SemanticEdit.Create(SemanticEditKind.Insert, null, f1), SemanticEdit.Create(SemanticEditKind.Insert, null, j1), SemanticEdit.Create(SemanticEditKind.Insert, null, cctor1))); using var md1 = diff1.GetMetadata(); var reader1 = md1.Reader; var readers = new[] { reader0, reader1 }; CheckNames(readers, diff1.EmitResult.ChangedTypes, "I", "J"); CheckNames(readers, reader1.GetTypeDefNames(), "J"); CheckNames(readers, reader1.GetFieldDefNames(), "X", "Y"); CheckNames(readers, reader1.GetMethodDefNames(), "add_Y", "remove_Y", "M", "N", "get_P", "set_P", "get_Q", "set_Q", "add_E", "remove_E", "add_F", "remove_F", ".cctor"); Assert.Equal(1, reader1.GetTableRowCount(TableIndex.NestedClass)); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, x1, x2), SemanticEdit.Create(SemanticEditKind.Update, m1, m2), SemanticEdit.Create(SemanticEditKind.Update, n1, n2), SemanticEdit.Create(SemanticEditKind.Update, getP1, getP2), SemanticEdit.Create(SemanticEditKind.Update, setP1, setP2), SemanticEdit.Create(SemanticEditKind.Update, getQ1, getQ2), SemanticEdit.Create(SemanticEditKind.Update, setQ1, setQ2), SemanticEdit.Create(SemanticEditKind.Update, addE1, addE2), SemanticEdit.Create(SemanticEditKind.Update, removeE1, removeE2), SemanticEdit.Create(SemanticEditKind.Update, addF1, addF2), SemanticEdit.Create(SemanticEditKind.Update, removeF1, removeF2), SemanticEdit.Create(SemanticEditKind.Update, cctor1, cctor2))); using var md2 = diff2.GetMetadata(); var reader2 = md2.Reader; readers = new[] { reader0, reader1, reader2 }; CheckNames(readers, diff1.EmitResult.ChangedTypes, "I", "J"); CheckNames(readers, reader2.GetTypeDefNames()); CheckNames(readers, reader2.GetFieldDefNames(), "X"); CheckNames(readers, reader2.GetMethodDefNames(), "M", "N", "get_P", "set_P", "get_Q", "set_Q", "add_E", "remove_E", "add_F", "remove_F", ".cctor"); Assert.Equal(0, reader2.GetTableRowCount(TableIndex.NestedClass)); CheckEncLog(reader2, Row(3, TableIndex.AssemblyRef, EditAndContinueOperation.Default), Row(10, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(2, TableIndex.Event, EditAndContinueOperation.Default), Row(3, TableIndex.Event, EditAndContinueOperation.Default), Row(1, TableIndex.Field, EditAndContinueOperation.Default), Row(3, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(4, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(5, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(6, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(7, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(8, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(9, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(10, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(11, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(12, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(13, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(1, TableIndex.Property, EditAndContinueOperation.Default), Row(2, TableIndex.Property, EditAndContinueOperation.Default), Row(3, TableIndex.Param, EditAndContinueOperation.Default), Row(4, TableIndex.Param, EditAndContinueOperation.Default), Row(5, TableIndex.Param, EditAndContinueOperation.Default), Row(6, TableIndex.Param, EditAndContinueOperation.Default), Row(7, TableIndex.Param, EditAndContinueOperation.Default), Row(8, TableIndex.Param, EditAndContinueOperation.Default), Row(11, TableIndex.MethodSemantics, EditAndContinueOperation.Default), Row(12, TableIndex.MethodSemantics, EditAndContinueOperation.Default), Row(13, TableIndex.MethodSemantics, EditAndContinueOperation.Default), Row(14, TableIndex.MethodSemantics, EditAndContinueOperation.Default), Row(15, TableIndex.MethodSemantics, EditAndContinueOperation.Default), Row(16, TableIndex.MethodSemantics, EditAndContinueOperation.Default), Row(17, TableIndex.MethodSemantics, EditAndContinueOperation.Default), Row(18, TableIndex.MethodSemantics, EditAndContinueOperation.Default)); diff2.VerifyIL(@" { // Code size 14 (0xe) .maxstack 8 IL_0000: nop IL_0001: ldsfld 0x04000001 IL_0006: ldc.i4.1 IL_0007: add IL_0008: stsfld 0x04000001 IL_000d: ret } { // Code size 2 (0x2) .maxstack 8 IL_0000: ldc.i4.3 IL_0001: ret } { // Code size 20 (0x14) .maxstack 8 IL_0000: ldc.i4.2 IL_0001: stsfld 0x04000001 IL_0006: nop IL_0007: ldsfld 0x04000001 IL_000c: ldc.i4.1 IL_000d: sub IL_000e: stsfld 0x04000001 IL_0013: ret } "); } [Fact] public void AddAttributeReferences() { var source0 = @"class A : System.Attribute { } class B : System.Attribute { } class C { [A] static void M1<[B]T>() { } [B] static object F1; [A] static object P1 { get { return null; } } [B] static event D E1; } delegate void D(); "; var source1 = @"class A : System.Attribute { } class B : System.Attribute { } class C { [A] static void M1<[B]T>() { } [B] static void M2<[A]T>() { } [B] static object F1; [A] static object F2; [A] static object P1 { get { return null; } } [B] static object P2 { get { return null; } } [B] static event D E1; [A] static event D E2; } delegate void D(); "; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); // Verify full metadata contains expected rows. var bytes0 = compilation0.EmitToArray(); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var reader0 = md0.MetadataReader; CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "A", "B", "C", "D"); CheckNames(reader0, reader0.GetMethodDefNames(), ".ctor", ".ctor", "M1", "get_P1", "add_E1", "remove_E1", ".ctor", ".ctor", "Invoke", "BeginInvoke", "EndInvoke"); CheckAttributes(reader0, new CustomAttributeRow(Handle(1, TableIndex.Field), Handle(2, TableIndex.MethodDef)), new CustomAttributeRow(Handle(1, TableIndex.Property), Handle(1, TableIndex.MethodDef)), new CustomAttributeRow(Handle(1, TableIndex.Event), Handle(2, TableIndex.MethodDef)), new CustomAttributeRow(Handle(1, TableIndex.Assembly), Handle(1, TableIndex.MemberRef)), new CustomAttributeRow(Handle(1, TableIndex.Assembly), Handle(2, TableIndex.MemberRef)), new CustomAttributeRow(Handle(1, TableIndex.Assembly), Handle(3, TableIndex.MemberRef)), new CustomAttributeRow(Handle(1, TableIndex.GenericParam), Handle(2, TableIndex.MethodDef)), new CustomAttributeRow(Handle(2, TableIndex.Field), Handle(4, TableIndex.MemberRef)), new CustomAttributeRow(Handle(2, TableIndex.Field), Handle(5, TableIndex.MemberRef)), new CustomAttributeRow(Handle(3, TableIndex.MethodDef), Handle(1, TableIndex.MethodDef)), new CustomAttributeRow(Handle(5, TableIndex.MethodDef), Handle(4, TableIndex.MemberRef)), new CustomAttributeRow(Handle(6, TableIndex.MethodDef), Handle(4, TableIndex.MemberRef))); var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Insert, null, compilation1.GetMember<MethodSymbol>("C.M2")), SemanticEdit.Create(SemanticEditKind.Insert, null, compilation1.GetMember<FieldSymbol>("C.F2")), SemanticEdit.Create(SemanticEditKind.Insert, null, compilation1.GetMember<PropertySymbol>("C.P2")), SemanticEdit.Create(SemanticEditKind.Insert, null, compilation1.GetMember<EventSymbol>("C.E2")))); // Verify delta metadata contains expected rows. using var md1 = diff1.GetMetadata(); var reader1 = md1.Reader; var readers = new[] { reader0, reader1 }; CheckNames(readers, diff1.EmitResult.ChangedTypes, "C"); CheckNames(readers, reader1.GetTypeDefNames()); CheckNames(readers, reader1.GetMethodDefNames(), "M2", "get_P2", "add_E2", "remove_E2"); CheckEncLogDefinitions(reader1, Row(3, TableIndex.StandAloneSig, EditAndContinueOperation.Default), Row(4, TableIndex.StandAloneSig, EditAndContinueOperation.Default), Row(1, TableIndex.EventMap, EditAndContinueOperation.AddEvent), Row(2, TableIndex.Event, EditAndContinueOperation.Default), Row(4, TableIndex.TypeDef, EditAndContinueOperation.AddField), Row(3, TableIndex.Field, EditAndContinueOperation.Default), Row(4, TableIndex.TypeDef, EditAndContinueOperation.AddField), Row(4, TableIndex.Field, EditAndContinueOperation.Default), Row(4, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(12, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(4, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(13, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(4, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(14, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(4, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(15, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(1, TableIndex.PropertyMap, EditAndContinueOperation.AddProperty), Row(2, TableIndex.Property, EditAndContinueOperation.Default), Row(14, TableIndex.MethodDef, EditAndContinueOperation.AddParameter), Row(8, TableIndex.Param, EditAndContinueOperation.Default), Row(15, TableIndex.MethodDef, EditAndContinueOperation.AddParameter), Row(9, TableIndex.Param, EditAndContinueOperation.Default), Row(7, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(13, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(14, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(15, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(16, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(17, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(18, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(19, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(20, TableIndex.CustomAttribute, EditAndContinueOperation.Default), Row(4, TableIndex.MethodSemantics, EditAndContinueOperation.Default), Row(5, TableIndex.MethodSemantics, EditAndContinueOperation.Default), Row(6, TableIndex.MethodSemantics, EditAndContinueOperation.Default), Row(2, TableIndex.GenericParam, EditAndContinueOperation.Default)); CheckEncMapDefinitions(reader1, Handle(3, TableIndex.Field), Handle(4, TableIndex.Field), Handle(12, TableIndex.MethodDef), Handle(13, TableIndex.MethodDef), Handle(14, TableIndex.MethodDef), Handle(15, TableIndex.MethodDef), Handle(8, TableIndex.Param), Handle(9, TableIndex.Param), Handle(7, TableIndex.CustomAttribute), Handle(13, TableIndex.CustomAttribute), Handle(14, TableIndex.CustomAttribute), Handle(15, TableIndex.CustomAttribute), Handle(16, TableIndex.CustomAttribute), Handle(17, TableIndex.CustomAttribute), Handle(18, TableIndex.CustomAttribute), Handle(19, TableIndex.CustomAttribute), Handle(20, TableIndex.CustomAttribute), Handle(3, TableIndex.StandAloneSig), Handle(4, TableIndex.StandAloneSig), Handle(2, TableIndex.Event), Handle(2, TableIndex.Property), Handle(4, TableIndex.MethodSemantics), Handle(5, TableIndex.MethodSemantics), Handle(6, TableIndex.MethodSemantics), Handle(2, TableIndex.GenericParam)); CheckAttributes(reader1, new CustomAttributeRow(Handle(1, TableIndex.GenericParam), Handle(1, TableIndex.MethodDef)), new CustomAttributeRow(Handle(2, TableIndex.Property), Handle(2, TableIndex.MethodDef)), new CustomAttributeRow(Handle(2, TableIndex.Event), Handle(1, TableIndex.MethodDef)), new CustomAttributeRow(Handle(3, TableIndex.Field), Handle(1, TableIndex.MethodDef)), new CustomAttributeRow(Handle(4, TableIndex.Field), Handle(11, TableIndex.MemberRef)), new CustomAttributeRow(Handle(4, TableIndex.Field), Handle(12, TableIndex.MemberRef)), new CustomAttributeRow(Handle(12, TableIndex.MethodDef), Handle(2, TableIndex.MethodDef)), new CustomAttributeRow(Handle(14, TableIndex.MethodDef), Handle(11, TableIndex.MemberRef)), new CustomAttributeRow(Handle(15, TableIndex.MethodDef), Handle(11, TableIndex.MemberRef))); } /// <summary> /// [assembly: ...] and [module: ...] attributes should /// not be included in delta metadata. /// </summary> [Fact] public void AssemblyAndModuleAttributeReferences() { var source0 = @"[assembly: System.CLSCompliantAttribute(true)] [module: System.CLSCompliantAttribute(true)] class C { }"; var source1 = @"[assembly: System.CLSCompliantAttribute(true)] [module: System.CLSCompliantAttribute(true)] class C { static void M() { } }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); // Verify full metadata contains expected rows. var bytes0 = compilation0.EmitToArray(); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var reader0 = md0.MetadataReader; CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "C"); var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Insert, null, compilation1.GetMember<MethodSymbol>("C.M")))); // Verify delta metadata contains expected rows. using var md1 = diff1.GetMetadata(); var readers = new[] { reader0, md1.Reader }; CheckNames(readers, diff1.EmitResult.ChangedTypes, "C"); CheckNames(readers, md1.Reader.GetTypeDefNames()); CheckNames(readers, md1.Reader.GetMethodDefNames(), "M"); CheckEncLog(md1.Reader, Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default), Row(7, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(2, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(2, TableIndex.MethodDef, EditAndContinueOperation.Default)); // C.M CheckEncMap(md1.Reader, Handle(7, TableIndex.TypeRef), Handle(2, TableIndex.MethodDef), Handle(2, TableIndex.AssemblyRef)); } [Fact] public void OtherReferences() { var source0 = @"delegate void D(); class C { object F; object P { get { return null; } } event D E; void M() { } }"; var source1 = @"delegate void D(); class C { object F; object P { get { return null; } } event D E; void M() { object o; o = typeof(D); o = F; o = P; E += null; } }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); // Verify full metadata contains expected rows. var bytes0 = compilation0.EmitToArray(); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var reader0 = md0.MetadataReader; CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "D", "C"); CheckNames(reader0, reader0.GetEventDefNames(), "E"); CheckNames(reader0, reader0.GetFieldDefNames(), "F", "E"); CheckNames(reader0, reader0.GetMethodDefNames(), ".ctor", "Invoke", "BeginInvoke", "EndInvoke", "get_P", "add_E", "remove_E", "M", ".ctor"); CheckNames(reader0, reader0.GetPropertyDefNames(), "P"); var method0 = compilation0.GetMember<MethodSymbol>("C.M"); // Emit delta metadata. var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider); var method1 = compilation1.GetMember<MethodSymbol>("C.M"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true))); // Verify delta metadata contains expected rows. using var md1 = diff1.GetMetadata(); var reader1 = md1.Reader; var readers = new[] { reader0, reader1 }; CheckNames(readers, diff1.EmitResult.ChangedTypes, "C"); CheckNames(readers, reader1.GetTypeDefNames()); CheckNames(readers, reader1.GetEventDefNames()); CheckNames(readers, reader1.GetFieldDefNames()); CheckNames(readers, reader1.GetMethodDefNames(), "M"); CheckNames(readers, reader1.GetPropertyDefNames()); } [Fact] public void ArrayInitializer() { var source0 = WithWindowsLineBreaks(@" class C { static void M() { int[] a = new[] { 1, 2, 3 }; } }"); var source1 = WithWindowsLineBreaks(@" class C { static void M() { int[] a = new[] { 1, 2, 3, 4 }; } }"); var compilation0 = CreateCompilation(Parse(source0, "a.cs"), options: TestOptions.DebugDll); var compilation1 = compilation0.RemoveAllSyntaxTrees().AddSyntaxTrees(Parse(source1, "a.cs")); var testData0 = new CompilationTestData(); var bytes0 = compilation0.EmitToArray(testData: testData0); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var reader0 = md0.MetadataReader; var generation0 = EmitBaseline.CreateInitialBaseline( ModuleMetadata.CreateFromImage(bytes0), testData0.GetMethodData("C.M").EncDebugInfoProvider()); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, compilation0.GetMember("C.M"), compilation1.GetMember("C.M")))); var md1 = diff1.GetMetadata(); var reader1 = md1.Reader; var readers = new[] { reader0, reader1 }; CheckNames(readers, diff1.EmitResult.ChangedTypes, "C"); CheckEncLog(reader1, Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default), Row(12, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(13, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(2, TableIndex.StandAloneSig, EditAndContinueOperation.Default), Row(1, TableIndex.MethodDef, EditAndContinueOperation.Default)); CheckEncMap(reader1, Handle(12, TableIndex.TypeRef), Handle(13, TableIndex.TypeRef), Handle(1, TableIndex.MethodDef), Handle(2, TableIndex.StandAloneSig), Handle(2, TableIndex.AssemblyRef)); diff1.VerifyIL( @"{ // Code size 25 (0x19) .maxstack 4 IL_0000: nop IL_0001: ldc.i4.4 IL_0002: newarr 0x0100000D IL_0007: dup IL_0008: ldc.i4.0 IL_0009: ldc.i4.1 IL_000a: stelem.i4 IL_000b: dup IL_000c: ldc.i4.1 IL_000d: ldc.i4.2 IL_000e: stelem.i4 IL_000f: dup IL_0010: ldc.i4.2 IL_0011: ldc.i4.3 IL_0012: stelem.i4 IL_0013: dup IL_0014: ldc.i4.3 IL_0015: ldc.i4.4 IL_0016: stelem.i4 IL_0017: stloc.0 IL_0018: ret }"); diff1.VerifyPdb(new[] { 0x06000001 }, @"<symbols> <files> <file id=""1"" name=""a.cs"" language=""C#"" checksumAlgorithm=""SHA1"" checksum=""15-9B-5B-24-28-37-02-4F-D2-2E-40-DB-1A-89-9F-4D-54-D5-95-89"" /> </files> <methods> <method token=""0x6000001""> <customDebugInfo> <using> <namespace usingCount=""0"" /> </using> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""5"" startColumn=""5"" endLine=""5"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""6"" startColumn=""9"" endLine=""6"" endColumn=""40"" document=""1"" /> <entry offset=""0x18"" startLine=""7"" startColumn=""5"" endLine=""7"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x19""> <local name=""a"" il_index=""0"" il_start=""0x0"" il_end=""0x19"" attributes=""0"" /> </scope> </method> </methods> </symbols>"); } [Fact] public void PInvokeModuleRefAndImplMap() { var source0 = @"using System.Runtime.InteropServices; class C { [DllImport(""msvcrt.dll"")] public static extern int getchar(); }"; var source1 = @"using System.Runtime.InteropServices; class C { [DllImport(""msvcrt.dll"")] public static extern int getchar(); [DllImport(""msvcrt.dll"")] public static extern int puts(string s); }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var bytes0 = compilation0.EmitToArray(); var generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), EmptyLocalsProvider); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var reader0 = md0.MetadataReader; var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Insert, null, compilation1.GetMember<MethodSymbol>("C.puts")))); using var md1 = diff1.GetMetadata(); var reader1 = md1.Reader; var readers = new[] { reader0, reader1 }; CheckNames(readers, diff1.EmitResult.ChangedTypes, "C"); CheckEncLogDefinitions(reader1, Row(2, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(3, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(3, TableIndex.MethodDef, EditAndContinueOperation.AddParameter), Row(1, TableIndex.Param, EditAndContinueOperation.Default), Row(2, TableIndex.ImplMap, EditAndContinueOperation.Default)); CheckEncMapDefinitions(reader1, Handle(3, TableIndex.MethodDef), Handle(1, TableIndex.Param), Handle(2, TableIndex.ImplMap)); } /// <summary> /// ClassLayout and FieldLayout tables. /// </summary> [Fact] public void ClassAndFieldLayout() { var source0 = @"using System.Runtime.InteropServices; [StructLayout(LayoutKind.Explicit, Pack=2)] class A { [FieldOffset(0)]internal byte F; [FieldOffset(2)]internal byte G; }"; var source1 = @"using System.Runtime.InteropServices; [StructLayout(LayoutKind.Explicit, Pack=2)] class A { [FieldOffset(0)]internal byte F; [FieldOffset(2)]internal byte G; } [StructLayout(LayoutKind.Explicit, Pack=4)] class B { [FieldOffset(0)]internal short F; [FieldOffset(4)]internal short G; }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var bytes0 = compilation0.EmitToArray(); var generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), EmptyLocalsProvider); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Insert, null, compilation1.GetMember<NamedTypeSymbol>("B")))); using var md1 = diff1.GetMetadata(); var reader1 = md1.Reader; CheckEncLog(reader1, Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default), Row(5, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(6, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(3, TableIndex.TypeDef, EditAndContinueOperation.Default), Row(3, TableIndex.TypeDef, EditAndContinueOperation.AddField), Row(3, TableIndex.Field, EditAndContinueOperation.Default), Row(3, TableIndex.TypeDef, EditAndContinueOperation.AddField), Row(4, TableIndex.Field, EditAndContinueOperation.Default), Row(3, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(2, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(2, TableIndex.ClassLayout, EditAndContinueOperation.Default), Row(3, TableIndex.FieldLayout, EditAndContinueOperation.Default), Row(4, TableIndex.FieldLayout, EditAndContinueOperation.Default)); CheckEncMap(reader1, Handle(6, TableIndex.TypeRef), Handle(3, TableIndex.TypeDef), Handle(3, TableIndex.Field), Handle(4, TableIndex.Field), Handle(2, TableIndex.MethodDef), Handle(5, TableIndex.MemberRef), Handle(2, TableIndex.ClassLayout), Handle(3, TableIndex.FieldLayout), Handle(4, TableIndex.FieldLayout), Handle(2, TableIndex.AssemblyRef)); } [Fact] public void NamespacesAndOverloads() { var compilation0 = CreateCompilation(options: TestOptions.DebugDll, source: @"class C { } namespace N { class C { } } namespace M { class C { void M1(N.C o) { } void M1(M.C o) { } void M2(N.C a, M.C b, global::C c) { M1(a); } } }"); var method0 = compilation0.GetMember<MethodSymbol>("M.C.M2"); var bytes0 = compilation0.EmitToArray(); var generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), EmptyLocalsProvider); var compilation1 = compilation0.WithSource(@" class C { } namespace N { class C { } } namespace M { class C { void M1(N.C o) { } void M1(M.C o) { } void M1(global::C o) { } void M2(N.C a, M.C b, global::C c) { M1(a); M1(b); } } }"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Insert, null, compilation1.GetMembers("M.C.M1")[2]))); diff1.VerifyIL( @"{ // Code size 2 (0x2) .maxstack 8 IL_0000: nop IL_0001: ret }"); var compilation2 = compilation1.WithSource(@" class C { } namespace N { class C { } } namespace M { class C { void M1(N.C o) { } void M1(M.C o) { } void M1(global::C o) { } void M2(N.C a, M.C b, global::C c) { M1(a); M1(b); M1(c); } } }"); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, compilation1.GetMember<MethodSymbol>("M.C.M2"), compilation2.GetMember<MethodSymbol>("M.C.M2")))); diff2.VerifyIL( @"{ // Code size 26 (0x1a) .maxstack 8 IL_0000: nop IL_0001: ldarg.0 IL_0002: ldarg.1 IL_0003: call 0x06000002 IL_0008: nop IL_0009: ldarg.0 IL_000a: ldarg.2 IL_000b: call 0x06000003 IL_0010: nop IL_0011: ldarg.0 IL_0012: ldarg.3 IL_0013: call 0x06000007 IL_0018: nop IL_0019: ret }"); } [Fact] public void TypesAndOverloads() { const string source = @"using System; struct A<T> { internal class B<U> { } } class B { } class C { static void M(A<B>.B<object> a) { M(a); M((A<B>.B<B>)null); } static void M(A<B>.B<B> a) { M(a); M((A<B>.B<object>)null); } static void M(A<B> a) { M(a); M((A<B>?)a); } static void M(Nullable<A<B>> a) { M(a); M(a.Value); } unsafe static void M(int* p) { M(p); M((byte*)p); } unsafe static void M(byte* p) { M(p); M((int*)p); } static void M(B[][] b) { M(b); M((object[][])b); } static void M(object[][] b) { M(b); M((B[][])b); } static void M(A<B[]>.B<object> b) { M(b); M((A<B[, ,]>.B<object>)null); } static void M(A<B[, ,]>.B<object> b) { M(b); M((A<B[]>.B<object>)null); } static void M(dynamic d) { M(d); M((dynamic[])d); } static void M(dynamic[] d) { M(d); M((dynamic)d); } static void M<T>(A<int>.B<T> t) where T : B { M(t); M((A<double>.B<int>)null); } static void M<T>(A<double>.B<T> t) where T : struct { M(t); M((A<int>.B<B>)null); } }"; var options = TestOptions.UnsafeDebugDll; var compilation0 = CreateCompilation(source, options: options, references: new[] { CSharpRef }); var bytes0 = compilation0.EmitToArray(); var generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), EmptyLocalsProvider); var n = compilation0.GetMembers("C.M").Length; Assert.Equal(14, n); //static void M(A<B>.B<object> a) //{ // M(a); // M((A<B>.B<B>)null); //} var compilation1 = compilation0.WithSource(source); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, compilation0.GetMembers("C.M")[0], compilation1.GetMembers("C.M")[0]))); diff1.VerifyIL( @"{ // Code size 16 (0x10) .maxstack 8 IL_0000: nop IL_0001: ldarg.0 IL_0002: call 0x06000002 IL_0007: nop IL_0008: ldnull IL_0009: call 0x06000003 IL_000e: nop IL_000f: ret }"); //static void M(A<B>.B<B> a) //{ // M(a); // M((A<B>.B<object>)null); //} var compilation2 = compilation1.WithSource(source); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, compilation1.GetMembers("C.M")[1], compilation2.GetMembers("C.M")[1]))); diff2.VerifyIL( @"{ // Code size 16 (0x10) .maxstack 8 IL_0000: nop IL_0001: ldarg.0 IL_0002: call 0x06000003 IL_0007: nop IL_0008: ldnull IL_0009: call 0x06000002 IL_000e: nop IL_000f: ret }"); //static void M(A<B> a) //{ // M(a); // M((A<B>?)a); //} var compilation3 = compilation2.WithSource(source); var diff3 = compilation3.EmitDifference( diff2.NextGeneration, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, compilation2.GetMembers("C.M")[2], compilation3.GetMembers("C.M")[2]))); diff3.VerifyIL( @"{ // Code size 21 (0x15) .maxstack 8 IL_0000: nop IL_0001: ldarg.0 IL_0002: call 0x06000004 IL_0007: nop IL_0008: ldarg.0 IL_0009: newobj 0x0A000016 IL_000e: call 0x06000005 IL_0013: nop IL_0014: ret }"); //static void M(Nullable<A<B>> a) //{ // M(a); // M(a.Value); //} var compilation4 = compilation3.WithSource(source); var diff4 = compilation4.EmitDifference( diff3.NextGeneration, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, compilation3.GetMembers("C.M")[3], compilation4.GetMembers("C.M")[3]))); diff4.VerifyIL( @"{ // Code size 22 (0x16) .maxstack 8 IL_0000: nop IL_0001: ldarg.0 IL_0002: call 0x06000005 IL_0007: nop IL_0008: ldarga.s V_0 IL_000a: call 0x0A000017 IL_000f: call 0x06000004 IL_0014: nop IL_0015: ret }"); //unsafe static void M(int* p) //{ // M(p); // M((byte*)p); //} var compilation5 = compilation4.WithSource(source); var diff5 = compilation5.EmitDifference( diff4.NextGeneration, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, compilation4.GetMembers("C.M")[4], compilation5.GetMembers("C.M")[4]))); diff5.VerifyIL( @"{ // Code size 16 (0x10) .maxstack 8 IL_0000: nop IL_0001: ldarg.0 IL_0002: call 0x06000006 IL_0007: nop IL_0008: ldarg.0 IL_0009: call 0x06000007 IL_000e: nop IL_000f: ret }"); //unsafe static void M(byte* p) //{ // M(p); // M((int*)p); //} var compilation6 = compilation5.WithSource(source); var diff6 = compilation6.EmitDifference( diff5.NextGeneration, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, compilation5.GetMembers("C.M")[5], compilation6.GetMembers("C.M")[5]))); diff6.VerifyIL( @"{ // Code size 16 (0x10) .maxstack 8 IL_0000: nop IL_0001: ldarg.0 IL_0002: call 0x06000007 IL_0007: nop IL_0008: ldarg.0 IL_0009: call 0x06000006 IL_000e: nop IL_000f: ret }"); //static void M(B[][] b) //{ // M(b); // M((object[][])b); //} var compilation7 = compilation6.WithSource(source); var diff7 = compilation7.EmitDifference( diff6.NextGeneration, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, compilation6.GetMembers("C.M")[6], compilation7.GetMembers("C.M")[6]))); diff7.VerifyIL( @"{ // Code size 18 (0x12) .maxstack 1 IL_0000: nop IL_0001: ldarg.0 IL_0002: call 0x06000008 IL_0007: nop IL_0008: ldarg.0 IL_0009: stloc.0 IL_000a: ldloc.0 IL_000b: call 0x06000009 IL_0010: nop IL_0011: ret }"); //static void M(object[][] b) //{ // M(b); // M((B[][])b); //} var compilation8 = compilation7.WithSource(source); var diff8 = compilation8.EmitDifference( diff7.NextGeneration, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, compilation7.GetMembers("C.M")[7], compilation8.GetMembers("C.M")[7]))); diff8.VerifyIL( @"{ // Code size 21 (0x15) .maxstack 8 IL_0000: nop IL_0001: ldarg.0 IL_0002: call 0x06000009 IL_0007: nop IL_0008: ldarg.0 IL_0009: castclass 0x1B00000A IL_000e: call 0x06000008 IL_0013: nop IL_0014: ret }"); //static void M(A<B[]>.B<object> b) //{ // M(b); // M((A<B[,,]>.B<object>)null); //} var compilation9 = compilation8.WithSource(source); var diff9 = compilation9.EmitDifference( diff8.NextGeneration, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, compilation8.GetMembers("C.M")[8], compilation9.GetMembers("C.M")[8]))); diff9.VerifyIL( @"{ // Code size 16 (0x10) .maxstack 8 IL_0000: nop IL_0001: ldarg.0 IL_0002: call 0x0600000A IL_0007: nop IL_0008: ldnull IL_0009: call 0x0600000B IL_000e: nop IL_000f: ret }"); //static void M(A<B[,,]>.B<object> b) //{ // M(b); // M((A<B[]>.B<object>)null); //} var compilation10 = compilation9.WithSource(source); var diff10 = compilation10.EmitDifference( diff9.NextGeneration, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, compilation9.GetMembers("C.M")[9], compilation10.GetMembers("C.M")[9]))); diff10.VerifyIL( @"{ // Code size 16 (0x10) .maxstack 8 IL_0000: nop IL_0001: ldarg.0 IL_0002: call 0x0600000B IL_0007: nop IL_0008: ldnull IL_0009: call 0x0600000A IL_000e: nop IL_000f: ret }"); // TODO: dynamic #if false //static void M(dynamic d) //{ // M(d); // M((dynamic[])d); //} previousMethod = compilation.GetMembers("C.M")[10]; compilation = compilation0.WithSource(source); generation = compilation.EmitDifference( generation, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, previousMethod, compilation.GetMembers("C.M")[10])), @"{ // Code size 16 (0x10) .maxstack 8 IL_0000: nop IL_0001: ldarg.0 IL_0002: call 0x06000002 IL_0007: nop IL_0008: ldnull IL_0009: call 0x06000003 IL_000e: nop IL_000f: ret }"); //static void M(dynamic[] d) //{ // M(d); // M((dynamic)d); //} previousMethod = compilation.GetMembers("C.M")[11]; compilation = compilation0.WithSource(source); generation = compilation.EmitDifference( generation, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, previousMethod, compilation.GetMembers("C.M")[11])), @"{ // Code size 16 (0x10) .maxstack 8 IL_0000: nop IL_0001: ldarg.0 IL_0002: call 0x06000002 IL_0007: nop IL_0008: ldnull IL_0009: call 0x06000003 IL_000e: nop IL_000f: ret }"); #endif //static void M<T>(A<int>.B<T> t) where T : B //{ // M(t); // M((A<double>.B<int>)null); //} var compilation11 = compilation10.WithSource(source); var diff11 = compilation11.EmitDifference( diff10.NextGeneration, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, compilation10.GetMembers("C.M")[12], compilation11.GetMembers("C.M")[12]))); diff11.VerifyIL( @"{ // Code size 16 (0x10) .maxstack 8 IL_0000: nop IL_0001: ldarg.0 IL_0002: call 0x2B000005 IL_0007: nop IL_0008: ldnull IL_0009: call 0x2B000006 IL_000e: nop IL_000f: ret }"); //static void M<T>(A<double>.B<T> t) where T : struct //{ // M(t); // M((A<int>.B<B>)null); //} var compilation12 = compilation11.WithSource(source); var diff12 = compilation12.EmitDifference( diff11.NextGeneration, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, compilation11.GetMembers("C.M")[13], compilation12.GetMembers("C.M")[13]))); diff12.VerifyIL( @"{ // Code size 16 (0x10) .maxstack 8 IL_0000: nop IL_0001: ldarg.0 IL_0002: call 0x2B000007 IL_0007: nop IL_0008: ldnull IL_0009: call 0x2B000008 IL_000e: nop IL_000f: ret }"); } /// <summary> /// Types should be retained in deleted locals /// for correct alignment of remaining locals. /// </summary> [Fact] public void DeletedValueTypeLocal() { var source0 = @"struct S1 { internal S1(int a, int b) { A = a; B = b; } internal int A; internal int B; } struct S2 { internal S2(int c) { C = c; } internal int C; } class C { static void Main() { var x = new S1(1, 2); var y = new S2(3); System.Console.WriteLine(y.C); } }"; var source1 = @"struct S1 { internal S1(int a, int b) { A = a; B = b; } internal int A; internal int B; } struct S2 { internal S2(int c) { C = c; } internal int C; } class C { static void Main() { var y = new S2(3); System.Console.WriteLine(y.C); } }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugExe); var compilation1 = compilation0.WithSource(source1); var testData0 = new CompilationTestData(); var bytes0 = compilation0.EmitToArray(testData: testData0); var methodData0 = testData0.GetMethodData("C.Main"); var method0 = compilation0.GetMember<MethodSymbol>("C.Main"); var generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), methodData0.EncDebugInfoProvider()); testData0.GetMethodData("C.Main").VerifyIL( @" { // Code size 31 (0x1f) .maxstack 3 .locals init (S1 V_0, //x S2 V_1) //y IL_0000: nop IL_0001: ldloca.s V_0 IL_0003: ldc.i4.1 IL_0004: ldc.i4.2 IL_0005: call ""S1..ctor(int, int)"" IL_000a: ldloca.s V_1 IL_000c: ldc.i4.3 IL_000d: call ""S2..ctor(int)"" IL_0012: ldloc.1 IL_0013: ldfld ""int S2.C"" IL_0018: call ""void System.Console.WriteLine(int)"" IL_001d: nop IL_001e: ret }"); var method1 = compilation1.GetMember<MethodSymbol>("C.Main"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true))); diff1.VerifyIL("C.Main", @"{ // Code size 22 (0x16) .maxstack 2 .locals init ([unchanged] V_0, S2 V_1) //y IL_0000: nop IL_0001: ldloca.s V_1 IL_0003: ldc.i4.3 IL_0004: call ""S2..ctor(int)"" IL_0009: ldloc.1 IL_000a: ldfld ""int S2.C"" IL_000f: call ""void System.Console.WriteLine(int)"" IL_0014: nop IL_0015: ret }"); } /// <summary> /// Instance and static constructors synthesized for /// PrivateImplementationDetails should not be /// generated for delta. /// </summary> [Fact] public void PrivateImplementationDetails() { var source = @"class C { static int[] F = new int[] { 1, 2, 3 }; int[] G = new int[] { 4, 5, 6 }; int M(int index) { return F[index] + G[index]; } }"; var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source); var testData0 = new CompilationTestData(); var bytes0 = compilation0.EmitToArray(testData: testData0); using (var md0 = ModuleMetadata.CreateFromImage(bytes0)) { var reader0 = md0.MetadataReader; var typeNames = new[] { reader0 }.GetStrings(reader0.GetTypeDefNames()); Assert.NotNull(typeNames.FirstOrDefault(n => n.StartsWith("<PrivateImplementationDetails>", StringComparison.Ordinal))); } var methodData0 = testData0.GetMethodData("C.M"); var method0 = compilation0.GetMember<MethodSymbol>("C.M"); var generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), methodData0.EncDebugInfoProvider()); var method1 = compilation1.GetMember<MethodSymbol>("C.M"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true))); diff1.VerifyIL("C.M", @" { // Code size 22 (0x16) .maxstack 3 .locals init ([int] V_0, int V_1) IL_0000: nop IL_0001: ldsfld ""int[] C.F"" IL_0006: ldarg.1 IL_0007: ldelem.i4 IL_0008: ldarg.0 IL_0009: ldfld ""int[] C.G"" IL_000e: ldarg.1 IL_000f: ldelem.i4 IL_0010: add IL_0011: stloc.1 IL_0012: br.s IL_0014 IL_0014: ldloc.1 IL_0015: ret }"); } [WorkItem(780989, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/780989")] [WorkItem(829353, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/829353")] [Fact] public void PrivateImplementationDetails_ArrayInitializer_FromMetadata() { var source0 = @"class C { static void M() { int[] a = { 1, 2, 3 }; System.Console.WriteLine(a[0]); } }"; var source1 = @"class C { static void M() { int[] a = { 1, 2, 3 }; System.Console.WriteLine(a[1]); } }"; var source2 = @"class C { static void M() { int[] a = { 4, 5, 6, 7, 8, 9, 10 }; System.Console.WriteLine(a[1]); } }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll.WithModuleName("MODULE")); var compilation1 = compilation0.WithSource(source1); var compilation2 = compilation1.WithSource(source2); var testData0 = new CompilationTestData(); var bytes0 = compilation0.EmitToArray(testData: testData0); var methodData0 = testData0.GetMethodData("C.M"); methodData0.VerifyIL( @" { // Code size 29 (0x1d) .maxstack 3 .locals init (int[] V_0) //a IL_0000: nop IL_0001: ldc.i4.3 IL_0002: newarr ""int"" IL_0007: dup IL_0008: ldtoken ""<PrivateImplementationDetails>.__StaticArrayInitTypeSize=12 <PrivateImplementationDetails>.4636993D3E1DA4E9D6B8F87B79E8F7C6D018580D52661950EABC3845C5897A4D"" IL_000d: call ""void System.Runtime.CompilerServices.RuntimeHelpers.InitializeArray(System.Array, System.RuntimeFieldHandle)"" IL_0012: stloc.0 IL_0013: ldloc.0 IL_0014: ldc.i4.0 IL_0015: ldelem.i4 IL_0016: call ""void System.Console.WriteLine(int)"" IL_001b: nop IL_001c: ret } "); var method0 = compilation0.GetMember<MethodSymbol>("C.M"); var generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), methodData0.EncDebugInfoProvider()); var method1 = compilation1.GetMember<MethodSymbol>("C.M"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true))); diff1.VerifyIL("C.M", @"{ // Code size 30 (0x1e) .maxstack 4 .locals init (int[] V_0) //a IL_0000: nop IL_0001: ldc.i4.3 IL_0002: newarr ""int"" IL_0007: dup IL_0008: ldc.i4.0 IL_0009: ldc.i4.1 IL_000a: stelem.i4 IL_000b: dup IL_000c: ldc.i4.1 IL_000d: ldc.i4.2 IL_000e: stelem.i4 IL_000f: dup IL_0010: ldc.i4.2 IL_0011: ldc.i4.3 IL_0012: stelem.i4 IL_0013: stloc.0 IL_0014: ldloc.0 IL_0015: ldc.i4.1 IL_0016: ldelem.i4 IL_0017: call ""void System.Console.WriteLine(int)"" IL_001c: nop IL_001d: ret }"); var method2 = compilation2.GetMember<MethodSymbol>("C.M"); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method1, method2, GetEquivalentNodesMap(method2, method1), preserveLocalVariables: true))); diff2.VerifyIL("C.M", @"{ // Code size 48 (0x30) .maxstack 4 .locals init ([unchanged] V_0, int[] V_1) //a IL_0000: nop IL_0001: ldc.i4.7 IL_0002: newarr ""int"" IL_0007: dup IL_0008: ldc.i4.0 IL_0009: ldc.i4.4 IL_000a: stelem.i4 IL_000b: dup IL_000c: ldc.i4.1 IL_000d: ldc.i4.5 IL_000e: stelem.i4 IL_000f: dup IL_0010: ldc.i4.2 IL_0011: ldc.i4.6 IL_0012: stelem.i4 IL_0013: dup IL_0014: ldc.i4.3 IL_0015: ldc.i4.7 IL_0016: stelem.i4 IL_0017: dup IL_0018: ldc.i4.4 IL_0019: ldc.i4.8 IL_001a: stelem.i4 IL_001b: dup IL_001c: ldc.i4.5 IL_001d: ldc.i4.s 9 IL_001f: stelem.i4 IL_0020: dup IL_0021: ldc.i4.6 IL_0022: ldc.i4.s 10 IL_0024: stelem.i4 IL_0025: stloc.1 IL_0026: ldloc.1 IL_0027: ldc.i4.1 IL_0028: ldelem.i4 IL_0029: call ""void System.Console.WriteLine(int)"" IL_002e: nop IL_002f: ret }"); } [WorkItem(780989, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/780989")] [WorkItem(829353, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/829353")] [Fact] public void PrivateImplementationDetails_ArrayInitializer_FromSource() { // PrivateImplementationDetails not needed initially. var source0 = @"class C { static object F1() { return null; } static object F2() { return null; } static object F3() { return null; } static object F4() { return null; } }"; var source1 = @"class C { static object F1() { return new[] { 1, 2, 3 }; } static object F2() { return new[] { 4, 5, 6 }; } static object F3() { return null; } static object F4() { return new[] { 7, 8, 9 }; } }"; var source2 = @"class C { static object F1() { return new[] { 1, 2, 3 } ?? new[] { 10, 11, 12 }; } static object F2() { return new[] { 4, 5, 6 }; } static object F3() { return new[] { 13, 14, 15 }; } static object F4() { return new[] { 7, 8, 9 }; } }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var compilation2 = compilation1.WithSource(source2); var testData0 = new CompilationTestData(); var bytes0 = compilation0.EmitToArray(testData: testData0); var generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), EmptyLocalsProvider); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, compilation0.GetMember<MethodSymbol>("C.F1"), compilation1.GetMember<MethodSymbol>("C.F1")), SemanticEdit.Create(SemanticEditKind.Update, compilation0.GetMember<MethodSymbol>("C.F2"), compilation1.GetMember<MethodSymbol>("C.F2")), SemanticEdit.Create(SemanticEditKind.Update, compilation0.GetMember<MethodSymbol>("C.F4"), compilation1.GetMember<MethodSymbol>("C.F4")))); diff1.VerifyIL("C.F1", @"{ // Code size 24 (0x18) .maxstack 4 .locals init (object V_0) IL_0000: nop IL_0001: ldc.i4.3 IL_0002: newarr ""int"" IL_0007: dup IL_0008: ldc.i4.0 IL_0009: ldc.i4.1 IL_000a: stelem.i4 IL_000b: dup IL_000c: ldc.i4.1 IL_000d: ldc.i4.2 IL_000e: stelem.i4 IL_000f: dup IL_0010: ldc.i4.2 IL_0011: ldc.i4.3 IL_0012: stelem.i4 IL_0013: stloc.0 IL_0014: br.s IL_0016 IL_0016: ldloc.0 IL_0017: ret }"); diff1.VerifyIL("C.F4", @"{ // Code size 25 (0x19) .maxstack 4 .locals init (object V_0) IL_0000: nop IL_0001: ldc.i4.3 IL_0002: newarr ""int"" IL_0007: dup IL_0008: ldc.i4.0 IL_0009: ldc.i4.7 IL_000a: stelem.i4 IL_000b: dup IL_000c: ldc.i4.1 IL_000d: ldc.i4.8 IL_000e: stelem.i4 IL_000f: dup IL_0010: ldc.i4.2 IL_0011: ldc.i4.s 9 IL_0013: stelem.i4 IL_0014: stloc.0 IL_0015: br.s IL_0017 IL_0017: ldloc.0 IL_0018: ret }"); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, compilation1.GetMember<MethodSymbol>("C.F1"), compilation2.GetMember<MethodSymbol>("C.F1")), SemanticEdit.Create(SemanticEditKind.Update, compilation1.GetMember<MethodSymbol>("C.F3"), compilation2.GetMember<MethodSymbol>("C.F3")))); diff2.VerifyIL("C.F1", @"{ // Code size 49 (0x31) .maxstack 4 .locals init (object V_0) IL_0000: nop IL_0001: ldc.i4.3 IL_0002: newarr ""int"" IL_0007: dup IL_0008: ldc.i4.0 IL_0009: ldc.i4.1 IL_000a: stelem.i4 IL_000b: dup IL_000c: ldc.i4.1 IL_000d: ldc.i4.2 IL_000e: stelem.i4 IL_000f: dup IL_0010: ldc.i4.2 IL_0011: ldc.i4.3 IL_0012: stelem.i4 IL_0013: dup IL_0014: brtrue.s IL_002c IL_0016: pop IL_0017: ldc.i4.3 IL_0018: newarr ""int"" IL_001d: dup IL_001e: ldc.i4.0 IL_001f: ldc.i4.s 10 IL_0021: stelem.i4 IL_0022: dup IL_0023: ldc.i4.1 IL_0024: ldc.i4.s 11 IL_0026: stelem.i4 IL_0027: dup IL_0028: ldc.i4.2 IL_0029: ldc.i4.s 12 IL_002b: stelem.i4 IL_002c: stloc.0 IL_002d: br.s IL_002f IL_002f: ldloc.0 IL_0030: ret }"); diff2.VerifyIL("C.F3", @"{ // Code size 27 (0x1b) .maxstack 4 .locals init (object V_0) IL_0000: nop IL_0001: ldc.i4.3 IL_0002: newarr ""int"" IL_0007: dup IL_0008: ldc.i4.0 IL_0009: ldc.i4.s 13 IL_000b: stelem.i4 IL_000c: dup IL_000d: ldc.i4.1 IL_000e: ldc.i4.s 14 IL_0010: stelem.i4 IL_0011: dup IL_0012: ldc.i4.2 IL_0013: ldc.i4.s 15 IL_0015: stelem.i4 IL_0016: stloc.0 IL_0017: br.s IL_0019 IL_0019: ldloc.0 IL_001a: ret }"); } /// <summary> /// Should not generate method for string switch since /// the CLR only allows adding private members. /// </summary> [WorkItem(834086, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/834086")] [Fact] public void PrivateImplementationDetails_ComputeStringHash() { var source = @"class C { static int F(string s) { switch (s) { case ""1"": return 1; case ""2"": return 2; case ""3"": return 3; case ""4"": return 4; case ""5"": return 5; case ""6"": return 6; case ""7"": return 7; default: return 0; } } }"; const string ComputeStringHashName = "ComputeStringHash"; var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source); var testData0 = new CompilationTestData(); var bytes0 = compilation0.EmitToArray(testData: testData0); var methodData0 = testData0.GetMethodData("C.F"); var method0 = compilation0.GetMember<MethodSymbol>("C.F"); var generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), methodData0.EncDebugInfoProvider()); // Should have generated call to ComputeStringHash and // added the method to <PrivateImplementationDetails>. var actualIL0 = methodData0.GetMethodIL(); Assert.True(actualIL0.Contains(ComputeStringHashName)); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var reader0 = md0.MetadataReader; CheckNames(reader0, reader0.GetMethodDefNames(), "F", ".ctor", ComputeStringHashName); var method1 = compilation1.GetMember<MethodSymbol>("C.F"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true))); // Should not have generated call to ComputeStringHash nor // added the method to <PrivateImplementationDetails>. var actualIL1 = diff1.GetMethodIL("C.F"); Assert.False(actualIL1.Contains(ComputeStringHashName)); using var md1 = diff1.GetMetadata(); var reader1 = md1.Reader; var readers = new[] { reader0, reader1 }; CheckNames(readers, reader1.GetMethodDefNames(), "F"); } /// <summary> /// Unique ids should not conflict with ids /// from previous generation. /// </summary> [WorkItem(9847, "https://github.com/dotnet/roslyn/issues/9847")] [Fact(Skip = "https://github.com/dotnet/roslyn/issues/9847")] public void UniqueIds() { var source0 = @"class C { int F() { System.Func<int> f = () => 3; return f(); } static int F(bool b) { System.Func<int> f = () => 1; System.Func<int> g = () => 2; return (b ? f : g)(); } }"; var source1 = @"class C { int F() { System.Func<int> f = () => 3; return f(); } static int F(bool b) { System.Func<int> f = () => 1; return f(); } }"; var source2 = @"class C { int F() { System.Func<int> f = () => 3; return f(); } static int F(bool b) { System.Func<int> g = () => 2; return g(); } }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var compilation2 = compilation1.WithSource(source2); var testData0 = new CompilationTestData(); var bytes0 = compilation0.EmitToArray(testData: testData0); var generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), EmptyLocalsProvider); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, compilation0.GetMembers("C.F")[1], compilation1.GetMembers("C.F")[1]))); diff1.VerifyIL("C.F", @"{ // Code size 40 (0x28) .maxstack 2 .locals init (System.Func<int> V_0, //f int V_1) IL_0000: nop IL_0001: ldsfld ""System.Func<int> C.CS$<>9__CachedAnonymousMethodDelegate6"" IL_0006: dup IL_0007: brtrue.s IL_001c IL_0009: pop IL_000a: ldnull IL_000b: ldftn ""int C.<F>b__5()"" IL_0011: newobj ""System.Func<int>..ctor(object, System.IntPtr)"" IL_0016: dup IL_0017: stsfld ""System.Func<int> C.CS$<>9__CachedAnonymousMethodDelegate6"" IL_001c: stloc.0 IL_001d: ldloc.0 IL_001e: callvirt ""int System.Func<int>.Invoke()"" IL_0023: stloc.1 IL_0024: br.s IL_0026 IL_0026: ldloc.1 IL_0027: ret }"); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, compilation1.GetMembers("C.F")[1], compilation2.GetMembers("C.F")[1]))); diff2.VerifyIL("C.F", @"{ // Code size 40 (0x28) .maxstack 2 .locals init (System.Func<int> V_0, //g int V_1) IL_0000: nop IL_0001: ldsfld ""System.Func<int> C.CS$<>9__CachedAnonymousMethodDelegate8"" IL_0006: dup IL_0007: brtrue.s IL_001c IL_0009: pop IL_000a: ldnull IL_000b: ldftn ""int C.<F>b__7()"" IL_0011: newobj ""System.Func<int>..ctor(object, System.IntPtr)"" IL_0016: dup IL_0017: stsfld ""System.Func<int> C.CS$<>9__CachedAnonymousMethodDelegate8"" IL_001c: stloc.0 IL_001d: ldloc.0 IL_001e: callvirt ""int System.Func<int>.Invoke()"" IL_0023: stloc.1 IL_0024: br.s IL_0026 IL_0026: ldloc.1 IL_0027: ret }"); } /// <summary> /// Avoid adding references from method bodies /// other than the changed methods. /// </summary> [Fact] public void ReferencesInIL() { var source0 = @"class C { static void F() { System.Console.WriteLine(1); } static void G() { System.Console.WriteLine(2); } }"; var source1 = @"class C { static void F() { System.Console.WriteLine(1); } static void G() { System.Console.Write(2); } }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); // Verify full metadata contains expected rows. var bytes0 = compilation0.EmitToArray(); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var reader0 = md0.MetadataReader; CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "C"); CheckNames(reader0, reader0.GetMethodDefNames(), "F", "G", ".ctor"); CheckNames(reader0, reader0.GetMemberRefNames(), ".ctor", ".ctor", ".ctor", "WriteLine", ".ctor"); var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider); var method0 = compilation0.GetMember<MethodSymbol>("C.G"); var method1 = compilation1.GetMember<MethodSymbol>("C.G"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create( SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true))); // "Write" should be included in string table, but "WriteLine" should not. Assert.True(diff1.MetadataDelta.IsIncluded("Write")); Assert.False(diff1.MetadataDelta.IsIncluded("WriteLine")); } /// <summary> /// Local slots must be preserved based on signature. /// </summary> [Fact] public void PreserveLocalSlots() { var source0 = @"class A<T> { } class B : A<B> { static B F() { return null; } static void M(object o) { object x = F(); A<B> y = F(); object z = F(); M(x); M(y); M(z); } static void N() { object a = F(); object b = F(); M(a); M(b); } }"; var methodNames0 = new[] { "A<T>..ctor", "B.F", "B.M", "B.N" }; var source1 = @"class A<T> { } class B : A<B> { static B F() { return null; } static void M(object o) { B z = F(); A<B> y = F(); object w = F(); M(w); M(y); } static void N() { object a = F(); object b = F(); M(a); M(b); } }"; var source2 = @"class A<T> { } class B : A<B> { static B F() { return null; } static void M(object o) { object x = F(); B z = F(); M(x); M(z); } static void N() { object a = F(); object b = F(); M(a); M(b); } }"; var source3 = @"class A<T> { } class B : A<B> { static B F() { return null; } static void M(object o) { object x = F(); B z = F(); M(x); M(z); } static void N() { object c = F(); object b = F(); M(c); M(b); } }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var compilation2 = compilation1.WithSource(source2); var compilation3 = compilation2.WithSource(source3); var method0 = compilation0.GetMember<MethodSymbol>("B.M"); var methodN = compilation0.GetMember<MethodSymbol>("B.N"); var testData0 = new CompilationTestData(); var bytes0 = compilation0.EmitToArray(testData: testData0); var generation0 = EmitBaseline.CreateInitialBaseline( ModuleMetadata.CreateFromImage(bytes0), m => testData0.GetMethodData(methodNames0[MetadataTokens.GetRowNumber(m) - 1]).GetEncDebugInfo()); #region Gen1 var method1 = compilation1.GetMember<MethodSymbol>("B.M"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true))); diff1.VerifyIL( @"{ // Code size 36 (0x24) .maxstack 1 IL_0000: nop IL_0001: call 0x06000002 IL_0006: stloc.3 IL_0007: call 0x06000002 IL_000c: stloc.1 IL_000d: call 0x06000002 IL_0012: stloc.s V_4 IL_0014: ldloc.s V_4 IL_0016: call 0x06000003 IL_001b: nop IL_001c: ldloc.1 IL_001d: call 0x06000003 IL_0022: nop IL_0023: ret }"); diff1.VerifyPdb(new[] { 0x06000001, 0x06000002, 0x06000003, 0x06000004 }, @" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method token=""0x6000003""> <customDebugInfo> <using> <namespace usingCount=""0"" /> </using> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""9"" startColumn=""5"" endLine=""9"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""10"" startColumn=""9"" endLine=""10"" endColumn=""19"" document=""1"" /> <entry offset=""0x7"" startLine=""11"" startColumn=""9"" endLine=""11"" endColumn=""22"" document=""1"" /> <entry offset=""0xd"" startLine=""12"" startColumn=""9"" endLine=""12"" endColumn=""24"" document=""1"" /> <entry offset=""0x14"" startLine=""13"" startColumn=""9"" endLine=""13"" endColumn=""14"" document=""1"" /> <entry offset=""0x1c"" startLine=""14"" startColumn=""9"" endLine=""14"" endColumn=""14"" document=""1"" /> <entry offset=""0x23"" startLine=""15"" startColumn=""5"" endLine=""15"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x24""> <local name=""z"" il_index=""3"" il_start=""0x0"" il_end=""0x24"" attributes=""0"" /> <local name=""y"" il_index=""1"" il_start=""0x0"" il_end=""0x24"" attributes=""0"" /> <local name=""w"" il_index=""4"" il_start=""0x0"" il_end=""0x24"" attributes=""0"" /> </scope> </method> </methods> </symbols>"); #endregion #region Gen2 var method2 = compilation2.GetMember<MethodSymbol>("B.M"); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method1, method2, GetEquivalentNodesMap(method2, method1), preserveLocalVariables: true))); diff2.VerifyIL( @"{ // Code size 30 (0x1e) .maxstack 1 IL_0000: nop IL_0001: call 0x06000002 IL_0006: stloc.s V_5 IL_0008: call 0x06000002 IL_000d: stloc.3 IL_000e: ldloc.s V_5 IL_0010: call 0x06000003 IL_0015: nop IL_0016: ldloc.3 IL_0017: call 0x06000003 IL_001c: nop IL_001d: ret }"); diff2.VerifyPdb(new[] { 0x06000001, 0x06000002, 0x06000003, 0x06000004 }, @" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method token=""0x6000003""> <customDebugInfo> <using> <namespace usingCount=""0"" /> </using> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""9"" startColumn=""5"" endLine=""9"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""10"" startColumn=""9"" endLine=""10"" endColumn=""24"" document=""1"" /> <entry offset=""0x8"" startLine=""11"" startColumn=""9"" endLine=""11"" endColumn=""19"" document=""1"" /> <entry offset=""0xe"" startLine=""12"" startColumn=""9"" endLine=""12"" endColumn=""14"" document=""1"" /> <entry offset=""0x16"" startLine=""13"" startColumn=""9"" endLine=""13"" endColumn=""14"" document=""1"" /> <entry offset=""0x1d"" startLine=""14"" startColumn=""5"" endLine=""14"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x1e""> <local name=""x"" il_index=""5"" il_start=""0x0"" il_end=""0x1e"" attributes=""0"" /> <local name=""z"" il_index=""3"" il_start=""0x0"" il_end=""0x1e"" attributes=""0"" /> </scope> </method> </methods> </symbols>"); #endregion #region Gen3 // Modify different method. (Previous generations // have not referenced method.) method2 = compilation2.GetMember<MethodSymbol>("B.N"); var method3 = compilation3.GetMember<MethodSymbol>("B.N"); var diff3 = compilation3.EmitDifference( diff2.NextGeneration, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method2, method3, GetEquivalentNodesMap(method3, method2), preserveLocalVariables: true))); diff3.VerifyIL( @"{ // Code size 28 (0x1c) .maxstack 1 IL_0000: nop IL_0001: call 0x06000002 IL_0006: stloc.2 IL_0007: call 0x06000002 IL_000c: stloc.1 IL_000d: ldloc.2 IL_000e: call 0x06000003 IL_0013: nop IL_0014: ldloc.1 IL_0015: call 0x06000003 IL_001a: nop IL_001b: ret }"); diff3.VerifyPdb(new[] { 0x06000001, 0x06000002, 0x06000003, 0x06000004 }, @" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method token=""0x6000004""> <customDebugInfo> <using> <namespace usingCount=""0"" /> </using> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""16"" startColumn=""5"" endLine=""16"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""17"" startColumn=""9"" endLine=""17"" endColumn=""24"" document=""1"" /> <entry offset=""0x7"" startLine=""18"" startColumn=""9"" endLine=""18"" endColumn=""24"" document=""1"" /> <entry offset=""0xd"" startLine=""19"" startColumn=""9"" endLine=""19"" endColumn=""14"" document=""1"" /> <entry offset=""0x14"" startLine=""20"" startColumn=""9"" endLine=""20"" endColumn=""14"" document=""1"" /> <entry offset=""0x1b"" startLine=""21"" startColumn=""5"" endLine=""21"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x1c""> <local name=""c"" il_index=""2"" il_start=""0x0"" il_end=""0x1c"" attributes=""0"" /> <local name=""b"" il_index=""1"" il_start=""0x0"" il_end=""0x1c"" attributes=""0"" /> </scope> </method> </methods> </symbols>"); #endregion } /// <summary> /// Preserve locals for method added after initial compilation. /// </summary> [Fact] public void PreserveLocalSlots_NewMethod() { var source0 = @"class C { }"; var source1 = @"class C { static void M() { var a = new object(); var b = string.Empty; } }"; var source2 = @"class C { static void M() { var a = 1; var b = string.Empty; } }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var compilation2 = compilation1.WithSource(source2); var bytes0 = compilation0.EmitToArray(); var generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), EmptyLocalsProvider); var m1 = compilation1.GetMember<MethodSymbol>("C.M"); var m2 = compilation2.GetMember<MethodSymbol>("C.M"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Insert, null, m1, null, preserveLocalVariables: true))); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, m1, m2, GetEquivalentNodesMap(m2, m1), preserveLocalVariables: true))); diff2.VerifyIL("C.M", @"{ // Code size 10 (0xa) .maxstack 1 .locals init ([object] V_0, string V_1, //b int V_2) //a IL_0000: nop IL_0001: ldc.i4.1 IL_0002: stloc.2 IL_0003: ldsfld ""string string.Empty"" IL_0008: stloc.1 IL_0009: ret }"); diff2.VerifyPdb(new[] { 0x06000002 }, @" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method token=""0x6000002""> <customDebugInfo> <using> <namespace usingCount=""0"" /> </using> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""4"" startColumn=""5"" endLine=""4"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""5"" startColumn=""9"" endLine=""5"" endColumn=""19"" document=""1"" /> <entry offset=""0x3"" startLine=""6"" startColumn=""9"" endLine=""6"" endColumn=""30"" document=""1"" /> <entry offset=""0x9"" startLine=""7"" startColumn=""5"" endLine=""7"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0xa""> <local name=""a"" il_index=""2"" il_start=""0x0"" il_end=""0xa"" attributes=""0"" /> <local name=""b"" il_index=""1"" il_start=""0x0"" il_end=""0xa"" attributes=""0"" /> </scope> </method> </methods> </symbols>"); } /// <summary> /// Local types should be retained, even if the local is no longer /// used by the method body, since there may be existing /// references to that slot, in a Watch window for instance. /// </summary> [WorkItem(843320, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/843320")] [Fact] public void PreserveLocalTypes() { var source0 = @"class C { static void Main() { var x = true; var y = x; System.Console.WriteLine(y); } }"; var source1 = @"class C { static void Main() { var x = ""A""; var y = x; System.Console.WriteLine(y); } }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var method0 = compilation0.GetMember<MethodSymbol>("C.Main"); var method1 = compilation1.GetMember<MethodSymbol>("C.Main"); var testData0 = new CompilationTestData(); var bytes0 = compilation0.EmitToArray(testData: testData0); var generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), testData0.GetMethodData("C.Main").EncDebugInfoProvider()); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true))); diff1.VerifyIL("C.Main", @" { // Code size 17 (0x11) .maxstack 1 .locals init ([bool] V_0, [bool] V_1, string V_2, //x string V_3) //y IL_0000: nop IL_0001: ldstr ""A"" IL_0006: stloc.2 IL_0007: ldloc.2 IL_0008: stloc.3 IL_0009: ldloc.3 IL_000a: call ""void System.Console.WriteLine(string)"" IL_000f: nop IL_0010: ret }"); } /// <summary> /// Preserve locals if SemanticEdit.PreserveLocalVariables is set. /// </summary> [Fact] public void PreserveLocalVariablesFlag() { var source = @"class C { static System.IDisposable F() { return null; } static void M() { using (F()) { } using (var x = F()) { } } }"; var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source); var testData0 = new CompilationTestData(); var bytes0 = compilation0.EmitToArray(testData: testData0); var method0 = compilation0.GetMember<MethodSymbol>("C.M"); var generation0 = EmitBaseline.CreateInitialBaseline( ModuleMetadata.CreateFromImage(bytes0), testData0.GetMethodData("C.M").EncDebugInfoProvider()); var method1 = compilation1.GetMember<MethodSymbol>("C.M"); var diff1a = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, preserveLocalVariables: false))); diff1a.VerifyIL("C.M", @" { // Code size 44 (0x2c) .maxstack 1 .locals init (System.IDisposable V_0, System.IDisposable V_1) //x IL_0000: nop IL_0001: call ""System.IDisposable C.F()"" IL_0006: stloc.0 .try { IL_0007: nop IL_0008: nop IL_0009: leave.s IL_0016 } finally { IL_000b: ldloc.0 IL_000c: brfalse.s IL_0015 IL_000e: ldloc.0 IL_000f: callvirt ""void System.IDisposable.Dispose()"" IL_0014: nop IL_0015: endfinally } IL_0016: call ""System.IDisposable C.F()"" IL_001b: stloc.1 .try { IL_001c: nop IL_001d: nop IL_001e: leave.s IL_002b } finally { IL_0020: ldloc.1 IL_0021: brfalse.s IL_002a IL_0023: ldloc.1 IL_0024: callvirt ""void System.IDisposable.Dispose()"" IL_0029: nop IL_002a: endfinally } IL_002b: ret } "); var diff1b = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, preserveLocalVariables: true))); diff1b.VerifyIL("C.M", @"{ // Code size 44 (0x2c) .maxstack 1 .locals init (System.IDisposable V_0, System.IDisposable V_1) //x IL_0000: nop IL_0001: call ""System.IDisposable C.F()"" IL_0006: stloc.0 .try { IL_0007: nop IL_0008: nop IL_0009: leave.s IL_0016 } finally { IL_000b: ldloc.0 IL_000c: brfalse.s IL_0015 IL_000e: ldloc.0 IL_000f: callvirt ""void System.IDisposable.Dispose()"" IL_0014: nop IL_0015: endfinally } IL_0016: call ""System.IDisposable C.F()"" IL_001b: stloc.1 .try { IL_001c: nop IL_001d: nop IL_001e: leave.s IL_002b } finally { IL_0020: ldloc.1 IL_0021: brfalse.s IL_002a IL_0023: ldloc.1 IL_0024: callvirt ""void System.IDisposable.Dispose()"" IL_0029: nop IL_002a: endfinally } IL_002b: ret }"); } [WorkItem(779531, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/779531")] [Fact] public void ChangeLocalType() { var source0 = @"enum E { } class C { static void M1() { var x = default(E); var y = x; var z = default(E); System.Console.WriteLine(y); } static void M2() { var x = default(E); var y = x; var z = default(E); System.Console.WriteLine(y); } }"; // Change locals in one method to type added. var source1 = @"enum E { } class A { } class C { static void M1() { var x = default(A); var y = x; var z = default(E); System.Console.WriteLine(y); } static void M2() { var x = default(E); var y = x; var z = default(E); System.Console.WriteLine(y); } }"; // Change locals in another method. var source2 = @"enum E { } class A { } class C { static void M1() { var x = default(A); var y = x; var z = default(E); System.Console.WriteLine(y); } static void M2() { var x = default(A); var y = x; var z = default(E); System.Console.WriteLine(y); } }"; // Change locals in same method. var source3 = @"enum E { } class A { } class C { static void M1() { var x = default(A); var y = x; var z = default(E); System.Console.WriteLine(y); } static void M2() { var x = default(A); var y = x; var z = default(A); System.Console.WriteLine(y); } }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var compilation2 = compilation1.WithSource(source2); var compilation3 = compilation2.WithSource(source3); var testData0 = new CompilationTestData(); var bytes0 = compilation0.EmitToArray(testData: testData0); var methodData0 = testData0.GetMethodData("C.M1"); var method0 = compilation0.GetMember<MethodSymbol>("C.M1"); var generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), methodData0.EncDebugInfoProvider()); var method1 = compilation1.GetMember<MethodSymbol>("C.M1"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Insert, null, compilation1.GetMember<NamedTypeSymbol>("A")), SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true))); diff1.VerifyIL("C.M1", @"{ // Code size 17 (0x11) .maxstack 1 .locals init ([unchanged] V_0, [unchanged] V_1, E V_2, //z A V_3, //x A V_4) //y IL_0000: nop IL_0001: ldnull IL_0002: stloc.3 IL_0003: ldloc.3 IL_0004: stloc.s V_4 IL_0006: ldc.i4.0 IL_0007: stloc.2 IL_0008: ldloc.s V_4 IL_000a: call ""void System.Console.WriteLine(object)"" IL_000f: nop IL_0010: ret }"); var method2 = compilation2.GetMember<MethodSymbol>("C.M2"); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, method1, method2, GetEquivalentNodesMap(method2, method1), preserveLocalVariables: true))); diff2.VerifyIL("C.M2", @"{ // Code size 17 (0x11) .maxstack 1 .locals init ([unchanged] V_0, [unchanged] V_1, E V_2, //z A V_3, //x A V_4) //y IL_0000: nop IL_0001: ldnull IL_0002: stloc.3 IL_0003: ldloc.3 IL_0004: stloc.s V_4 IL_0006: ldc.i4.0 IL_0007: stloc.2 IL_0008: ldloc.s V_4 IL_000a: call ""void System.Console.WriteLine(object)"" IL_000f: nop IL_0010: ret }"); var method3 = compilation3.GetMember<MethodSymbol>("C.M2"); var diff3 = compilation3.EmitDifference( diff2.NextGeneration, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, method2, method3, GetEquivalentNodesMap(method3, method2), preserveLocalVariables: true))); diff3.VerifyIL("C.M2", @"{ // Code size 18 (0x12) .maxstack 1 .locals init ([unchanged] V_0, [unchanged] V_1, [unchanged] V_2, A V_3, //x A V_4, //y A V_5) //z IL_0000: nop IL_0001: ldnull IL_0002: stloc.3 IL_0003: ldloc.3 IL_0004: stloc.s V_4 IL_0006: ldnull IL_0007: stloc.s V_5 IL_0009: ldloc.s V_4 IL_000b: call ""void System.Console.WriteLine(object)"" IL_0010: nop IL_0011: ret }"); } [Fact] public void AnonymousTypes_Update() { var source0 = MarkedSource(@" class C { static void F() { var <N:0>x = new { A = 1 }</N:0>; } } "); var source1 = MarkedSource(@" class C { static void F() { var <N:0>x = new { A = 2 }</N:0>; } } "); var source2 = MarkedSource(@" class C { static void F() { var <N:0>x = new { A = 3 }</N:0>; } } "); var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll.WithMetadataImportOptions(MetadataImportOptions.All)); var compilation1 = compilation0.WithSource(source1.Tree); var compilation2 = compilation1.WithSource(source2.Tree); var v0 = CompileAndVerify(compilation0); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var f0 = compilation0.GetMember<MethodSymbol>("C.F"); var f1 = compilation1.GetMember<MethodSymbol>("C.F"); var f2 = compilation2.GetMember<MethodSymbol>("C.F"); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); v0.VerifyIL("C.F", @" { // Code size 9 (0x9) .maxstack 1 .locals init (<>f__AnonymousType0<int> V_0) //x IL_0000: nop IL_0001: ldc.i4.1 IL_0002: newobj ""<>f__AnonymousType0<int>..ctor(int)"" IL_0007: stloc.0 IL_0008: ret } "); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true))); diff1.VerifySynthesizedMembers( "<>f__AnonymousType0<<A>j__TPar>: {Equals, GetHashCode, ToString}"); diff1.VerifyIL("C.F", @" { // Code size 9 (0x9) .maxstack 1 .locals init (<>f__AnonymousType0<int> V_0) //x IL_0000: nop IL_0001: ldc.i4.2 IL_0002: newobj ""<>f__AnonymousType0<int>..ctor(int)"" IL_0007: stloc.0 IL_0008: ret } "); // expect a single TypeRef for System.Object var md1 = diff1.GetMetadata(); AssertEx.Equal(new[] { "[0x23000002] System.Object" }, DumpTypeRefs(new[] { md0.MetadataReader, md1.Reader })); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, f1, f2, GetSyntaxMapFromMarkers(source1, source2), preserveLocalVariables: true))); diff2.VerifySynthesizedMembers( "<>f__AnonymousType0<<A>j__TPar>: {Equals, GetHashCode, ToString}"); diff2.VerifyIL("C.F", @" { // Code size 9 (0x9) .maxstack 1 .locals init (<>f__AnonymousType0<int> V_0) //x IL_0000: nop IL_0001: ldc.i4.3 IL_0002: newobj ""<>f__AnonymousType0<int>..ctor(int)"" IL_0007: stloc.0 IL_0008: ret } "); // expect a single TypeRef for System.Object var md2 = diff2.GetMetadata(); AssertEx.Equal(new[] { "[0x23000003] System.Object" }, DumpTypeRefs(new[] { md0.MetadataReader, md1.Reader, md2.Reader })); } [Fact] public void AnonymousTypes_UpdateAfterAdd() { var source0 = MarkedSource(@" class C { static void F() { } } "); var source1 = MarkedSource(@" class C { static void F() { var <N:0>x = new { A = 2 }</N:0>; } } "); var source2 = MarkedSource(@" class C { static void F() { var <N:0>x = new { A = 3 }</N:0>; } } "); var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll.WithMetadataImportOptions(MetadataImportOptions.All), targetFramework: TargetFramework.NetStandard20); var compilation1 = compilation0.WithSource(source1.Tree); var compilation2 = compilation1.WithSource(source2.Tree); var v0 = CompileAndVerify(compilation0); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var f0 = compilation0.GetMember<MethodSymbol>("C.F"); var f1 = compilation1.GetMember<MethodSymbol>("C.F"); var f2 = compilation2.GetMember<MethodSymbol>("C.F"); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true))); var md1 = diff1.GetMetadata(); diff1.VerifySynthesizedMembers( "<>f__AnonymousType0<<A>j__TPar>: {Equals, GetHashCode, ToString}"); diff1.VerifyIL("C.F", @" { // Code size 9 (0x9) .maxstack 1 .locals init (<>f__AnonymousType0<int> V_0) //x IL_0000: nop IL_0001: ldc.i4.2 IL_0002: newobj ""<>f__AnonymousType0<int>..ctor(int)"" IL_0007: stloc.0 IL_0008: ret } "); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, f1, f2, GetSyntaxMapFromMarkers(source1, source2), preserveLocalVariables: true))); diff2.VerifySynthesizedMembers( "<>f__AnonymousType0<<A>j__TPar>: {Equals, GetHashCode, ToString}"); diff2.VerifyIL("C.F", @" { // Code size 9 (0x9) .maxstack 1 .locals init (<>f__AnonymousType0<int> V_0) //x IL_0000: nop IL_0001: ldc.i4.3 IL_0002: newobj ""<>f__AnonymousType0<int>..ctor(int)"" IL_0007: stloc.0 IL_0008: ret } "); // expect a single TypeRef for System.Object var md2 = diff2.GetMetadata(); AssertEx.Equal(new[] { "[0x23000003] System.Object" }, DumpTypeRefs(new[] { md0.MetadataReader, md1.Reader, md2.Reader })); } /// <summary> /// Reuse existing anonymous types. /// </summary> [WorkItem(825903, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/825903")] [Fact] public void AnonymousTypes() { var source0 = @"namespace N { class A { static object F = new { A = 1, B = 2 }; } } namespace M { class B { static void M() { var x = new { B = 3, A = 4 }; var y = x.A; var z = new { }; } } }"; var source1 = @"namespace N { class A { static object F = new { A = 1, B = 2 }; } } namespace M { class B { static void M() { var x = new { B = 3, A = 4 }; var y = new { A = x.A }; var z = new { }; } } }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var m0 = compilation0.GetMember<MethodSymbol>("M.B.M"); var m1 = compilation1.GetMember<MethodSymbol>("M.B.M"); var testData0 = new CompilationTestData(); var bytes0 = compilation0.EmitToArray(testData: testData0); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var generation0 = EmitBaseline.CreateInitialBaseline(md0, testData0.GetMethodData("M.B.M").EncDebugInfoProvider()); var reader0 = md0.MetadataReader; CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "<>f__AnonymousType0`2", "<>f__AnonymousType1`2", "<>f__AnonymousType2", "B", "A"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, m0, m1, GetEquivalentNodesMap(m1, m0), preserveLocalVariables: true))); using var md1 = diff1.GetMetadata(); var reader1 = md1.Reader; CheckNames(new[] { reader0, reader1 }, reader1.GetTypeDefNames(), "<>f__AnonymousType3`1"); // one additional type diff1.VerifyIL("M.B.M", @" { // Code size 28 (0x1c) .maxstack 2 .locals init (<>f__AnonymousType1<int, int> V_0, //x [int] V_1, <>f__AnonymousType2 V_2, //z <>f__AnonymousType3<int> V_3) //y IL_0000: nop IL_0001: ldc.i4.3 IL_0002: ldc.i4.4 IL_0003: newobj ""<>f__AnonymousType1<int, int>..ctor(int, int)"" IL_0008: stloc.0 IL_0009: ldloc.0 IL_000a: callvirt ""int <>f__AnonymousType1<int, int>.A.get"" IL_000f: newobj ""<>f__AnonymousType3<int>..ctor(int)"" IL_0014: stloc.3 IL_0015: newobj ""<>f__AnonymousType2..ctor()"" IL_001a: stloc.2 IL_001b: ret }"); } /// <summary> /// Anonymous type names with module ids /// and gaps in indices. /// </summary> [ConditionalFact(typeof(WindowsOnly), Reason = "ILASM doesn't support Portable PDBs")] [WorkItem(2982, "https://github.com/dotnet/coreclr/issues/2982")] public void AnonymousTypes_OtherTypeNames() { var ilSource = @".assembly extern netstandard { .ver 2:0:0:0 .publickeytoken = (cc 7b 13 ff cd 2d dd 51) } // Valid signature, although not sequential index .class '<>f__AnonymousType2'<'<A>j__TPar', '<B>j__TPar'> extends object { .field public !'<A>j__TPar' A .field public !'<B>j__TPar' B } // Invalid signature, unexpected type parameter names .class '<>f__AnonymousType1'<A, B> extends object { .field public !A A .field public !B B } // Module id, duplicate index .class '<m>f__AnonymousType2`1'<'<A>j__TPar'> extends object { .field public !'<A>j__TPar' A } // Module id .class '<m>f__AnonymousType3`1'<'<B>j__TPar'> extends object { .field public !'<B>j__TPar' B } .class public C extends object { .method public specialname rtspecialname instance void .ctor() { ret } .method public static object F() { ldnull ret } }"; var source0 = @"class C { static object F() { return 0; } }"; var source1 = @"class C { static object F() { var x = new { A = new object(), B = 1 }; var y = new { A = x.A }; return y; } }"; var metadata0 = (MetadataImageReference)CompileIL(ilSource, prependDefaultHeader: false); var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll, targetFramework: TargetFramework.NetStandard20); var compilation1 = compilation0.WithSource(source1); var f0 = compilation0.GetMember<MethodSymbol>("C.F"); var f1 = compilation1.GetMember<MethodSymbol>("C.F"); var moduleMetadata0 = ((AssemblyMetadata)metadata0.GetMetadataNoCopy()).GetModules()[0]; var generation0 = EmitBaseline.CreateInitialBaseline(moduleMetadata0, m => default); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetEquivalentNodesMap(f1, f0), preserveLocalVariables: true))); using var md1 = diff1.GetMetadata(); diff1.VerifyIL("C.F", @"{ // Code size 31 (0x1f) .maxstack 2 .locals init (<>f__AnonymousType2<object, int> V_0, //x <>f__AnonymousType3<object> V_1, //y object V_2) IL_0000: nop IL_0001: newobj ""object..ctor()"" IL_0006: ldc.i4.1 IL_0007: newobj ""<>f__AnonymousType2<object, int>..ctor(object, int)"" IL_000c: stloc.0 IL_000d: ldloc.0 IL_000e: callvirt ""object <>f__AnonymousType2<object, int>.A.get"" IL_0013: newobj ""<>f__AnonymousType3<object>..ctor(object)"" IL_0018: stloc.1 IL_0019: ldloc.1 IL_001a: stloc.2 IL_001b: br.s IL_001d IL_001d: ldloc.2 IL_001e: ret }"); } /// <summary> /// Update method with anonymous type that was /// not directly referenced in previous generation. /// </summary> [Fact] public void AnonymousTypes_SkipGeneration() { var source0 = MarkedSource( @"class A { } class B { static object F() { var <N:0>x = new { A = 1 }</N:0>; return x.A; } static object G() { var <N:1>x = 1</N:1>; return x; } }"); var source1 = MarkedSource( @"class A { } class B { static object F() { var <N:0>x = new { A = 1 }</N:0>; return x.A; } static object G() { var <N:1>x = 1</N:1>; return x + 1; } }"); var source2 = MarkedSource( @"class A { } class B { static object F() { var <N:0>x = new { A = 1 }</N:0>; return x.A; } static object G() { var <N:1>x = new { A = new A() }</N:1>; var <N:2>y = new { B = 2 }</N:2>; return x.A; } }"); var source3 = MarkedSource( @"class A { } class B { static object F() { var <N:0>x = new { A = 1 }</N:0>; return x.A; } static object G() { var <N:1>x = new { A = new A() }</N:1>; var <N:2>y = new { B = 3 }</N:2>; return y.B; } }"); var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll); var compilation1 = compilation0.WithSource(source1.Tree); var compilation2 = compilation1.WithSource(source2.Tree); var compilation3 = compilation2.WithSource(source3.Tree); var v0 = CompileAndVerify(compilation0); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); var method0 = compilation0.GetMember<MethodSymbol>("B.G"); var method1 = compilation1.GetMember<MethodSymbol>("B.G"); var method2 = compilation2.GetMember<MethodSymbol>("B.G"); var method3 = compilation3.GetMember<MethodSymbol>("B.G"); var reader0 = md0.MetadataReader; CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "<>f__AnonymousType0`1", "A", "B"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true))); var md1 = diff1.GetMetadata(); var reader1 = md1.Reader; CheckNames(new[] { reader0, reader1 }, reader1.GetTypeDefNames()); // no additional types diff1.VerifyIL("B.G", @" { // Code size 16 (0x10) .maxstack 2 .locals init (int V_0, //x [object] V_1, object V_2) IL_0000: nop IL_0001: ldc.i4.1 IL_0002: stloc.0 IL_0003: ldloc.0 IL_0004: ldc.i4.1 IL_0005: add IL_0006: box ""int"" IL_000b: stloc.2 IL_000c: br.s IL_000e IL_000e: ldloc.2 IL_000f: ret }"); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method1, method2, GetSyntaxMapFromMarkers(source1, source2), preserveLocalVariables: true))); var md2 = diff2.GetMetadata(); var reader2 = md2.Reader; CheckNames(new[] { reader0, reader1, reader2 }, reader2.GetTypeDefNames(), "<>f__AnonymousType1`1"); // one additional type diff2.VerifyIL("B.G", @" { // Code size 33 (0x21) .maxstack 1 .locals init ([int] V_0, [object] V_1, [object] V_2, <>f__AnonymousType0<A> V_3, //x <>f__AnonymousType1<int> V_4, //y object V_5) IL_0000: nop IL_0001: newobj ""A..ctor()"" IL_0006: newobj ""<>f__AnonymousType0<A>..ctor(A)"" IL_000b: stloc.3 IL_000c: ldc.i4.2 IL_000d: newobj ""<>f__AnonymousType1<int>..ctor(int)"" IL_0012: stloc.s V_4 IL_0014: ldloc.3 IL_0015: callvirt ""A <>f__AnonymousType0<A>.A.get"" IL_001a: stloc.s V_5 IL_001c: br.s IL_001e IL_001e: ldloc.s V_5 IL_0020: ret }"); var diff3 = compilation3.EmitDifference( diff2.NextGeneration, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method2, method3, GetSyntaxMapFromMarkers(source2, source3), preserveLocalVariables: true))); var md3 = diff3.GetMetadata(); var reader3 = md3.Reader; CheckNames(new[] { reader0, reader1, reader2, reader3 }, reader3.GetTypeDefNames()); // no additional types diff3.VerifyIL("B.G", @" { // Code size 39 (0x27) .maxstack 1 .locals init ([int] V_0, [object] V_1, [object] V_2, <>f__AnonymousType0<A> V_3, //x <>f__AnonymousType1<int> V_4, //y [object] V_5, object V_6) IL_0000: nop IL_0001: newobj ""A..ctor()"" IL_0006: newobj ""<>f__AnonymousType0<A>..ctor(A)"" IL_000b: stloc.3 IL_000c: ldc.i4.3 IL_000d: newobj ""<>f__AnonymousType1<int>..ctor(int)"" IL_0012: stloc.s V_4 IL_0014: ldloc.s V_4 IL_0016: callvirt ""int <>f__AnonymousType1<int>.B.get"" IL_001b: box ""int"" IL_0020: stloc.s V_6 IL_0022: br.s IL_0024 IL_0024: ldloc.s V_6 IL_0026: ret }"); } /// <summary> /// Update another method (without directly referencing /// anonymous type) after updating method with anonymous type. /// </summary> [Fact] public void AnonymousTypes_SkipGeneration_2() { var source0 = @"class C { static object F() { var x = new { A = 1 }; return x.A; } static object G() { var x = 1; return x; } }"; var source1 = @"class C { static object F() { var x = new { A = 2, B = 3 }; return x.A; } static object G() { var x = 1; return x; } }"; var source2 = @"class C { static object F() { var x = new { A = 2, B = 3 }; return x.A; } static object G() { var x = 1; return x + 1; } }"; var source3 = @"class C { static object F() { var x = new { A = 2, B = 3 }; return x.A; } static object G() { var x = new { A = (object)null }; var y = new { A = 'a', B = 'b' }; return x; } }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var compilation2 = compilation1.WithSource(source2); var compilation3 = compilation2.WithSource(source3); var f0 = compilation0.GetMember<MethodSymbol>("C.F"); var f1 = compilation1.GetMember<MethodSymbol>("C.F"); var g1 = compilation1.GetMember<MethodSymbol>("C.G"); var g2 = compilation2.GetMember<MethodSymbol>("C.G"); var g3 = compilation3.GetMember<MethodSymbol>("C.G"); var testData0 = new CompilationTestData(); var bytes0 = compilation0.EmitToArray(testData: testData0); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var generation0 = EmitBaseline.CreateInitialBaseline( md0, m => md0.MetadataReader.GetString(md0.MetadataReader.GetMethodDefinition(m).Name) switch { "F" => testData0.GetMethodData("C.F").GetEncDebugInfo(), "G" => testData0.GetMethodData("C.G").GetEncDebugInfo(), _ => default, }); var reader0 = md0.MetadataReader; CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "<>f__AnonymousType0`1", "C"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetEquivalentNodesMap(f1, f0), preserveLocalVariables: true))); using var md1 = diff1.GetMetadata(); var reader1 = md1.Reader; var readers = new List<MetadataReader> { reader0, reader1 }; CheckNames(readers, reader1.GetTypeDefNames(), "<>f__AnonymousType1`2"); // one additional type var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, g1, g2, GetEquivalentNodesMap(g2, g1), preserveLocalVariables: true))); using var md2 = diff2.GetMetadata(); var reader2 = md2.Reader; readers.Add(reader2); CheckNames(readers, reader2.GetTypeDefNames()); // no additional types var diff3 = compilation3.EmitDifference( diff2.NextGeneration, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, g2, g3, GetEquivalentNodesMap(g3, g2), preserveLocalVariables: true))); using var md3 = diff3.GetMetadata(); var reader3 = md3.Reader; readers.Add(reader3); CheckNames(readers, reader3.GetTypeDefNames()); // no additional types } /// <summary> /// Local from previous generation is of an anonymous /// type not available in next generation. /// </summary> [Fact] public void AnonymousTypes_AddThenDelete() { var source0 = @"class C { object A; static object F() { var x = new C(); var y = x.A; return y; } }"; var source1 = @"class C { static object F() { var x = new { A = new object() }; var y = x.A; return y; } }"; var source2 = @"class C { static object F() { var x = new { A = new object(), B = 2 }; var y = x.A; y = new { B = new object() }.B; return y; } }"; var source3 = @"class C { static object F() { var x = new { A = new object(), B = 3 }; var y = x.A; return y; } }"; var source4 = @"class C { static object F() { var x = new { B = 4, A = new object() }; var y = x.A; return y; } }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var compilation2 = compilation1.WithSource(source2); var compilation3 = compilation2.WithSource(source3); var compilation4 = compilation3.WithSource(source4); var testData0 = new CompilationTestData(); var bytes0 = compilation0.EmitToArray(testData: testData0); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var generation0 = EmitBaseline.CreateInitialBaseline(md0, testData0.GetMethodData("C.F").EncDebugInfoProvider()); var method0 = compilation0.GetMember<MethodSymbol>("C.F"); var reader0 = md0.MetadataReader; CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "C"); var method1 = compilation1.GetMember<MethodSymbol>("C.F"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true))); using var md1 = diff1.GetMetadata(); var reader1 = md1.Reader; CheckNames(new[] { reader0, reader1 }, reader1.GetTypeDefNames(), "<>f__AnonymousType0`1"); // one additional type diff1.VerifyIL("C.F", @" { // Code size 27 (0x1b) .maxstack 1 .locals init ([unchanged] V_0, object V_1, //y [object] V_2, <>f__AnonymousType0<object> V_3, //x object V_4) IL_0000: nop IL_0001: newobj ""object..ctor()"" IL_0006: newobj ""<>f__AnonymousType0<object>..ctor(object)"" IL_000b: stloc.3 IL_000c: ldloc.3 IL_000d: callvirt ""object <>f__AnonymousType0<object>.A.get"" IL_0012: stloc.1 IL_0013: ldloc.1 IL_0014: stloc.s V_4 IL_0016: br.s IL_0018 IL_0018: ldloc.s V_4 IL_001a: ret }"); var method2 = compilation2.GetMember<MethodSymbol>("C.F"); } [Fact] public void AnonymousTypes_DifferentCase() { var source0 = MarkedSource(@" class C { static void M() { var <N:0>x = new { A = 1, B = 2 }</N:0>; var <N:1>y = new { a = 3, b = 4 }</N:1>; } }"); var source1 = MarkedSource(@" class C { static void M() { var <N:0>x = new { a = 1, B = 2 }</N:0>; var <N:1>y = new { AB = 3 }</N:1>; } }"); var source2 = MarkedSource(@" class C { static void M() { var <N:0>x = new { a = 1, B = 2 }</N:0>; var <N:1>y = new { Ab = 5 }</N:1>; } }"); var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll); var compilation1 = compilation0.WithSource(source1.Tree); var compilation2 = compilation1.WithSource(source2.Tree); var v0 = CompileAndVerify(compilation0); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var reader0 = md0.MetadataReader; var m0 = compilation0.GetMember<MethodSymbol>("C.M"); var m1 = compilation1.GetMember<MethodSymbol>("C.M"); var m2 = compilation2.GetMember<MethodSymbol>("C.M"); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "<>f__AnonymousType0`2", "<>f__AnonymousType1`2", "C"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, m0, m1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true))); var reader1 = diff1.GetMetadata().Reader; CheckNames(new[] { reader0, reader1 }, reader1.GetTypeDefNames(), "<>f__AnonymousType2`2", "<>f__AnonymousType3`1"); // the first two slots can't be reused since the type changed diff1.VerifyIL("C.M", @"{ // Code size 17 (0x11) .maxstack 2 .locals init ([unchanged] V_0, [unchanged] V_1, <>f__AnonymousType2<int, int> V_2, //x <>f__AnonymousType3<int> V_3) //y IL_0000: nop IL_0001: ldc.i4.1 IL_0002: ldc.i4.2 IL_0003: newobj ""<>f__AnonymousType2<int, int>..ctor(int, int)"" IL_0008: stloc.2 IL_0009: ldc.i4.3 IL_000a: newobj ""<>f__AnonymousType3<int>..ctor(int)"" IL_000f: stloc.3 IL_0010: ret }"); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, m1, m2, GetSyntaxMapFromMarkers(source1, source2), preserveLocalVariables: true))); var reader2 = diff2.GetMetadata().Reader; CheckNames(new[] { reader0, reader1, reader2 }, reader2.GetTypeDefNames(), "<>f__AnonymousType4`1"); // we can reuse slot for "x", it's type haven't changed diff2.VerifyIL("C.M", @"{ // Code size 18 (0x12) .maxstack 2 .locals init ([unchanged] V_0, [unchanged] V_1, <>f__AnonymousType2<int, int> V_2, //x [unchanged] V_3, <>f__AnonymousType4<int> V_4) //y IL_0000: nop IL_0001: ldc.i4.1 IL_0002: ldc.i4.2 IL_0003: newobj ""<>f__AnonymousType2<int, int>..ctor(int, int)"" IL_0008: stloc.2 IL_0009: ldc.i4.5 IL_000a: newobj ""<>f__AnonymousType4<int>..ctor(int)"" IL_000f: stloc.s V_4 IL_0011: ret }"); } [Fact] public void AnonymousTypes_Nested1() { var template = @" using System; using System.Linq; class C { static void F(string[] args) { var <N:0>result = from a in args <N:1>let x = a.Reverse()</N:1> <N:2>let y = x.Reverse()</N:2> <N:3>where x.SequenceEqual(y)</N:3> <N:4>select new { Value = a, Length = a.Length }</N:4></N:0>; Console.WriteLine(<<VALUE>>); } }"; var source0 = MarkedSource(template.Replace("<<VALUE>>", "0")); var source1 = MarkedSource(template.Replace("<<VALUE>>", "1")); var source2 = MarkedSource(template.Replace("<<VALUE>>", "2")); var compilation0 = CreateCompilationWithMscorlib45(new[] { source0.Tree }, new[] { SystemCoreRef }, options: ComSafeDebugDll); var compilation1 = compilation0.WithSource(source1.Tree); var compilation2 = compilation0.WithSource(source2.Tree); var v0 = CompileAndVerify(compilation0); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var f0 = compilation0.GetMember<MethodSymbol>("C.F"); var f1 = compilation1.GetMember<MethodSymbol>("C.F"); var f2 = compilation2.GetMember<MethodSymbol>("C.F"); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); var expectedIL = @" { // Code size 155 (0x9b) .maxstack 3 .locals init (System.Collections.Generic.IEnumerable<<anonymous type: string Value, int Length>> V_0) //result IL_0000: nop IL_0001: ldarg.0 IL_0002: ldsfld ""System.Func<string, <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>> C.<>c.<>9__0_0"" IL_0007: dup IL_0008: brtrue.s IL_0021 IL_000a: pop IL_000b: ldsfld ""C.<>c C.<>c.<>9"" IL_0010: ldftn ""<anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> C.<>c.<F>b__0_0(string)"" IL_0016: newobj ""System.Func<string, <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>>..ctor(object, System.IntPtr)"" IL_001b: dup IL_001c: stsfld ""System.Func<string, <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>> C.<>c.<>9__0_0"" IL_0021: call ""System.Collections.Generic.IEnumerable<<anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>> System.Linq.Enumerable.Select<string, <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>>(System.Collections.Generic.IEnumerable<string>, System.Func<string, <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>>)"" IL_0026: ldsfld ""System.Func<<anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>, <anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>> C.<>c.<>9__0_1"" IL_002b: dup IL_002c: brtrue.s IL_0045 IL_002e: pop IL_002f: ldsfld ""C.<>c C.<>c.<>9"" IL_0034: ldftn ""<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y> C.<>c.<F>b__0_1(<anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>)"" IL_003a: newobj ""System.Func<<anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>, <anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>>..ctor(object, System.IntPtr)"" IL_003f: dup IL_0040: stsfld ""System.Func<<anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>, <anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>> C.<>c.<>9__0_1"" IL_0045: call ""System.Collections.Generic.IEnumerable<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>> System.Linq.Enumerable.Select<<anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>, <anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>>(System.Collections.Generic.IEnumerable<<anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>>, System.Func<<anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>, <anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>>)"" IL_004a: ldsfld ""System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, bool> C.<>c.<>9__0_2"" IL_004f: dup IL_0050: brtrue.s IL_0069 IL_0052: pop IL_0053: ldsfld ""C.<>c C.<>c.<>9"" IL_0058: ldftn ""bool C.<>c.<F>b__0_2(<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>)"" IL_005e: newobj ""System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, bool>..ctor(object, System.IntPtr)"" IL_0063: dup IL_0064: stsfld ""System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, bool> C.<>c.<>9__0_2"" IL_0069: call ""System.Collections.Generic.IEnumerable<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>> System.Linq.Enumerable.Where<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>>(System.Collections.Generic.IEnumerable<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>>, System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, bool>)"" IL_006e: ldsfld ""System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, <anonymous type: string Value, int Length>> C.<>c.<>9__0_3"" IL_0073: dup IL_0074: brtrue.s IL_008d IL_0076: pop IL_0077: ldsfld ""C.<>c C.<>c.<>9"" IL_007c: ldftn ""<anonymous type: string Value, int Length> C.<>c.<F>b__0_3(<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>)"" IL_0082: newobj ""System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, <anonymous type: string Value, int Length>>..ctor(object, System.IntPtr)"" IL_0087: dup IL_0088: stsfld ""System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, <anonymous type: string Value, int Length>> C.<>c.<>9__0_3"" IL_008d: call ""System.Collections.Generic.IEnumerable<<anonymous type: string Value, int Length>> System.Linq.Enumerable.Select<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, <anonymous type: string Value, int Length>>(System.Collections.Generic.IEnumerable<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>>, System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, <anonymous type: string Value, int Length>>)"" IL_0092: stloc.0 IL_0093: ldc.i4.<<VALUE>> IL_0094: call ""void System.Console.WriteLine(int)"" IL_0099: nop IL_009a: ret } "; v0.VerifyIL("C.F", expectedIL.Replace("<<VALUE>>", "0")); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true))); diff1.VerifySynthesizedMembers( "C: {<>c}", "C.<>c: {<>9__0_0, <>9__0_1, <>9__0_2, <>9__0_3, <F>b__0_0, <F>b__0_1, <F>b__0_2, <F>b__0_3}", "<>f__AnonymousType2<<Value>j__TPar, <Length>j__TPar>: {Equals, GetHashCode, ToString}", "<>f__AnonymousType1<<<>h__TransparentIdentifier0>j__TPar, <y>j__TPar>: {Equals, GetHashCode, ToString}", "<>f__AnonymousType0<<a>j__TPar, <x>j__TPar>: {Equals, GetHashCode, ToString}"); diff1.VerifyIL("C.F", expectedIL.Replace("<<VALUE>>", "1")); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, f1, f2, GetSyntaxMapFromMarkers(source1, source2), preserveLocalVariables: true))); diff2.VerifySynthesizedMembers( "C: {<>c}", "C.<>c: {<>9__0_0, <>9__0_1, <>9__0_2, <>9__0_3, <F>b__0_0, <F>b__0_1, <F>b__0_2, <F>b__0_3}", "<>f__AnonymousType2<<Value>j__TPar, <Length>j__TPar>: {Equals, GetHashCode, ToString}", "<>f__AnonymousType1<<<>h__TransparentIdentifier0>j__TPar, <y>j__TPar>: {Equals, GetHashCode, ToString}", "<>f__AnonymousType0<<a>j__TPar, <x>j__TPar>: {Equals, GetHashCode, ToString}"); diff2.VerifyIL("C.F", expectedIL.Replace("<<VALUE>>", "2")); } [Fact] public void AnonymousTypes_Nested2() { var template = @" using System; using System.Linq; class C { static void F(string[] args) { var <N:0>result = from a in args <N:1>let x = a.Reverse()</N:1> <N:2>let y = x.Reverse()</N:2> <N:3>where x.SequenceEqual(y)</N:3> <N:4>select new { Value = a, Length = a.Length }</N:4></N:0>; Console.WriteLine(<<VALUE>>); } }"; var source0 = MarkedSource(template.Replace("<<VALUE>>", "0")); var source1 = MarkedSource(template.Replace("<<VALUE>>", "1")); var source2 = MarkedSource(template.Replace("<<VALUE>>", "2")); var compilation0 = CreateCompilationWithMscorlib45(new[] { source0.Tree }, new[] { SystemCoreRef }, options: ComSafeDebugDll); var compilation1 = compilation0.WithSource(source1.Tree); var compilation2 = compilation0.WithSource(source2.Tree); var v0 = CompileAndVerify(compilation0); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var f0 = compilation0.GetMember<MethodSymbol>("C.F"); var f1 = compilation1.GetMember<MethodSymbol>("C.F"); var f2 = compilation2.GetMember<MethodSymbol>("C.F"); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); var expectedIL = @" { // Code size 155 (0x9b) .maxstack 3 .locals init (System.Collections.Generic.IEnumerable<<anonymous type: string Value, int Length>> V_0) //result IL_0000: nop IL_0001: ldarg.0 IL_0002: ldsfld ""System.Func<string, <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>> C.<>c.<>9__0_0"" IL_0007: dup IL_0008: brtrue.s IL_0021 IL_000a: pop IL_000b: ldsfld ""C.<>c C.<>c.<>9"" IL_0010: ldftn ""<anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> C.<>c.<F>b__0_0(string)"" IL_0016: newobj ""System.Func<string, <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>>..ctor(object, System.IntPtr)"" IL_001b: dup IL_001c: stsfld ""System.Func<string, <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>> C.<>c.<>9__0_0"" IL_0021: call ""System.Collections.Generic.IEnumerable<<anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>> System.Linq.Enumerable.Select<string, <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>>(System.Collections.Generic.IEnumerable<string>, System.Func<string, <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>>)"" IL_0026: ldsfld ""System.Func<<anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>, <anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>> C.<>c.<>9__0_1"" IL_002b: dup IL_002c: brtrue.s IL_0045 IL_002e: pop IL_002f: ldsfld ""C.<>c C.<>c.<>9"" IL_0034: ldftn ""<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y> C.<>c.<F>b__0_1(<anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>)"" IL_003a: newobj ""System.Func<<anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>, <anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>>..ctor(object, System.IntPtr)"" IL_003f: dup IL_0040: stsfld ""System.Func<<anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>, <anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>> C.<>c.<>9__0_1"" IL_0045: call ""System.Collections.Generic.IEnumerable<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>> System.Linq.Enumerable.Select<<anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>, <anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>>(System.Collections.Generic.IEnumerable<<anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>>, System.Func<<anonymous type: string a, System.Collections.Generic.IEnumerable<char> x>, <anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>>)"" IL_004a: ldsfld ""System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, bool> C.<>c.<>9__0_2"" IL_004f: dup IL_0050: brtrue.s IL_0069 IL_0052: pop IL_0053: ldsfld ""C.<>c C.<>c.<>9"" IL_0058: ldftn ""bool C.<>c.<F>b__0_2(<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>)"" IL_005e: newobj ""System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, bool>..ctor(object, System.IntPtr)"" IL_0063: dup IL_0064: stsfld ""System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, bool> C.<>c.<>9__0_2"" IL_0069: call ""System.Collections.Generic.IEnumerable<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>> System.Linq.Enumerable.Where<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>>(System.Collections.Generic.IEnumerable<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>>, System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, bool>)"" IL_006e: ldsfld ""System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, <anonymous type: string Value, int Length>> C.<>c.<>9__0_3"" IL_0073: dup IL_0074: brtrue.s IL_008d IL_0076: pop IL_0077: ldsfld ""C.<>c C.<>c.<>9"" IL_007c: ldftn ""<anonymous type: string Value, int Length> C.<>c.<F>b__0_3(<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>)"" IL_0082: newobj ""System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, <anonymous type: string Value, int Length>>..ctor(object, System.IntPtr)"" IL_0087: dup IL_0088: stsfld ""System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, <anonymous type: string Value, int Length>> C.<>c.<>9__0_3"" IL_008d: call ""System.Collections.Generic.IEnumerable<<anonymous type: string Value, int Length>> System.Linq.Enumerable.Select<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, <anonymous type: string Value, int Length>>(System.Collections.Generic.IEnumerable<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>>, System.Func<<anonymous type: <anonymous type: string a, System.Collections.Generic.IEnumerable<char> x> <>h__TransparentIdentifier0, System.Collections.Generic.IEnumerable<char> y>, <anonymous type: string Value, int Length>>)"" IL_0092: stloc.0 IL_0093: ldc.i4.<<VALUE>> IL_0094: call ""void System.Console.WriteLine(int)"" IL_0099: nop IL_009a: ret } "; v0.VerifyIL("C.F", expectedIL.Replace("<<VALUE>>", "0")); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true))); diff1.VerifySynthesizedMembers( "C: {<>c}", "C.<>c: {<>9__0_0, <>9__0_1, <>9__0_2, <>9__0_3, <F>b__0_0, <F>b__0_1, <F>b__0_2, <F>b__0_3}", "<>f__AnonymousType2<<Value>j__TPar, <Length>j__TPar>: {Equals, GetHashCode, ToString}", "<>f__AnonymousType1<<<>h__TransparentIdentifier0>j__TPar, <y>j__TPar>: {Equals, GetHashCode, ToString}", "<>f__AnonymousType0<<a>j__TPar, <x>j__TPar>: {Equals, GetHashCode, ToString}"); diff1.VerifyIL("C.F", expectedIL.Replace("<<VALUE>>", "1")); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, f1, f2, GetSyntaxMapFromMarkers(source1, source2), preserveLocalVariables: true))); diff2.VerifySynthesizedMembers( "C: {<>c}", "C.<>c: {<>9__0_0, <>9__0_1, <>9__0_2, <>9__0_3, <F>b__0_0, <F>b__0_1, <F>b__0_2, <F>b__0_3}", "<>f__AnonymousType2<<Value>j__TPar, <Length>j__TPar>: {Equals, GetHashCode, ToString}", "<>f__AnonymousType1<<<>h__TransparentIdentifier0>j__TPar, <y>j__TPar>: {Equals, GetHashCode, ToString}", "<>f__AnonymousType0<<a>j__TPar, <x>j__TPar>: {Equals, GetHashCode, ToString}"); diff2.VerifyIL("C.F", expectedIL.Replace("<<VALUE>>", "2")); } [Fact] public void AnonymousTypes_Query1() { var source0 = MarkedSource(@" using System.Linq; class C { static void F(string[] args) { args = new[] { ""a"", ""bB"", ""Cc"", ""DD"" }; var <N:4>result = from a in args <N:0>let x = a.Reverse()</N:0> <N:1>let y = x.Reverse()</N:1> <N:2>where x.SequenceEqual(y)</N:2> <N:3>select new { Value = a, Length = a.Length }</N:3></N:4>; var <N:8>newArgs = from a in result <N:5>let value = a.Value</N:5> <N:6>let length = a.Length</N:6> <N:7>where value.Length == length</N:7> select value</N:8>; args = args.Concat(newArgs).ToArray(); System.Diagnostics.Debugger.Break(); result.ToString(); } } "); var source1 = MarkedSource(@" using System.Linq; class C { static void F(string[] args) { args = new[] { ""a"", ""bB"", ""Cc"", ""DD"" }; var list = false ? null : new { Head = (dynamic)null, Tail = (dynamic)null }; for (int i = 0; i < 10; i++) { var <N:4>result = from a in args <N:0>let x = a.Reverse()</N:0> <N:1>let y = x.Reverse()</N:1> <N:2>where x.SequenceEqual(y)</N:2> orderby a.Length ascending, a descending <N:3>select new { Value = a, Length = x.Count() }</N:3></N:4>; var linked = result.Aggregate( false ? new { Head = (string)null, Tail = (dynamic)null } : null, (total, curr) => new { Head = curr.Value, Tail = (dynamic)total }); var str = linked?.Tail?.Head; var <N:8>newArgs = from a in result <N:5>let value = a.Value</N:5> <N:6>let length = a.Length</N:6> <N:7>where value.Length == length</N:7> select value + value</N:8>; args = args.Concat(newArgs).ToArray(); list = new { Head = (dynamic)i, Tail = (dynamic)list }; System.Diagnostics.Debugger.Break(); } System.Diagnostics.Debugger.Break(); } } "); var compilation0 = CreateCompilationWithMscorlib45(new[] { source0.Tree }, new[] { SystemCoreRef, CSharpRef }, options: ComSafeDebugDll); var compilation1 = compilation0.WithSource(source1.Tree); var v0 = CompileAndVerify(compilation0); v0.VerifyDiagnostics(); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var f0 = compilation0.GetMember<MethodSymbol>("C.F"); var f1 = compilation1.GetMember<MethodSymbol>("C.F"); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); v0.VerifyLocalSignature("C.F", @" .locals init (System.Collections.Generic.IEnumerable<<anonymous type: string Value, int Length>> V_0, //result System.Collections.Generic.IEnumerable<string> V_1) //newArgs "); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true))); diff1.VerifySynthesizedMembers( "C.<>o__0#1: {<>p__0}", "C: {<>o__0#1, <>c}", "C.<>c: {<>9__0_0, <>9__0_1, <>9__0_2, <>9__0_3#1, <>9__0_4#1, <>9__0_3, <>9__0_6#1, <>9__0_4, <>9__0_5, <>9__0_6, <>9__0_10#1, <F>b__0_0, <F>b__0_1, <F>b__0_2, <F>b__0_3#1, <F>b__0_4#1, <F>b__0_3, <F>b__0_6#1, <F>b__0_4, <F>b__0_5, <F>b__0_6, <F>b__0_10#1}", "<>f__AnonymousType4<<<>h__TransparentIdentifier0>j__TPar, <length>j__TPar>: {Equals, GetHashCode, ToString}", "<>f__AnonymousType2<<Value>j__TPar, <Length>j__TPar>: {Equals, GetHashCode, ToString}", "<>f__AnonymousType5<<Head>j__TPar, <Tail>j__TPar>: {Equals, GetHashCode, ToString}", "<>f__AnonymousType3<<a>j__TPar, <value>j__TPar>: {Equals, GetHashCode, ToString}", "<>f__AnonymousType0<<a>j__TPar, <x>j__TPar>: {Equals, GetHashCode, ToString}", "<>f__AnonymousType1<<<>h__TransparentIdentifier0>j__TPar, <y>j__TPar>: {Equals, GetHashCode, ToString}"); diff1.VerifyLocalSignature("C.F", @" .locals init (System.Collections.Generic.IEnumerable<<anonymous type: string Value, int Length>> V_0, //result System.Collections.Generic.IEnumerable<string> V_1, //newArgs <>f__AnonymousType5<dynamic, dynamic> V_2, //list int V_3, //i <>f__AnonymousType5<string, dynamic> V_4, //linked object V_5, //str <>f__AnonymousType5<string, dynamic> V_6, object V_7, bool V_8) "); } [Fact] public void AnonymousTypes_Dynamic1() { var template = @" using System; class C { public void F() { var <N:0>x = new { A = (dynamic)null, B = 1 }</N:0>; Console.WriteLine(x.B + <<VALUE>>); } } "; var source0 = MarkedSource(template.Replace("<<VALUE>>", "0")); var source1 = MarkedSource(template.Replace("<<VALUE>>", "1")); var source2 = MarkedSource(template.Replace("<<VALUE>>", "2")); var compilation0 = CreateCompilationWithMscorlib45(new[] { source0.Tree }, options: ComSafeDebugDll); var compilation1 = compilation0.WithSource(source1.Tree); var compilation2 = compilation1.WithSource(source2.Tree); var v0 = CompileAndVerify(compilation0); v0.VerifyDiagnostics(); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var f0 = compilation0.GetMember<MethodSymbol>("C.F"); var f1 = compilation1.GetMember<MethodSymbol>("C.F"); var f2 = compilation2.GetMember<MethodSymbol>("C.F"); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); var baselineIL0 = @" { // Code size 22 (0x16) .maxstack 2 .locals init (<>f__AnonymousType0<dynamic, int> V_0) //x IL_0000: nop IL_0001: ldnull IL_0002: ldc.i4.1 IL_0003: newobj ""<>f__AnonymousType0<dynamic, int>..ctor(dynamic, int)"" IL_0008: stloc.0 IL_0009: ldloc.0 IL_000a: callvirt ""int <>f__AnonymousType0<dynamic, int>.B.get"" IL_000f: call ""void System.Console.WriteLine(int)"" IL_0014: nop IL_0015: ret } "; v0.VerifyIL("C.F", baselineIL0); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true))); diff1.VerifySynthesizedMembers( "<>f__AnonymousType0<<A>j__TPar, <B>j__TPar>: {Equals, GetHashCode, ToString}"); var baselineIL = @" { // Code size 24 (0x18) .maxstack 2 .locals init (<>f__AnonymousType0<dynamic, int> V_0) //x IL_0000: nop IL_0001: ldnull IL_0002: ldc.i4.1 IL_0003: newobj ""<>f__AnonymousType0<dynamic, int>..ctor(dynamic, int)"" IL_0008: stloc.0 IL_0009: ldloc.0 IL_000a: callvirt ""int <>f__AnonymousType0<dynamic, int>.B.get"" IL_000f: ldc.i4.<<VALUE>> IL_0010: add IL_0011: call ""void System.Console.WriteLine(int)"" IL_0016: nop IL_0017: ret } "; diff1.VerifyIL("C.F", baselineIL.Replace("<<VALUE>>", "1")); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, f1, f2, GetSyntaxMapFromMarkers(source1, source2), preserveLocalVariables: true))); diff2.VerifySynthesizedMembers( "<>f__AnonymousType0<<A>j__TPar, <B>j__TPar>: {Equals, GetHashCode, ToString}"); diff2.VerifyIL("C.F", baselineIL.Replace("<<VALUE>>", "2")); } /// <summary> /// Should not re-use locals if the method metadata /// signature is unsupported. /// </summary> [WorkItem(9849, "https://github.com/dotnet/roslyn/issues/9849")] [Fact(Skip = "https://github.com/dotnet/roslyn/issues/9849")] public void LocalType_UnsupportedSignatureContent() { // Equivalent to C#, but with extra local and required modifier on // expected local. Used to generate initial (unsupported) metadata. var ilSource = @".assembly extern mscorlib { .ver 4:0:0:0 .publickeytoken = (B7 7A 5C 56 19 34 E0 89) } .assembly '<<GeneratedFileName>>' { } .class C { .method public specialname rtspecialname instance void .ctor() { ret } .method private static object F() { ldnull ret } .method private static void M1() { .locals init ([0] object other, [1] object modreq(int32) o) call object C::F() stloc.1 ldloc.1 call void C::M2(object) ret } .method private static void M2(object o) { ret } }"; var source = @"class C { static object F() { return null; } static void M1() { object o = F(); M2(o); } static void M2(object o) { } }"; ImmutableArray<byte> assemblyBytes; ImmutableArray<byte> pdbBytes; EmitILToArray(ilSource, appendDefaultHeader: false, includePdb: false, assemblyBytes: out assemblyBytes, pdbBytes: out pdbBytes); var md0 = ModuleMetadata.CreateFromImage(assemblyBytes); // Still need a compilation with source for the initial // generation - to get a MethodSymbol and syntax map. var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source); var method0 = compilation0.GetMember<MethodSymbol>("C.M1"); var generation0 = EmitBaseline.CreateInitialBaseline(md0, m => default); var method1 = compilation1.GetMember<MethodSymbol>("C.M1"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true))); diff1.VerifyIL("C.M1", @"{ // Code size 15 (0xf) .maxstack 1 .locals init (object V_0) //o IL_0000: nop IL_0001: call ""object C.F()"" IL_0006: stloc.0 IL_0007: ldloc.0 IL_0008: call ""void C.M2(object)"" IL_000d: nop IL_000e: ret }"); } /// <summary> /// Should not re-use locals with custom modifiers. /// </summary> [WorkItem(9848, "https://github.com/dotnet/roslyn/issues/9848")] [Fact(Skip = "https://github.com/dotnet/roslyn/issues/9848")] public void LocalType_CustomModifiers() { // Equivalent method signature to C#, but // with optional modifier on locals. var ilSource = @".assembly extern mscorlib { .ver 4:0:0:0 .publickeytoken = (B7 7A 5C 56 19 34 E0 89) } .assembly '<<GeneratedFileName>>' { } .class public C { .method public specialname rtspecialname instance void .ctor() { ret } .method public static object F(class [mscorlib]System.IDisposable d) { .locals init ([0] class C modopt(int32) c, [1] class [mscorlib]System.IDisposable modopt(object), [2] bool V_2, [3] object V_3) ldnull ret } }"; var source = @"class C { static object F(System.IDisposable d) { C c; using (d) { c = (C)d; } return c; } }"; var metadata0 = (MetadataImageReference)CompileIL(ilSource, prependDefaultHeader: false); // Still need a compilation with source for the initial // generation - to get a MethodSymbol and syntax map. var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source); var moduleMetadata0 = ((AssemblyMetadata)metadata0.GetMetadataNoCopy()).GetModules()[0]; var method0 = compilation0.GetMember<MethodSymbol>("C.F"); var generation0 = EmitBaseline.CreateInitialBaseline( moduleMetadata0, m => default); var method1 = compilation1.GetMember<MethodSymbol>("C.F"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true))); diff1.VerifyIL("C.F", @" { // Code size 38 (0x26) .maxstack 1 .locals init ([unchanged] V_0, [unchanged] V_1, [bool] V_2, [object] V_3, C V_4, //c System.IDisposable V_5, object V_6) -IL_0000: nop -IL_0001: ldarg.0 IL_0002: stloc.s V_5 .try { -IL_0004: nop -IL_0005: ldarg.0 IL_0006: castclass ""C"" IL_000b: stloc.s V_4 -IL_000d: nop IL_000e: leave.s IL_001d } finally { ~IL_0010: ldloc.s V_5 IL_0012: brfalse.s IL_001c IL_0014: ldloc.s V_5 IL_0016: callvirt ""void System.IDisposable.Dispose()"" IL_001b: nop IL_001c: endfinally } -IL_001d: ldloc.s V_4 IL_001f: stloc.s V_6 IL_0021: br.s IL_0023 -IL_0023: ldloc.s V_6 IL_0025: ret }", methodToken: diff1.EmitResult.UpdatedMethods.Single()); } /// <summary> /// Temporaries for locals used within a single /// statement should not be preserved. /// </summary> [Fact] public void TemporaryLocals_Other() { // Use increment as an example of a compiler generated // temporary that does not span multiple statements. var source = @"class C { int P { get; set; } static int M() { var c = new C(); return c.P++; } }"; var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source); var testData0 = new CompilationTestData(); var bytes0 = compilation0.EmitToArray(testData: testData0); var methodData0 = testData0.GetMethodData("C.M"); var method0 = compilation0.GetMember<MethodSymbol>("C.M"); var generation0 = EmitBaseline.CreateInitialBaseline( ModuleMetadata.CreateFromImage(bytes0), methodData0.EncDebugInfoProvider()); var method1 = compilation1.GetMember<MethodSymbol>("C.M"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true))); diff1.VerifyIL("C.M", @" { // Code size 32 (0x20) .maxstack 3 .locals init (C V_0, //c [int] V_1, [int] V_2, int V_3, int V_4) IL_0000: nop IL_0001: newobj ""C..ctor()"" IL_0006: stloc.0 IL_0007: ldloc.0 IL_0008: dup IL_0009: callvirt ""int C.P.get"" IL_000e: stloc.3 IL_000f: ldloc.3 IL_0010: ldc.i4.1 IL_0011: add IL_0012: callvirt ""void C.P.set"" IL_0017: nop IL_0018: ldloc.3 IL_0019: stloc.s V_4 IL_001b: br.s IL_001d IL_001d: ldloc.s V_4 IL_001f: ret }"); } /// <summary> /// Local names array (from PDB) may have fewer slots than method /// signature (from metadata) when the trailing slots are unnamed. /// </summary> [WorkItem(782270, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/782270")] [Fact] public void Bug782270() { var source = @"class C { static System.IDisposable F() { return null; } static void M() { using (var o = F()) { } } }"; var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source); var testData0 = new CompilationTestData(); var bytes0 = compilation0.EmitToArray(testData: testData0); var methodData0 = testData0.GetMethodData("C.M"); var method0 = compilation0.GetMember<MethodSymbol>("C.M"); var generation0 = EmitBaseline.CreateInitialBaseline( ModuleMetadata.CreateFromImage(bytes0), testData0.GetMethodData("C.M").EncDebugInfoProvider()); testData0.GetMethodData("C.M").VerifyIL(@" { // Code size 23 (0x17) .maxstack 1 .locals init (System.IDisposable V_0) //o IL_0000: nop IL_0001: call ""System.IDisposable C.F()"" IL_0006: stloc.0 .try { IL_0007: nop IL_0008: nop IL_0009: leave.s IL_0016 } finally { IL_000b: ldloc.0 IL_000c: brfalse.s IL_0015 IL_000e: ldloc.0 IL_000f: callvirt ""void System.IDisposable.Dispose()"" IL_0014: nop IL_0015: endfinally } IL_0016: ret }"); var method1 = compilation1.GetMember<MethodSymbol>("C.M"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true))); diff1.VerifyIL("C.M", @" { // Code size 23 (0x17) .maxstack 1 .locals init (System.IDisposable V_0) //o IL_0000: nop IL_0001: call ""System.IDisposable C.F()"" IL_0006: stloc.0 .try { IL_0007: nop IL_0008: nop IL_0009: leave.s IL_0016 } finally { IL_000b: ldloc.0 IL_000c: brfalse.s IL_0015 IL_000e: ldloc.0 IL_000f: callvirt ""void System.IDisposable.Dispose()"" IL_0014: nop IL_0015: endfinally } IL_0016: ret }"); } /// <summary> /// Similar to above test but with no named locals in original. /// </summary> [WorkItem(782270, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/782270")] [Fact] public void Bug782270_NoNamedLocals() { // Equivalent to C#, but with unnamed locals. // Used to generate initial metadata. var ilSource = @".assembly extern netstandard { .ver 2:0:0:0 .publickeytoken = (cc 7b 13 ff cd 2d dd 51) } .assembly '<<GeneratedFileName>>' { } .class C extends object { .method private static class [netstandard]System.IDisposable F() { ldnull ret } .method private static void M() { .locals init ([0] object, [1] object) ret } }"; var source0 = @"class C { static System.IDisposable F() { return null; } static void M() { } }"; var source1 = @"class C { static System.IDisposable F() { return null; } static void M() { using (var o = F()) { } } }"; EmitILToArray(ilSource, appendDefaultHeader: false, includePdb: false, assemblyBytes: out var assemblyBytes, pdbBytes: out var pdbBytes); var md0 = ModuleMetadata.CreateFromImage(assemblyBytes); // Still need a compilation with source for the initial // generation - to get a MethodSymbol and syntax map. var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll, targetFramework: TargetFramework.NetStandard20); var compilation1 = compilation0.WithSource(source1); var method0 = compilation0.GetMember<MethodSymbol>("C.M"); var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider); var method1 = compilation1.GetMember<MethodSymbol>("C.M"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true))); diff1.VerifyIL("C.M", @" { // Code size 23 (0x17) .maxstack 1 .locals init ([object] V_0, [object] V_1, System.IDisposable V_2) //o IL_0000: nop IL_0001: call ""System.IDisposable C.F()"" IL_0006: stloc.2 .try { IL_0007: nop IL_0008: nop IL_0009: leave.s IL_0016 } finally { IL_000b: ldloc.2 IL_000c: brfalse.s IL_0015 IL_000e: ldloc.2 IL_000f: callvirt ""void System.IDisposable.Dispose()"" IL_0014: nop IL_0015: endfinally } IL_0016: ret } "); } [Fact] public void TemporaryLocals_ReferencedType() { var source = @"class C { static object F() { return null; } static void M() { var x = new System.Collections.Generic.HashSet<int>(); x.Add(1); } }"; var compilation0 = CreateCompilation(source, new[] { CSharpRef }, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source); var testData0 = new CompilationTestData(); var bytes0 = compilation0.EmitToArray(testData: testData0); var methodData0 = testData0.GetMethodData("C.M"); var method0 = compilation0.GetMember<MethodSymbol>("C.M"); var modMeta = ModuleMetadata.CreateFromImage(bytes0); var generation0 = EmitBaseline.CreateInitialBaseline( modMeta, methodData0.EncDebugInfoProvider()); var method1 = compilation1.GetMember<MethodSymbol>("C.M"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true))); diff1.VerifyIL("C.M", @" { // Code size 16 (0x10) .maxstack 2 .locals init (System.Collections.Generic.HashSet<int> V_0) //x IL_0000: nop IL_0001: newobj ""System.Collections.Generic.HashSet<int>..ctor()"" IL_0006: stloc.0 IL_0007: ldloc.0 IL_0008: ldc.i4.1 IL_0009: callvirt ""bool System.Collections.Generic.HashSet<int>.Add(int)"" IL_000e: pop IL_000f: ret } "); } [WorkItem(770502, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/770502")] [WorkItem(839565, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/839565")] [Fact] public void DynamicOperations() { var source = @"class A { static object F = null; object x = ((dynamic)F) + 1; static A() { ((dynamic)F).F(); } A() { } static void M(object o) { ((dynamic)o).x = 1; } static void N(A o) { o.x = 1; } } class B { static object F = null; static object G = ((dynamic)F).F(); object x = ((dynamic)F) + 1; }"; var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll, references: new[] { CSharpRef }); var compilation1 = compilation0.WithSource(source); var testData0 = new CompilationTestData(); var bytes0 = compilation0.EmitToArray(testData: testData0); using var md0 = ModuleMetadata.CreateFromImage(bytes0); // Source method with dynamic operations. var methodData0 = testData0.GetMethodData("A.M"); var generation0 = EmitBaseline.CreateInitialBaseline(md0, methodData0.EncDebugInfoProvider()); var method0 = compilation0.GetMember<MethodSymbol>("A.M"); var method1 = compilation1.GetMember<MethodSymbol>("A.M"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true))); diff1.EmitResult.Diagnostics.Verify(); // Source method with no dynamic operations. methodData0 = testData0.GetMethodData("A.N"); generation0 = EmitBaseline.CreateInitialBaseline(md0, methodData0.EncDebugInfoProvider()); method0 = compilation0.GetMember<MethodSymbol>("A.N"); method1 = compilation1.GetMember<MethodSymbol>("A.N"); diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true))); diff1.EmitResult.Diagnostics.Verify(); // Explicit .ctor with dynamic operations. methodData0 = testData0.GetMethodData("A..ctor"); generation0 = EmitBaseline.CreateInitialBaseline(md0, methodData0.EncDebugInfoProvider()); method0 = compilation0.GetMember<MethodSymbol>("A..ctor"); method1 = compilation1.GetMember<MethodSymbol>("A..ctor"); diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true))); diff1.EmitResult.Diagnostics.Verify(); // Explicit .cctor with dynamic operations. methodData0 = testData0.GetMethodData("A..cctor"); generation0 = EmitBaseline.CreateInitialBaseline(md0, methodData0.EncDebugInfoProvider()); method0 = compilation0.GetMember<MethodSymbol>("A..cctor"); method1 = compilation1.GetMember<MethodSymbol>("A..cctor"); diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true))); diff1.EmitResult.Diagnostics.Verify(); // Implicit .ctor with dynamic operations. methodData0 = testData0.GetMethodData("B..ctor"); generation0 = EmitBaseline.CreateInitialBaseline(md0, methodData0.EncDebugInfoProvider()); method0 = compilation0.GetMember<MethodSymbol>("B..ctor"); method1 = compilation1.GetMember<MethodSymbol>("B..ctor"); diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true))); diff1.EmitResult.Diagnostics.Verify(); // Implicit .cctor with dynamic operations. methodData0 = testData0.GetMethodData("B..cctor"); generation0 = EmitBaseline.CreateInitialBaseline(md0, methodData0.EncDebugInfoProvider()); method0 = compilation0.GetMember<MethodSymbol>("B..cctor"); method1 = compilation1.GetMember<MethodSymbol>("B..cctor"); diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true))); diff1.EmitResult.Diagnostics.Verify(); } [Fact] public void DynamicLocals() { var template = @" using System; class C { public void F() { dynamic <N:0>x = 1</N:0>; Console.WriteLine((int)x + <<VALUE>>); } } "; var source0 = MarkedSource(template.Replace("<<VALUE>>", "0")); var source1 = MarkedSource(template.Replace("<<VALUE>>", "1")); var source2 = MarkedSource(template.Replace("<<VALUE>>", "2")); var compilation0 = CreateCompilationWithMscorlib45(new[] { source0.Tree }, new[] { SystemCoreRef, CSharpRef }, options: ComSafeDebugDll); var compilation1 = compilation0.WithSource(source1.Tree); var compilation2 = compilation1.WithSource(source2.Tree); var v0 = CompileAndVerify(compilation0); v0.VerifyDiagnostics(); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var f0 = compilation0.GetMember<MethodSymbol>("C.F"); var f1 = compilation1.GetMember<MethodSymbol>("C.F"); var f2 = compilation2.GetMember<MethodSymbol>("C.F"); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); v0.VerifyIL("C.F", @" { // Code size 82 (0x52) .maxstack 3 .locals init (object V_0) //x IL_0000: nop IL_0001: ldc.i4.1 IL_0002: box ""int"" IL_0007: stloc.0 IL_0008: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>> C.<>o__0.<>p__0"" IL_000d: brfalse.s IL_0011 IL_000f: br.s IL_0036 IL_0011: ldc.i4.s 16 IL_0013: ldtoken ""int"" IL_0018: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_001d: ldtoken ""C"" IL_0022: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0027: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.Convert(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Type, System.Type)"" IL_002c: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0031: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>> C.<>o__0.<>p__0"" IL_0036: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>> C.<>o__0.<>p__0"" IL_003b: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>>.Target"" IL_0040: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>> C.<>o__0.<>p__0"" IL_0045: ldloc.0 IL_0046: callvirt ""int System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>.Invoke(System.Runtime.CompilerServices.CallSite, dynamic)"" IL_004b: call ""void System.Console.WriteLine(int)"" IL_0050: nop IL_0051: ret } "); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true))); diff1.VerifySynthesizedMembers( "C: {<>o__0#1}", "C.<>o__0#1: {<>p__0}"); diff1.VerifyIL("C.F", @" { // Code size 84 (0x54) .maxstack 3 .locals init (object V_0) //x IL_0000: nop IL_0001: ldc.i4.1 IL_0002: box ""int"" IL_0007: stloc.0 IL_0008: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>> C.<>o__0#1.<>p__0"" IL_000d: brfalse.s IL_0011 IL_000f: br.s IL_0036 IL_0011: ldc.i4.s 16 IL_0013: ldtoken ""int"" IL_0018: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_001d: ldtoken ""C"" IL_0022: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0027: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.Convert(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Type, System.Type)"" IL_002c: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0031: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>> C.<>o__0#1.<>p__0"" IL_0036: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>> C.<>o__0#1.<>p__0"" IL_003b: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>>.Target"" IL_0040: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>> C.<>o__0#1.<>p__0"" IL_0045: ldloc.0 IL_0046: callvirt ""int System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>.Invoke(System.Runtime.CompilerServices.CallSite, dynamic)"" IL_004b: ldc.i4.1 IL_004c: add IL_004d: call ""void System.Console.WriteLine(int)"" IL_0052: nop IL_0053: ret } "); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, f1, f2, GetSyntaxMapFromMarkers(source1, source2), preserveLocalVariables: true))); diff2.VerifySynthesizedMembers( "C: {<>o__0#2, <>o__0#1}", "C.<>o__0#1: {<>p__0}", "C.<>o__0#2: {<>p__0}"); diff2.VerifyIL("C.F", @" { // Code size 84 (0x54) .maxstack 3 .locals init (object V_0) //x IL_0000: nop IL_0001: ldc.i4.1 IL_0002: box ""int"" IL_0007: stloc.0 IL_0008: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>> C.<>o__0#2.<>p__0"" IL_000d: brfalse.s IL_0011 IL_000f: br.s IL_0036 IL_0011: ldc.i4.s 16 IL_0013: ldtoken ""int"" IL_0018: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_001d: ldtoken ""C"" IL_0022: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0027: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.Convert(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Type, System.Type)"" IL_002c: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0031: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>> C.<>o__0#2.<>p__0"" IL_0036: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>> C.<>o__0#2.<>p__0"" IL_003b: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>>.Target"" IL_0040: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>> C.<>o__0#2.<>p__0"" IL_0045: ldloc.0 IL_0046: callvirt ""int System.Func<System.Runtime.CompilerServices.CallSite, dynamic, int>.Invoke(System.Runtime.CompilerServices.CallSite, dynamic)"" IL_004b: ldc.i4.2 IL_004c: add IL_004d: call ""void System.Console.WriteLine(int)"" IL_0052: nop IL_0053: ret } "); } [Fact] public void ExceptionFilters() { var source0 = MarkedSource(@" using System; using System.IO; class C { static bool G(Exception e) => true; static void F() { try { throw new InvalidOperationException(); } catch <N:0>(IOException e)</N:0> <N:1>when (G(e))</N:1> { Console.WriteLine(); } catch <N:2>(Exception e)</N:2> <N:3>when (G(e))</N:3> { Console.WriteLine(); } } } "); var source1 = MarkedSource(@" using System; using System.IO; class C { static bool G(Exception e) => true; static void F() { try { throw new InvalidOperationException(); } catch <N:0>(IOException e)</N:0> <N:1>when (G(e))</N:1> { Console.WriteLine(); } catch <N:2>(Exception e)</N:2> <N:3>when (G(e))</N:3> { Console.WriteLine(); } Console.WriteLine(1); } }"); var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll); var compilation1 = compilation0.WithSource(source1.Tree); var v0 = CompileAndVerify(compilation0); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var f0 = compilation0.GetMember<MethodSymbol>("C.F"); var f1 = compilation1.GetMember<MethodSymbol>("C.F"); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true))); diff1.VerifyIL("C.F", @" { // Code size 90 (0x5a) .maxstack 2 .locals init (System.IO.IOException V_0, //e bool V_1, System.Exception V_2, //e bool V_3) IL_0000: nop .try { IL_0001: nop IL_0002: newobj ""System.InvalidOperationException..ctor()"" IL_0007: throw } filter { IL_0008: isinst ""System.IO.IOException"" IL_000d: dup IL_000e: brtrue.s IL_0014 IL_0010: pop IL_0011: ldc.i4.0 IL_0012: br.s IL_0020 IL_0014: stloc.0 IL_0015: ldloc.0 IL_0016: call ""bool C.G(System.Exception)"" IL_001b: stloc.1 IL_001c: ldloc.1 IL_001d: ldc.i4.0 IL_001e: cgt.un IL_0020: endfilter } // end filter { // handler IL_0022: pop IL_0023: nop IL_0024: call ""void System.Console.WriteLine()"" IL_0029: nop IL_002a: nop IL_002b: leave.s IL_0052 } filter { IL_002d: isinst ""System.Exception"" IL_0032: dup IL_0033: brtrue.s IL_0039 IL_0035: pop IL_0036: ldc.i4.0 IL_0037: br.s IL_0045 IL_0039: stloc.2 IL_003a: ldloc.2 IL_003b: call ""bool C.G(System.Exception)"" IL_0040: stloc.3 IL_0041: ldloc.3 IL_0042: ldc.i4.0 IL_0043: cgt.un IL_0045: endfilter } // end filter { // handler IL_0047: pop IL_0048: nop IL_0049: call ""void System.Console.WriteLine()"" IL_004e: nop IL_004f: nop IL_0050: leave.s IL_0052 } IL_0052: ldc.i4.1 IL_0053: call ""void System.Console.WriteLine(int)"" IL_0058: nop IL_0059: ret } "); } [ConditionalFact(typeof(WindowsDesktopOnly), Reason = ConditionalSkipReason.NoPiaNeedsDesktop)] public void MethodSignatureWithNoPIAType() { var sourcePIA = @" using System; using System.Runtime.InteropServices; [assembly: ImportedFromTypeLib(""_.dll"")] [assembly: Guid(""35DB1A6B-D635-4320-A062-28D42920E2A3"")] [ComImport()] [Guid(""35DB1A6B-D635-4320-A062-28D42920E2A4"")] public interface I { }"; var source0 = MarkedSource(@" class C { static void M(I x) { System.Console.WriteLine(1); } }"); var source1 = MarkedSource(@" class C { static void M(I x) { System.Console.WriteLine(2); } }"); var compilationPIA = CreateCompilation(sourcePIA, options: TestOptions.DebugDll); var referencePIA = compilationPIA.EmitToImageReference(embedInteropTypes: true); var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll, references: new MetadataReference[] { referencePIA }); var compilation1 = compilation0.WithSource(source1.Tree); var method0 = compilation0.GetMember<MethodSymbol>("C.M"); var method1 = compilation1.GetMember<MethodSymbol>("C.M"); var v0 = CompileAndVerify(compilation0); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true))); diff1.EmitResult.Diagnostics.Verify( // error CS7096: Cannot continue since the edit includes a reference to an embedded type: 'I'. Diagnostic(ErrorCode.ERR_EncNoPIAReference).WithArguments("I")); } [WorkItem(844472, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/844472")] [ConditionalFact(typeof(WindowsDesktopOnly), Reason = ConditionalSkipReason.NoPiaNeedsDesktop)] public void LocalSignatureWithNoPIAType() { var sourcePIA = @" using System; using System.Runtime.InteropServices; [assembly: ImportedFromTypeLib(""_.dll"")] [assembly: Guid(""35DB1A6B-D635-4320-A062-28D42920E2A3"")] [ComImport()] [Guid(""35DB1A6B-D635-4320-A062-28D42920E2A4"")] public interface I { }"; var source0 = MarkedSource(@" class C { static void M(I x) { I <N:0>y = null</N:0>; M(null); } }"); var source1 = MarkedSource(@" class C { static void M(I x) { I <N:0>y = null</N:0>; M(x); } }"); var compilationPIA = CreateCompilation(sourcePIA, options: TestOptions.DebugDll); var referencePIA = compilationPIA.EmitToImageReference(embedInteropTypes: true); var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll, references: new MetadataReference[] { referencePIA }); var compilation1 = compilation0.WithSource(source1.Tree); var method0 = compilation0.GetMember<MethodSymbol>("C.M"); var method1 = compilation1.GetMember<MethodSymbol>("C.M"); var v0 = CompileAndVerify(compilation0); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true))); diff1.EmitResult.Diagnostics.Verify( // (6,16): warning CS0219: The variable 'y' is assigned but its value is never used Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "y").WithArguments("y"), // error CS7096: Cannot continue since the edit includes a reference to an embedded type: 'I'. Diagnostic(ErrorCode.ERR_EncNoPIAReference).WithArguments("I")); } /// <summary> /// Disallow edits that require NoPIA references. /// </summary> [ConditionalFact(typeof(WindowsDesktopOnly), Reason = ConditionalSkipReason.NoPiaNeedsDesktop)] public void NoPIAReferences() { var sourcePIA = @"using System; using System.Runtime.InteropServices; [assembly: ImportedFromTypeLib(""_.dll"")] [assembly: Guid(""35DB1A6B-D635-4320-A062-28D42921E2B3"")] [ComImport()] [Guid(""35DB1A6B-D635-4320-A062-28D42921E2B4"")] public interface IA { void M(); int P { get; } event Action E; } [ComImport()] [Guid(""35DB1A6B-D635-4320-A062-28D42921E2B5"")] public interface IB { } [ComImport()] [Guid(""35DB1A6B-D635-4320-A062-28D42921E2B6"")] public interface IC { } public struct S { public object F; }"; var source0 = @"class C<T> { static object F = typeof(IC); static void M1() { var o = default(IA); o.M(); M2(o.P); o.E += M1; M2(C<IA>.F); M2(new S()); } static void M2(object o) { } }"; var source1A = source0; var source1B = @"class C<T> { static object F = typeof(IC); static void M1() { M2(null); } static void M2(object o) { } }"; var compilationPIA = CreateCompilation(sourcePIA, options: TestOptions.DebugDll); var referencePIA = compilationPIA.EmitToImageReference(embedInteropTypes: true); var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll, references: new MetadataReference[] { referencePIA, CSharpRef }); var compilation1A = compilation0.WithSource(source1A); var compilation1B = compilation0.WithSource(source1B); var method0 = compilation0.GetMember<MethodSymbol>("C.M1"); var method1B = compilation1B.GetMember<MethodSymbol>("C.M1"); var method1A = compilation1A.GetMember<MethodSymbol>("C.M1"); var testData0 = new CompilationTestData(); var bytes0 = compilation0.EmitToArray(testData: testData0); var methodData0 = testData0.GetMethodData("C<T>.M1"); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var reader0 = md0.MetadataReader; CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "C`1", "IA", "IC", "S"); var generation0 = EmitBaseline.CreateInitialBaseline(md0, methodData0.EncDebugInfoProvider()); // Disallow edits that require NoPIA references. var diff1A = compilation1A.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1A, GetEquivalentNodesMap(method1A, method0), preserveLocalVariables: true))); diff1A.EmitResult.Diagnostics.Verify( // error CS7094: Cannot continue since the edit includes a reference to an embedded type: 'S'. Diagnostic(ErrorCode.ERR_EncNoPIAReference).WithArguments("S"), // error CS7094: Cannot continue since the edit includes a reference to an embedded type: 'IA'. Diagnostic(ErrorCode.ERR_EncNoPIAReference).WithArguments("IA")); // Allow edits that do not require NoPIA references, // even if the previous code included references. var diff1B = compilation1B.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1B, GetEquivalentNodesMap(method1B, method0), preserveLocalVariables: true))); diff1B.VerifyIL("C<T>.M1", @"{ // Code size 9 (0x9) .maxstack 1 .locals init ([unchanged] V_0, [unchanged] V_1) IL_0000: nop IL_0001: ldnull IL_0002: call ""void C<T>.M2(object)"" IL_0007: nop IL_0008: ret }"); using var md1 = diff1B.GetMetadata(); var reader1 = md1.Reader; var readers = new[] { reader0, reader1 }; CheckNames(readers, reader1.GetTypeDefNames()); } [WorkItem(844536, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/844536")] [ConditionalFact(typeof(WindowsDesktopOnly), Reason = ConditionalSkipReason.NoPiaNeedsDesktop)] public void NoPIATypeInNamespace() { var sourcePIA = @"using System; using System.Runtime.InteropServices; [assembly: ImportedFromTypeLib(""_.dll"")] [assembly: Guid(""35DB1A6B-D635-4320-A062-28D42920E2A5"")] namespace N { [ComImport()] [Guid(""35DB1A6B-D635-4320-A062-28D42920E2A6"")] public interface IA { } } [ComImport()] [Guid(""35DB1A6B-D635-4320-A062-28D42920E2A7"")] public interface IB { }"; var source = @"class C<T> { static void M(object o) { M(C<N.IA>.E.X); M(C<IB>.E.X); } enum E { X } }"; var compilationPIA = CreateCompilation(sourcePIA, options: TestOptions.DebugDll); var referencePIA = compilationPIA.EmitToImageReference(embedInteropTypes: true); var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll, references: new MetadataReference[] { referencePIA, CSharpRef }); var compilation1 = compilation0.WithSource(source); var bytes0 = compilation0.EmitToArray(); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var generation0 = EmitBaseline.CreateInitialBaseline(md0, m => default); var method0 = compilation0.GetMember<MethodSymbol>("C.M"); var method1 = compilation1.GetMember<MethodSymbol>("C.M"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1))); diff1.EmitResult.Diagnostics.Verify( // error CS7094: Cannot continue since the edit includes a reference to an embedded type: 'N.IA'. Diagnostic(ErrorCode.ERR_EncNoPIAReference).WithArguments("N.IA"), // error CS7094: Cannot continue since the edit includes a reference to an embedded type: 'IB'. Diagnostic(ErrorCode.ERR_EncNoPIAReference).WithArguments("IB")); diff1.VerifyIL("C<T>.M", @"{ // Code size 26 (0x1a) .maxstack 1 IL_0000: nop IL_0001: ldc.i4.0 IL_0002: box ""C<N.IA>.E"" IL_0007: call ""void C<T>.M(object)"" IL_000c: nop IL_000d: ldc.i4.0 IL_000e: box ""C<IB>.E"" IL_0013: call ""void C<T>.M(object)"" IL_0018: nop IL_0019: ret }"); } /// <summary> /// Should use TypeDef rather than TypeRef for unrecognized /// local of a type defined in the original assembly. /// </summary> [WorkItem(910777, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/910777")] [Fact] public void UnrecognizedLocalOfTypeFromAssembly() { var source = @"class E : System.Exception { } class C { static void M() { try { } catch (E e) { } } }"; var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll, targetFramework: TargetFramework.NetStandard20); var compilation1 = compilation0.WithSource(source); var testData0 = new CompilationTestData(); var bytes0 = compilation0.EmitToArray(testData: testData0); var methodData0 = testData0.GetMethodData("C.M"); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var reader0 = md0.MetadataReader; CheckNames(reader0, reader0.GetAssemblyRefNames(), "netstandard"); var method0 = compilation0.GetMember<MethodSymbol>("C.M"); var method1 = compilation1.GetMember<MethodSymbol>("C.M"); var generation0 = EmitBaseline.CreateInitialBaseline(md0, methodData0.EncDebugInfoProvider()); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables: true))); using var md1 = diff1.GetMetadata(); var reader1 = md1.Reader; var readers = new[] { reader0, reader1 }; CheckNames(readers, reader1.GetAssemblyRefNames(), "netstandard"); CheckNames(readers, reader1.GetTypeRefNames(), "Object"); CheckEncLog(reader1, Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default), Row(7, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(2, TableIndex.StandAloneSig, EditAndContinueOperation.Default), Row(2, TableIndex.MethodDef, EditAndContinueOperation.Default)); CheckEncMap(reader1, Handle(7, TableIndex.TypeRef), Handle(2, TableIndex.MethodDef), Handle(2, TableIndex.StandAloneSig), Handle(2, TableIndex.AssemblyRef)); diff1.VerifyIL("C.M", @" { // Code size 11 (0xb) .maxstack 1 .locals init (E V_0) //e IL_0000: nop .try { IL_0001: nop IL_0002: nop IL_0003: leave.s IL_000a } catch E { IL_0005: stloc.0 IL_0006: nop IL_0007: nop IL_0008: leave.s IL_000a } IL_000a: ret }"); } /// <summary> /// Similar to above test but with anonymous type /// added in subsequent generation. /// </summary> [WorkItem(910777, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/910777")] [Fact] public void UnrecognizedLocalOfAnonymousTypeFromAssembly() { var source0 = @"class C { static string F() { return null; } static string G() { var o = new { Y = 1 }; return o.ToString(); } }"; var source1 = @"class C { static string F() { var o = new { X = 1 }; return o.ToString(); } static string G() { var o = new { Y = 1 }; return o.ToString(); } }"; var source2 = @"class C { static string F() { return null; } static string G() { return null; } }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll, targetFramework: TargetFramework.NetStandard20); var compilation1 = compilation0.WithSource(source1); var compilation2 = compilation1.WithSource(source2); var method0F = compilation0.GetMember<MethodSymbol>("C.F"); var method1F = compilation1.GetMember<MethodSymbol>("C.F"); var method1G = compilation1.GetMember<MethodSymbol>("C.G"); var method2F = compilation2.GetMember<MethodSymbol>("C.F"); var method2G = compilation2.GetMember<MethodSymbol>("C.G"); var bytes0 = compilation0.EmitToArray(); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var reader0 = md0.MetadataReader; CheckNames(reader0, reader0.GetAssemblyRefNames(), "netstandard"); // Use empty LocalVariableNameProvider for original locals and // use preserveLocalVariables: true for the edit so that existing // locals are retained even though all are unrecognized. var generation0 = EmitBaseline.CreateInitialBaseline( md0, EmptyLocalsProvider); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0F, method1F, syntaxMap: s => null, preserveLocalVariables: true))); using var md1 = diff1.GetMetadata(); var reader1 = md1.Reader; var readers = new List<MetadataReader> { reader0, reader1 }; CheckNames(readers, reader1.GetAssemblyRefNames(), "netstandard"); CheckNames(readers, reader1.GetTypeDefNames(), "<>f__AnonymousType1`1"); CheckNames(readers, reader1.GetTypeRefNames(), "CompilerGeneratedAttribute", "DebuggerDisplayAttribute", "Object", "DebuggerBrowsableState", "DebuggerBrowsableAttribute", "DebuggerHiddenAttribute", "EqualityComparer`1", "String", "IFormatProvider"); // Change method updated in generation 1. var diff2F = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method1F, method2F, syntaxMap: s => null, preserveLocalVariables: true))); using var md2 = diff2F.GetMetadata(); var reader2 = md2.Reader; readers.Add(reader2); CheckNames(readers, reader2.GetAssemblyRefNames(), "netstandard"); CheckNames(readers, reader2.GetTypeDefNames()); CheckNames(readers, reader2.GetTypeRefNames(), "Object"); // Change method unchanged since generation 0. var diff2G = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method1G, method2G, syntaxMap: s => null, preserveLocalVariables: true))); } [Fact] public void BrokenOutputStreams() { var source0 = @"class C { static string F() { return null; } }"; var source1 = @"class C { static string F() { var o = new { X = 1 }; return o.ToString(); } }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var bytes0 = compilation0.EmitToArray(); using (new EnsureEnglishUICulture()) using (var md0 = ModuleMetadata.CreateFromImage(bytes0)) { var method0F = compilation0.GetMember<MethodSymbol>("C.F"); var generation0 = EmitBaseline.CreateInitialBaseline( md0, EmptyLocalsProvider); var method1F = compilation1.GetMember<MethodSymbol>("C.F"); using MemoryStream mdStream = new MemoryStream(), ilStream = new MemoryStream(), pdbStream = new MemoryStream(); var isAddedSymbol = new Func<ISymbol, bool>(s => false); var badStream = new BrokenStream(); badStream.BreakHow = BrokenStream.BreakHowType.ThrowOnWrite; var result = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0F, method1F, syntaxMap: s => null, preserveLocalVariables: true)), isAddedSymbol, badStream, ilStream, pdbStream, new CompilationTestData(), default); Assert.False(result.Success); result.Diagnostics.Verify( // error CS8104: An error occurred while writing the output file: System.IO.IOException: I/O error occurred. Diagnostic(ErrorCode.ERR_PeWritingFailure).WithArguments(badStream.ThrownException.ToString()).WithLocation(1, 1) ); result = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0F, method1F, syntaxMap: s => null, preserveLocalVariables: true)), isAddedSymbol, mdStream, badStream, pdbStream, new CompilationTestData(), default); Assert.False(result.Success); result.Diagnostics.Verify( // error CS8104: An error occurred while writing the output file: System.IO.IOException: I/O error occurred. Diagnostic(ErrorCode.ERR_PeWritingFailure).WithArguments(badStream.ThrownException.ToString()).WithLocation(1, 1) ); result = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0F, method1F, syntaxMap: s => null, preserveLocalVariables: true)), isAddedSymbol, mdStream, ilStream, badStream, new CompilationTestData(), default); Assert.False(result.Success); result.Diagnostics.Verify( // error CS0041: Unexpected error writing debug information -- 'I/O error occurred.' Diagnostic(ErrorCode.FTL_DebugEmitFailure).WithArguments("I/O error occurred.").WithLocation(1, 1) ); } } [Fact] public void BrokenPortablePdbStream() { var source0 = @"class C { static string F() { return null; } }"; var source1 = @"class C { static string F() { var o = new { X = 1 }; return o.ToString(); } }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); var bytes0 = compilation0.EmitToArray(EmitOptions.Default.WithDebugInformationFormat(DebugInformationFormat.PortablePdb)); using (new EnsureEnglishUICulture()) using (var md0 = ModuleMetadata.CreateFromImage(bytes0)) { var method0F = compilation0.GetMember<MethodSymbol>("C.F"); var generation0 = EmitBaseline.CreateInitialBaseline( md0, EmptyLocalsProvider); var method1F = compilation1.GetMember<MethodSymbol>("C.F"); using MemoryStream mdStream = new MemoryStream(), ilStream = new MemoryStream(), pdbStream = new MemoryStream(); var isAddedSymbol = new Func<ISymbol, bool>(s => false); var badStream = new BrokenStream(); badStream.BreakHow = BrokenStream.BreakHowType.ThrowOnWrite; var result = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0F, method1F, syntaxMap: s => null, preserveLocalVariables: true)), isAddedSymbol, mdStream, ilStream, badStream, new CompilationTestData(), default); Assert.False(result.Success); result.Diagnostics.Verify( // error CS0041: Unexpected error writing debug information -- 'I/O error occurred.' Diagnostic(ErrorCode.FTL_DebugEmitFailure).WithArguments("I/O error occurred.").WithLocation(1, 1) ); } } [WorkItem(923492, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/923492")] [ConditionalFact(typeof(WindowsDesktopOnly), Reason = ConditionalSkipReason.NativePdbRequiresDesktop)] public void SymWriterErrors() { var source0 = @"class C { }"; var source1 = @"class C { static void Main() { } }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll); var compilation1 = compilation0.WithSource(source1); // Verify full metadata contains expected rows. var bytes0 = compilation0.EmitToArray(); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var diff1 = compilation1.EmitDifference( EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider), ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Insert, null, compilation1.GetMember<MethodSymbol>("C.Main"))), testData: new CompilationTestData { SymWriterFactory = _ => new MockSymUnmanagedWriter() }); diff1.EmitResult.Diagnostics.Verify( // error CS0041: Unexpected error writing debug information -- 'MockSymUnmanagedWriter error message' Diagnostic(ErrorCode.FTL_DebugEmitFailure).WithArguments("MockSymUnmanagedWriter error message")); Assert.False(diff1.EmitResult.Success); } [WorkItem(1058058, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1058058")] [Fact] public void BlobContainsInvalidValues() { var source0 = @"class C { static void F() { string goo = ""abc""; } }"; var source1 = @"class C { static void F() { float goo = 10; } }"; var source2 = @"class C { static void F() { bool goo = true; } }"; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugDll, targetFramework: TargetFramework.NetStandard20); var compilation1 = compilation0.WithSource(source1); var compilation2 = compilation1.WithSource(source2); var bytes0 = compilation0.EmitToArray(); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var reader0 = md0.MetadataReader; CheckNames(reader0, reader0.GetAssemblyRefNames(), "netstandard"); var method0F = compilation0.GetMember<MethodSymbol>("C.F"); var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider); var method1F = compilation1.GetMember<MethodSymbol>("C.F"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0F, method1F, syntaxMap: s => null, preserveLocalVariables: true))); var handle = MetadataTokens.BlobHandle(1); byte[] value0 = reader0.GetBlobBytes(handle); Assert.Equal("20-01-01-08", BitConverter.ToString(value0)); using var md1 = diff1.GetMetadata(); var reader1 = md1.Reader; var method2F = compilation2.GetMember<MethodSymbol>("C.F"); var diff2F = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method1F, method2F, syntaxMap: s => null, preserveLocalVariables: true))); byte[] value1 = reader1.GetBlobBytes(handle); Assert.Equal("07-02-0E-0C", BitConverter.ToString(value1)); using var md2 = diff2F.GetMetadata(); var reader2 = md2.Reader; byte[] value2 = reader2.GetBlobBytes(handle); Assert.Equal("07-03-0E-0C-02", BitConverter.ToString(value2)); } [Fact] public void ReferenceToMemberAddedToAnotherAssembly1() { var sourceA0 = @" public class A { } "; var sourceA1 = @" public class A { public void M() { System.Console.WriteLine(1);} } public class X {} "; var sourceB0 = @" public class B { public static void F() { } }"; var sourceB1 = @" public class B { public static void F() { new A().M(); } } public class Y : X { } "; var compilationA0 = CreateCompilation(sourceA0, options: TestOptions.DebugDll, assemblyName: "LibA"); var compilationA1 = compilationA0.WithSource(sourceA1); var compilationB0 = CreateCompilation(sourceB0, new[] { compilationA0.ToMetadataReference() }, options: TestOptions.DebugDll, assemblyName: "LibB"); var compilationB1 = CreateCompilation(sourceB1, new[] { compilationA1.ToMetadataReference() }, options: TestOptions.DebugDll, assemblyName: "LibB"); var bytesA0 = compilationA0.EmitToArray(); var bytesB0 = compilationB0.EmitToArray(); var mdA0 = ModuleMetadata.CreateFromImage(bytesA0); var mdB0 = ModuleMetadata.CreateFromImage(bytesB0); var generationA0 = EmitBaseline.CreateInitialBaseline(mdA0, EmptyLocalsProvider); var generationB0 = EmitBaseline.CreateInitialBaseline(mdB0, EmptyLocalsProvider); var mA1 = compilationA1.GetMember<MethodSymbol>("A.M"); var mX1 = compilationA1.GetMember<TypeSymbol>("X"); var allAddedSymbols = new ISymbol[] { mA1.GetPublicSymbol(), mX1.GetPublicSymbol() }; var diffA1 = compilationA1.EmitDifference( generationA0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Insert, null, mA1), SemanticEdit.Create(SemanticEditKind.Insert, null, mX1)), allAddedSymbols); diffA1.EmitResult.Diagnostics.Verify(); var diffB1 = compilationB1.EmitDifference( generationB0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, compilationB0.GetMember<MethodSymbol>("B.F"), compilationB1.GetMember<MethodSymbol>("B.F")), SemanticEdit.Create(SemanticEditKind.Insert, null, compilationB1.GetMember<TypeSymbol>("Y"))), allAddedSymbols); diffB1.EmitResult.Diagnostics.Verify( // (7,14): error CS7101: Member 'X' added during the current debug session can only be accessed from within its declaring assembly 'LibA'. // public class X {} Diagnostic(ErrorCode.ERR_EncReferenceToAddedMember, "X").WithArguments("X", "LibA").WithLocation(7, 14), // (4,17): error CS7101: Member 'M' added during the current debug session can only be accessed from within its declaring assembly 'LibA'. // public void M() { System.Console.WriteLine(1);} Diagnostic(ErrorCode.ERR_EncReferenceToAddedMember, "M").WithArguments("M", "LibA").WithLocation(4, 17)); } [Fact] public void ReferenceToMemberAddedToAnotherAssembly2() { var sourceA = @" public class A { public void M() { } }"; var sourceB0 = @" public class B { public static void F() { var a = new A(); } }"; var sourceB1 = @" public class B { public static void F() { var a = new A(); a.M(); } }"; var sourceB2 = @" public class B { public static void F() { var a = new A(); } }"; var compilationA = CreateCompilation(sourceA, options: TestOptions.DebugDll, assemblyName: "AssemblyA"); var aRef = compilationA.ToMetadataReference(); var compilationB0 = CreateCompilation(sourceB0, new[] { aRef }, options: TestOptions.DebugDll, assemblyName: "AssemblyB"); var compilationB1 = compilationB0.WithSource(sourceB1); var compilationB2 = compilationB1.WithSource(sourceB2); var testDataB0 = new CompilationTestData(); var bytesB0 = compilationB0.EmitToArray(testData: testDataB0); var mdB0 = ModuleMetadata.CreateFromImage(bytesB0); var generationB0 = EmitBaseline.CreateInitialBaseline(mdB0, testDataB0.GetMethodData("B.F").EncDebugInfoProvider()); var f0 = compilationB0.GetMember<MethodSymbol>("B.F"); var f1 = compilationB1.GetMember<MethodSymbol>("B.F"); var f2 = compilationB2.GetMember<MethodSymbol>("B.F"); var diffB1 = compilationB1.EmitDifference( generationB0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetEquivalentNodesMap(f1, f0), preserveLocalVariables: true))); diffB1.VerifyIL("B.F", @" { // Code size 15 (0xf) .maxstack 1 .locals init (A V_0) //a IL_0000: nop IL_0001: newobj ""A..ctor()"" IL_0006: stloc.0 IL_0007: ldloc.0 IL_0008: callvirt ""void A.M()"" IL_000d: nop IL_000e: ret } "); var diffB2 = compilationB2.EmitDifference( diffB1.NextGeneration, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, f1, f2, GetEquivalentNodesMap(f2, f1), preserveLocalVariables: true))); diffB2.VerifyIL("B.F", @" { // Code size 8 (0x8) .maxstack 1 .locals init (A V_0) //a IL_0000: nop IL_0001: newobj ""A..ctor()"" IL_0006: stloc.0 IL_0007: ret } "); } [ConditionalFact(typeof(WindowsDesktopOnly), Reason = ConditionalSkipReason.TestExecutionNeedsDesktopTypes)] public void UniqueSynthesizedNames_DynamicSiteContainer() { var source0 = @" public class C { public static void F(dynamic d) { d.Goo(); } }"; var source1 = @" public class C { public static void F(dynamic d) { d.Bar(); } }"; var source2 = @" public class C { public static void F(dynamic d, byte b) { d.Bar(); } public static void F(dynamic d) { d.Bar(); } }"; var compilation0 = CreateCompilation(source0, targetFramework: TargetFramework.StandardAndCSharp, options: ComSafeDebugDll.WithMetadataImportOptions(MetadataImportOptions.All), assemblyName: "A"); var compilation1 = compilation0.WithSource(source1); var compilation2 = compilation1.WithSource(source2); var f0 = compilation0.GetMember<MethodSymbol>("C.F"); var f1 = compilation1.GetMember<MethodSymbol>("C.F"); var f_byte2 = compilation2.GetMembers("C.F").Single(m => m.ToString() == "C.F(dynamic, byte)"); var v0 = CompileAndVerify(compilation0); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, f0, f1, preserveLocalVariables: true))); diff1.EmitResult.Diagnostics.Verify(); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Insert, null, f_byte2))); diff2.EmitResult.Diagnostics.Verify(); var reader0 = md0.MetadataReader; var reader1 = diff1.GetMetadata().Reader; var reader2 = diff2.GetMetadata().Reader; CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "C", "<>o__0"); CheckNames(new[] { reader0, reader1 }, reader1.GetTypeDefNames(), "<>o__0#1"); CheckNames(new[] { reader0, reader1, reader2 }, reader2.GetTypeDefNames(), "<>o__0#2"); } [WorkItem(918650, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/918650")] [Fact] public void ManyGenerations() { var source = @"class C {{ static int F() {{ return {0}; }} }}"; var compilation0 = CreateCompilation(String.Format(source, 1), options: TestOptions.DebugDll); var bytes0 = compilation0.EmitToArray(); var md0 = ModuleMetadata.CreateFromImage(bytes0); var generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider); var method0 = compilation0.GetMember<MethodSymbol>("C.F"); for (int i = 2; i <= 50; i++) { var compilation1 = compilation0.WithSource(String.Format(source, i)); var method1 = compilation1.GetMember<MethodSymbol>("C.F"); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1))); compilation0 = compilation1; method0 = method1; generation0 = diff1.NextGeneration; } } [WorkItem(187868, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/187868")] [Fact] public void PdbReadingErrors() { var source0 = MarkedSource(@" using System; class C { static void F() { <N:0>Console.WriteLine(1);</N:0> } }"); var source1 = MarkedSource(@" using System; class C { static void F() { <N:0>Console.WriteLine(2);</N:0> } }"); var compilation0 = CreateCompilation(source0.Tree, options: TestOptions.DebugDll, assemblyName: "PdbReadingErrorsAssembly"); var compilation1 = compilation0.WithSource(source1.Tree); var v0 = CompileAndVerify(compilation0); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var f0 = compilation0.GetMember<MethodSymbol>("C.F"); var f1 = compilation1.GetMember<MethodSymbol>("C.F"); var generation0 = EmitBaseline.CreateInitialBaseline(md0, methodHandle => { throw new InvalidDataException("Bad PDB!"); }); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true))); diff1.EmitResult.Diagnostics.Verify( // (6,14): error CS7038: Failed to emit module 'Unable to read debug information of method 'C.F()' (token 0x06000001) from assembly 'PdbReadingErrorsAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null''. Diagnostic(ErrorCode.ERR_InvalidDebugInfo, "F").WithArguments("C.F()", "100663297", "PdbReadingErrorsAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(6, 14)); } [Fact] public void PdbReadingErrors_PassThruExceptions() { var source0 = MarkedSource(@" using System; class C { static void F() { <N:0>Console.WriteLine(1);</N:0> } }"); var source1 = MarkedSource(@" using System; class C { static void F() { <N:0>Console.WriteLine(2);</N:0> } }"); var compilation0 = CreateCompilation(source0.Tree, options: TestOptions.DebugDll, assemblyName: "PdbReadingErrorsAssembly"); var compilation1 = compilation0.WithSource(source1.Tree); var v0 = CompileAndVerify(compilation0); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var f0 = compilation0.GetMember<MethodSymbol>("C.F"); var f1 = compilation1.GetMember<MethodSymbol>("C.F"); var generation0 = EmitBaseline.CreateInitialBaseline(md0, methodHandle => { throw new ArgumentOutOfRangeException(); }); // the compiler should't swallow any exceptions but InvalidDataException Assert.Throws<ArgumentOutOfRangeException>(() => compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true)))); } [Fact] public void PatternVariable_TypeChange() { var source0 = MarkedSource(@" class C { static int F(object o) { if (o is int <N:0>i</N:0>) { return i; } return 0; } }"); var source1 = MarkedSource(@" class C { static int F(object o) { if (o is bool <N:0>i</N:0>) { return i ? 1 : 0; } return 0; } }"); var source2 = MarkedSource(@" class C { static int F(object o) { if (o is int <N:0>j</N:0>) { return j; } return 0; } }"); var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll); var compilation1 = compilation0.WithSource(source1.Tree); var compilation2 = compilation1.WithSource(source2.Tree); var f0 = compilation0.GetMember<MethodSymbol>("C.F"); var f1 = compilation1.GetMember<MethodSymbol>("C.F"); var f2 = compilation2.GetMember<MethodSymbol>("C.F"); var v0 = CompileAndVerify(compilation0); v0.VerifyIL("C.F", @" { // Code size 35 (0x23) .maxstack 1 .locals init (int V_0, //i bool V_1, int V_2) IL_0000: nop IL_0001: ldarg.0 IL_0002: isinst ""int"" IL_0007: brfalse.s IL_0013 IL_0009: ldarg.0 IL_000a: unbox.any ""int"" IL_000f: stloc.0 IL_0010: ldc.i4.1 IL_0011: br.s IL_0014 IL_0013: ldc.i4.0 IL_0014: stloc.1 IL_0015: ldloc.1 IL_0016: brfalse.s IL_001d IL_0018: nop IL_0019: ldloc.0 IL_001a: stloc.2 IL_001b: br.s IL_0021 IL_001d: ldc.i4.0 IL_001e: stloc.2 IL_001f: br.s IL_0021 IL_0021: ldloc.2 IL_0022: ret }"); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true))); diff1.VerifyIL("C.F", @" { // Code size 46 (0x2e) .maxstack 1 .locals init ([int] V_0, [bool] V_1, [int] V_2, bool V_3, //i bool V_4, int V_5) IL_0000: nop IL_0001: ldarg.0 IL_0002: isinst ""bool"" IL_0007: brfalse.s IL_0013 IL_0009: ldarg.0 IL_000a: unbox.any ""bool"" IL_000f: stloc.3 IL_0010: ldc.i4.1 IL_0011: br.s IL_0014 IL_0013: ldc.i4.0 IL_0014: stloc.s V_4 IL_0016: ldloc.s V_4 IL_0018: brfalse.s IL_0026 IL_001a: nop IL_001b: ldloc.3 IL_001c: brtrue.s IL_0021 IL_001e: ldc.i4.0 IL_001f: br.s IL_0022 IL_0021: ldc.i4.1 IL_0022: stloc.s V_5 IL_0024: br.s IL_002b IL_0026: ldc.i4.0 IL_0027: stloc.s V_5 IL_0029: br.s IL_002b IL_002b: ldloc.s V_5 IL_002d: ret }"); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, f1, f2, GetSyntaxMapFromMarkers(source1, source2), preserveLocalVariables: true))); diff2.VerifyIL("C.F", @" { // Code size 42 (0x2a) .maxstack 1 .locals init ([int] V_0, [bool] V_1, [int] V_2, [bool] V_3, [bool] V_4, [int] V_5, int V_6, //j bool V_7, int V_8) IL_0000: nop IL_0001: ldarg.0 IL_0002: isinst ""int"" IL_0007: brfalse.s IL_0014 IL_0009: ldarg.0 IL_000a: unbox.any ""int"" IL_000f: stloc.s V_6 IL_0011: ldc.i4.1 IL_0012: br.s IL_0015 IL_0014: ldc.i4.0 IL_0015: stloc.s V_7 IL_0017: ldloc.s V_7 IL_0019: brfalse.s IL_0022 IL_001b: nop IL_001c: ldloc.s V_6 IL_001e: stloc.s V_8 IL_0020: br.s IL_0027 IL_0022: ldc.i4.0 IL_0023: stloc.s V_8 IL_0025: br.s IL_0027 IL_0027: ldloc.s V_8 IL_0029: ret }"); } [Fact] public void PatternVariable_DeleteInsert() { var source0 = MarkedSource(@" class C { static int F(object o) { if (o is int <N:0>i</N:0>) { return i; } return 0; } }"); var source1 = MarkedSource(@" class C { static int F(object o) { if (o is int) { return 1; } return 0; } }"); var source2 = MarkedSource(@" class C { static int F(object o) { if (o is int <N:0>i</N:0>) { return i; } return 0; } }"); var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll); var compilation1 = compilation0.WithSource(source1.Tree); var compilation2 = compilation1.WithSource(source2.Tree); var f0 = compilation0.GetMember<MethodSymbol>("C.F"); var f1 = compilation1.GetMember<MethodSymbol>("C.F"); var f2 = compilation2.GetMember<MethodSymbol>("C.F"); var v0 = CompileAndVerify(compilation0); v0.VerifyIL("C.F", @" { // Code size 35 (0x23) .maxstack 1 .locals init (int V_0, //i bool V_1, int V_2) IL_0000: nop IL_0001: ldarg.0 IL_0002: isinst ""int"" IL_0007: brfalse.s IL_0013 IL_0009: ldarg.0 IL_000a: unbox.any ""int"" IL_000f: stloc.0 IL_0010: ldc.i4.1 IL_0011: br.s IL_0014 IL_0013: ldc.i4.0 IL_0014: stloc.1 IL_0015: ldloc.1 IL_0016: brfalse.s IL_001d IL_0018: nop IL_0019: ldloc.0 IL_001a: stloc.2 IL_001b: br.s IL_0021 IL_001d: ldc.i4.0 IL_001e: stloc.2 IL_001f: br.s IL_0021 IL_0021: ldloc.2 IL_0022: ret }"); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true))); diff1.VerifyIL("C.F", @" { // Code size 28 (0x1c) .maxstack 2 .locals init ([int] V_0, [bool] V_1, [int] V_2, bool V_3, int V_4) IL_0000: nop IL_0001: ldarg.0 IL_0002: isinst ""int"" IL_0007: ldnull IL_0008: cgt.un IL_000a: stloc.3 IL_000b: ldloc.3 IL_000c: brfalse.s IL_0014 IL_000e: nop IL_000f: ldc.i4.1 IL_0010: stloc.s V_4 IL_0012: br.s IL_0019 IL_0014: ldc.i4.0 IL_0015: stloc.s V_4 IL_0017: br.s IL_0019 IL_0019: ldloc.s V_4 IL_001b: ret }"); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, f1, f2, GetSyntaxMapFromMarkers(source1, source2), preserveLocalVariables: true))); diff2.VerifyIL("C.F", @" { // Code size 42 (0x2a) .maxstack 1 .locals init ([int] V_0, [bool] V_1, [int] V_2, [bool] V_3, [int] V_4, int V_5, //i bool V_6, int V_7) IL_0000: nop IL_0001: ldarg.0 IL_0002: isinst ""int"" IL_0007: brfalse.s IL_0014 IL_0009: ldarg.0 IL_000a: unbox.any ""int"" IL_000f: stloc.s V_5 IL_0011: ldc.i4.1 IL_0012: br.s IL_0015 IL_0014: ldc.i4.0 IL_0015: stloc.s V_6 IL_0017: ldloc.s V_6 IL_0019: brfalse.s IL_0022 IL_001b: nop IL_001c: ldloc.s V_5 IL_001e: stloc.s V_7 IL_0020: br.s IL_0027 IL_0022: ldc.i4.0 IL_0023: stloc.s V_7 IL_0025: br.s IL_0027 IL_0027: ldloc.s V_7 IL_0029: ret }"); } [Fact] public void PatternVariable_InConstructorInitializer() { var baseClass = "public class Base { public Base(bool x) { } }"; var source0 = MarkedSource(@" public class C : Base { public C(int a) : base(a is int <N:0>x</N:0> && x == 0 && a is int <N:1>y</N:1>) { y = 1; } }" + baseClass); var source1 = MarkedSource(@" public class C : Base { public C(int a) : base(a is int <N:0>x</N:0> && x == 0) { } }" + baseClass); var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll); var compilation1 = compilation0.WithSource(source1.Tree); var compilation2 = compilation1.WithSource(source0.Tree); var ctor0 = compilation0.GetMember<MethodSymbol>("C..ctor"); var ctor1 = compilation1.GetMember<MethodSymbol>("C..ctor"); var ctor2 = compilation2.GetMember<MethodSymbol>("C..ctor"); var v0 = CompileAndVerify(compilation0); v0.VerifyIL("C..ctor", @" { // Code size 22 (0x16) .maxstack 2 .locals init (int V_0, //x int V_1) //y IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: stloc.0 IL_0003: ldloc.0 IL_0004: brtrue.s IL_000b IL_0006: ldarg.1 IL_0007: stloc.1 IL_0008: ldc.i4.1 IL_0009: br.s IL_000c IL_000b: ldc.i4.0 IL_000c: call ""Base..ctor(bool)"" IL_0011: nop IL_0012: nop IL_0013: ldc.i4.1 IL_0014: stloc.1 IL_0015: ret } "); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, ctor0, ctor1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true))); diff1.VerifyIL("C..ctor", @" { // Code size 15 (0xf) .maxstack 3 .locals init (int V_0, //x [int] V_1) IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: stloc.0 IL_0003: ldloc.0 IL_0004: ldc.i4.0 IL_0005: ceq IL_0007: call ""Base..ctor(bool)"" IL_000c: nop IL_000d: nop IL_000e: ret } "); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, ctor1, ctor2, GetSyntaxMapFromMarkers(source1, source0), preserveLocalVariables: true))); diff2.VerifyIL("C..ctor", @" { // Code size 22 (0x16) .maxstack 2 .locals init (int V_0, //x [int] V_1, int V_2) //y IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: stloc.0 IL_0003: ldloc.0 IL_0004: brtrue.s IL_000b IL_0006: ldarg.1 IL_0007: stloc.2 IL_0008: ldc.i4.1 IL_0009: br.s IL_000c IL_000b: ldc.i4.0 IL_000c: call ""Base..ctor(bool)"" IL_0011: nop IL_0012: nop IL_0013: ldc.i4.1 IL_0014: stloc.2 IL_0015: ret } "); } [Fact] public void PatternVariable_InFieldInitializer() { var source0 = MarkedSource(@" public class C { public static int a = 0; public bool field = a is int <N:0>x</N:0> && x == 0 && a is int <N:1>y</N:1>; }"); var source1 = MarkedSource(@" public class C { public static int a = 0; public bool field = a is int <N:0>x</N:0> && x == 0; }"); var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll); var compilation1 = compilation0.WithSource(source1.Tree); var compilation2 = compilation1.WithSource(source0.Tree); var ctor0 = compilation0.GetMember<MethodSymbol>("C..ctor"); var ctor1 = compilation1.GetMember<MethodSymbol>("C..ctor"); var ctor2 = compilation2.GetMember<MethodSymbol>("C..ctor"); var v0 = CompileAndVerify(compilation0); v0.VerifyIL("C..ctor", @" { // Code size 33 (0x21) .maxstack 2 .locals init (int V_0, //x int V_1) //y IL_0000: ldarg.0 IL_0001: ldsfld ""int C.a"" IL_0006: stloc.0 IL_0007: ldloc.0 IL_0008: brtrue.s IL_0013 IL_000a: ldsfld ""int C.a"" IL_000f: stloc.1 IL_0010: ldc.i4.1 IL_0011: br.s IL_0014 IL_0013: ldc.i4.0 IL_0014: stfld ""bool C.field"" IL_0019: ldarg.0 IL_001a: call ""object..ctor()"" IL_001f: nop IL_0020: ret } "); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, ctor0, ctor1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true))); diff1.VerifyIL("C..ctor", @" { // Code size 24 (0x18) .maxstack 3 .locals init (int V_0, //x [int] V_1) IL_0000: ldarg.0 IL_0001: ldsfld ""int C.a"" IL_0006: stloc.0 IL_0007: ldloc.0 IL_0008: ldc.i4.0 IL_0009: ceq IL_000b: stfld ""bool C.field"" IL_0010: ldarg.0 IL_0011: call ""object..ctor()"" IL_0016: nop IL_0017: ret } "); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, ctor1, ctor2, GetSyntaxMapFromMarkers(source1, source0), preserveLocalVariables: true))); diff2.VerifyIL("C..ctor", @" { // Code size 33 (0x21) .maxstack 2 .locals init (int V_0, //x [int] V_1, int V_2) //y IL_0000: ldarg.0 IL_0001: ldsfld ""int C.a"" IL_0006: stloc.0 IL_0007: ldloc.0 IL_0008: brtrue.s IL_0013 IL_000a: ldsfld ""int C.a"" IL_000f: stloc.2 IL_0010: ldc.i4.1 IL_0011: br.s IL_0014 IL_0013: ldc.i4.0 IL_0014: stfld ""bool C.field"" IL_0019: ldarg.0 IL_001a: call ""object..ctor()"" IL_001f: nop IL_0020: ret } "); } [Fact] public void PatternVariable_InQuery() { var source0 = MarkedSource(@" using System.Linq; public class Program { static void N() { var <N:0>query = from a in new int[] { 1, 2 } <N:1>select a is int <N:2>x</N:2> && x == 0 && a is int <N:3>y</N:3></N:1></N:0>; } }"); var source1 = MarkedSource(@" using System.Linq; public class Program { static int M(int x, out int y) { y = 42; return 43; } static void N() { var <N:0>query = from a in new int[] { 1, 2 } <N:1>select a is int <N:2>x</N:2> && x == 0</N:1></N:0>; } }"); var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll); var compilation1 = compilation0.WithSource(source1.Tree); var compilation2 = compilation1.WithSource(source0.Tree); var n0 = compilation0.GetMember<MethodSymbol>("Program.N"); var n1 = compilation1.GetMember<MethodSymbol>("Program.N"); var n2 = compilation2.GetMember<MethodSymbol>("Program.N"); var v0 = CompileAndVerify(compilation0); v0.VerifyIL("Program.N()", @" { // Code size 53 (0x35) .maxstack 4 .locals init (System.Collections.Generic.IEnumerable<bool> V_0) //query IL_0000: nop IL_0001: ldc.i4.2 IL_0002: newarr ""int"" IL_0007: dup IL_0008: ldc.i4.0 IL_0009: ldc.i4.1 IL_000a: stelem.i4 IL_000b: dup IL_000c: ldc.i4.1 IL_000d: ldc.i4.2 IL_000e: stelem.i4 IL_000f: ldsfld ""System.Func<int, bool> Program.<>c.<>9__0_0"" IL_0014: dup IL_0015: brtrue.s IL_002e IL_0017: pop IL_0018: ldsfld ""Program.<>c Program.<>c.<>9"" IL_001d: ldftn ""bool Program.<>c.<N>b__0_0(int)"" IL_0023: newobj ""System.Func<int, bool>..ctor(object, System.IntPtr)"" IL_0028: dup IL_0029: stsfld ""System.Func<int, bool> Program.<>c.<>9__0_0"" IL_002e: call ""System.Collections.Generic.IEnumerable<bool> System.Linq.Enumerable.Select<int, bool>(System.Collections.Generic.IEnumerable<int>, System.Func<int, bool>)"" IL_0033: stloc.0 IL_0034: ret } "); v0.VerifyIL("Program.<>c.<N>b__0_0(int)", @" { // Code size 12 (0xc) .maxstack 1 .locals init (int V_0, //x int V_1) //y IL_0000: ldarg.1 IL_0001: stloc.0 IL_0002: ldloc.0 IL_0003: brtrue.s IL_000a IL_0005: ldarg.1 IL_0006: stloc.1 IL_0007: ldc.i4.1 IL_0008: br.s IL_000b IL_000a: ldc.i4.0 IL_000b: ret } "); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, n0, n1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true))); diff1.VerifySynthesizedMembers("Program: {<>c}", "Program.<>c: {<>9__0_0, <N>b__0_0}"); diff1.VerifyIL("Program.N()", @" { // Code size 53 (0x35) .maxstack 4 .locals init (System.Collections.Generic.IEnumerable<bool> V_0) //query IL_0000: nop IL_0001: ldc.i4.2 IL_0002: newarr ""int"" IL_0007: dup IL_0008: ldc.i4.0 IL_0009: ldc.i4.1 IL_000a: stelem.i4 IL_000b: dup IL_000c: ldc.i4.1 IL_000d: ldc.i4.2 IL_000e: stelem.i4 IL_000f: ldsfld ""System.Func<int, bool> Program.<>c.<>9__0_0"" IL_0014: dup IL_0015: brtrue.s IL_002e IL_0017: pop IL_0018: ldsfld ""Program.<>c Program.<>c.<>9"" IL_001d: ldftn ""bool Program.<>c.<N>b__0_0(int)"" IL_0023: newobj ""System.Func<int, bool>..ctor(object, System.IntPtr)"" IL_0028: dup IL_0029: stsfld ""System.Func<int, bool> Program.<>c.<>9__0_0"" IL_002e: call ""System.Collections.Generic.IEnumerable<bool> System.Linq.Enumerable.Select<int, bool>(System.Collections.Generic.IEnumerable<int>, System.Func<int, bool>)"" IL_0033: stloc.0 IL_0034: ret } "); diff1.VerifyIL("Program.<>c.<N>b__0_0(int)", @" { // Code size 7 (0x7) .maxstack 2 .locals init (int V_0, //x [int] V_1) IL_0000: ldarg.1 IL_0001: stloc.0 IL_0002: ldloc.0 IL_0003: ldc.i4.0 IL_0004: ceq IL_0006: ret } "); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, n1, n2, GetSyntaxMapFromMarkers(source1, source0), preserveLocalVariables: true))); diff2.VerifySynthesizedMembers("Program: {<>c}", "Program.<>c: {<>9__0_0, <N>b__0_0}"); diff2.VerifyIL("Program.N()", @" { // Code size 53 (0x35) .maxstack 4 .locals init (System.Collections.Generic.IEnumerable<bool> V_0) //query IL_0000: nop IL_0001: ldc.i4.2 IL_0002: newarr ""int"" IL_0007: dup IL_0008: ldc.i4.0 IL_0009: ldc.i4.1 IL_000a: stelem.i4 IL_000b: dup IL_000c: ldc.i4.1 IL_000d: ldc.i4.2 IL_000e: stelem.i4 IL_000f: ldsfld ""System.Func<int, bool> Program.<>c.<>9__0_0"" IL_0014: dup IL_0015: brtrue.s IL_002e IL_0017: pop IL_0018: ldsfld ""Program.<>c Program.<>c.<>9"" IL_001d: ldftn ""bool Program.<>c.<N>b__0_0(int)"" IL_0023: newobj ""System.Func<int, bool>..ctor(object, System.IntPtr)"" IL_0028: dup IL_0029: stsfld ""System.Func<int, bool> Program.<>c.<>9__0_0"" IL_002e: call ""System.Collections.Generic.IEnumerable<bool> System.Linq.Enumerable.Select<int, bool>(System.Collections.Generic.IEnumerable<int>, System.Func<int, bool>)"" IL_0033: stloc.0 IL_0034: ret } "); diff2.VerifyIL("Program.<>c.<N>b__0_0(int)", @" { // Code size 12 (0xc) .maxstack 1 .locals init (int V_0, //x [int] V_1, int V_2) //y IL_0000: ldarg.1 IL_0001: stloc.0 IL_0002: ldloc.0 IL_0003: brtrue.s IL_000a IL_0005: ldarg.1 IL_0006: stloc.2 IL_0007: ldc.i4.1 IL_0008: br.s IL_000b IL_000a: ldc.i4.0 IL_000b: ret } "); } [Fact] public void Tuple_Parenthesized() { var source0 = MarkedSource(@" class C { static int F() { (int, (int, int)) <N:0>x</N:0> = (1, (2, 3)); return x.Item1 + x.Item2.Item1 + x.Item2.Item2; } }"); var source1 = MarkedSource(@" class C { static int F() { (int, int, int) <N:0>x</N:0> = (1, 2, 3); return x.Item1 + x.Item2 + x.Item3; } }"); var source2 = MarkedSource(@" class C { static int F() { (int, int) <N:0>x</N:0> = (1, 3); return x.Item1 + x.Item2; } }"); var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll); var compilation1 = compilation0.WithSource(source1.Tree); var compilation2 = compilation1.WithSource(source2.Tree); var f0 = compilation0.GetMember<MethodSymbol>("C.F"); var f1 = compilation1.GetMember<MethodSymbol>("C.F"); var f2 = compilation2.GetMember<MethodSymbol>("C.F"); var v0 = CompileAndVerify(compilation0); v0.VerifyIL("C.F", @" { // Code size 51 (0x33) .maxstack 4 .locals init (System.ValueTuple<int, System.ValueTuple<int, int>> V_0, //x int V_1) IL_0000: nop IL_0001: ldloca.s V_0 IL_0003: ldc.i4.1 IL_0004: ldc.i4.2 IL_0005: ldc.i4.3 IL_0006: newobj ""System.ValueTuple<int, int>..ctor(int, int)"" IL_000b: call ""System.ValueTuple<int, System.ValueTuple<int, int>>..ctor(int, System.ValueTuple<int, int>)"" IL_0010: ldloc.0 IL_0011: ldfld ""int System.ValueTuple<int, System.ValueTuple<int, int>>.Item1"" IL_0016: ldloc.0 IL_0017: ldfld ""System.ValueTuple<int, int> System.ValueTuple<int, System.ValueTuple<int, int>>.Item2"" IL_001c: ldfld ""int System.ValueTuple<int, int>.Item1"" IL_0021: add IL_0022: ldloc.0 IL_0023: ldfld ""System.ValueTuple<int, int> System.ValueTuple<int, System.ValueTuple<int, int>>.Item2"" IL_0028: ldfld ""int System.ValueTuple<int, int>.Item2"" IL_002d: add IL_002e: stloc.1 IL_002f: br.s IL_0031 IL_0031: ldloc.1 IL_0032: ret } "); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true))); diff1.VerifyIL("C.F", @" { // Code size 36 (0x24) .maxstack 4 .locals init ([unchanged] V_0, [int] V_1, System.ValueTuple<int, int, int> V_2, //x int V_3) IL_0000: nop IL_0001: ldloca.s V_2 IL_0003: ldc.i4.1 IL_0004: ldc.i4.2 IL_0005: ldc.i4.3 IL_0006: call ""System.ValueTuple<int, int, int>..ctor(int, int, int)"" IL_000b: ldloc.2 IL_000c: ldfld ""int System.ValueTuple<int, int, int>.Item1"" IL_0011: ldloc.2 IL_0012: ldfld ""int System.ValueTuple<int, int, int>.Item2"" IL_0017: add IL_0018: ldloc.2 IL_0019: ldfld ""int System.ValueTuple<int, int, int>.Item3"" IL_001e: add IL_001f: stloc.3 IL_0020: br.s IL_0022 IL_0022: ldloc.3 IL_0023: ret } "); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, f1, f2, GetSyntaxMapFromMarkers(source1, source2), preserveLocalVariables: true))); diff2.VerifyIL("C.F", @" { // Code size 32 (0x20) .maxstack 3 .locals init ([unchanged] V_0, [int] V_1, [unchanged] V_2, [int] V_3, System.ValueTuple<int, int> V_4, //x int V_5) IL_0000: nop IL_0001: ldloca.s V_4 IL_0003: ldc.i4.1 IL_0004: ldc.i4.3 IL_0005: call ""System.ValueTuple<int, int>..ctor(int, int)"" IL_000a: ldloc.s V_4 IL_000c: ldfld ""int System.ValueTuple<int, int>.Item1"" IL_0011: ldloc.s V_4 IL_0013: ldfld ""int System.ValueTuple<int, int>.Item2"" IL_0018: add IL_0019: stloc.s V_5 IL_001b: br.s IL_001d IL_001d: ldloc.s V_5 IL_001f: ret } "); } [Fact] public void Tuple_Decomposition() { var source0 = MarkedSource(@" class C { static int F() { (int <N:0>x</N:0>, int <N:1>y</N:1>, int <N:2>z</N:2>) = (1, 2, 3); return x + y + z; } }"); var source1 = MarkedSource(@" class C { static int F() { (int <N:0>x</N:0>, int <N:2>z</N:2>) = (1, 3); return x + z; } }"); var source2 = MarkedSource(@" class C { static int F() { (int <N:0>x</N:0>, int <N:1>y</N:1>, int <N:2>z</N:2>) = (1, 2, 3); return x + y + z; } }"); var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll); var compilation1 = compilation0.WithSource(source1.Tree); var compilation2 = compilation1.WithSource(source2.Tree); var f0 = compilation0.GetMember<MethodSymbol>("C.F"); var f1 = compilation1.GetMember<MethodSymbol>("C.F"); var f2 = compilation2.GetMember<MethodSymbol>("C.F"); var v0 = CompileAndVerify(compilation0); v0.VerifyIL("C.F", @" { // Code size 17 (0x11) .maxstack 2 .locals init (int V_0, //x int V_1, //y int V_2, //z int V_3) IL_0000: nop IL_0001: ldc.i4.1 IL_0002: stloc.0 IL_0003: ldc.i4.2 IL_0004: stloc.1 IL_0005: ldc.i4.3 IL_0006: stloc.2 IL_0007: ldloc.0 IL_0008: ldloc.1 IL_0009: add IL_000a: ldloc.2 IL_000b: add IL_000c: stloc.3 IL_000d: br.s IL_000f IL_000f: ldloc.3 IL_0010: ret } "); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true))); diff1.VerifyIL("C.F", @" { // Code size 15 (0xf) .maxstack 2 .locals init (int V_0, //x [int] V_1, int V_2, //z [int] V_3, int V_4) IL_0000: nop IL_0001: ldc.i4.1 IL_0002: stloc.0 IL_0003: ldc.i4.3 IL_0004: stloc.2 IL_0005: ldloc.0 IL_0006: ldloc.2 IL_0007: add IL_0008: stloc.s V_4 IL_000a: br.s IL_000c IL_000c: ldloc.s V_4 IL_000e: ret } "); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, f1, f2, GetSyntaxMapFromMarkers(source1, source2), preserveLocalVariables: true))); diff2.VerifyIL("C.F", @" { // Code size 21 (0x15) .maxstack 2 .locals init (int V_0, //x [int] V_1, int V_2, //z [int] V_3, [int] V_4, int V_5, //y int V_6) IL_0000: nop IL_0001: ldc.i4.1 IL_0002: stloc.0 IL_0003: ldc.i4.2 IL_0004: stloc.s V_5 IL_0006: ldc.i4.3 IL_0007: stloc.2 IL_0008: ldloc.0 IL_0009: ldloc.s V_5 IL_000b: add IL_000c: ldloc.2 IL_000d: add IL_000e: stloc.s V_6 IL_0010: br.s IL_0012 IL_0012: ldloc.s V_6 IL_0014: ret } "); } [Fact] public void ForeachStatement() { var source0 = MarkedSource(@" class C { public static (int, (bool, double))[] F() => new[] { (1, (true, 2.0)) }; public static void G() { foreach (var (<N:0>x</N:0>, (<N:1>y</N:1>, <N:2>z</N:2>)) in F()) { System.Console.WriteLine(x); } } }"); var source1 = MarkedSource(@" class C { public static (int, (bool, double))[] F() => new[] { (1, (true, 2.0)) }; public static void G() { foreach (var (<N:0>x1</N:0>, (<N:1>y</N:1>, <N:2>z</N:2>)) in F()) { System.Console.WriteLine(x1); } } }"); var source2 = MarkedSource(@" class C { public static (int, (bool, double))[] F() => new[] { (1, (true, 2.0)) }; public static void G() { foreach (var (<N:0>x1</N:0>, <N:1>yz</N:1>) in F()) { System.Console.WriteLine(x1); } } }"); var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll); var compilation1 = compilation0.WithSource(source1.Tree); var compilation2 = compilation1.WithSource(source2.Tree); var f0 = compilation0.GetMember<MethodSymbol>("C.G"); var f1 = compilation1.GetMember<MethodSymbol>("C.G"); var f2 = compilation2.GetMember<MethodSymbol>("C.G"); var v0 = CompileAndVerify(compilation0); v0.VerifyIL("C.G", @" { // Code size 70 (0x46) .maxstack 2 .locals init (System.ValueTuple<int, System.ValueTuple<bool, double>>[] V_0, int V_1, int V_2, //x bool V_3, //y double V_4, //z System.ValueTuple<bool, double> V_5) IL_0000: nop IL_0001: nop IL_0002: call ""System.ValueTuple<int, System.ValueTuple<bool, double>>[] C.F()"" IL_0007: stloc.0 IL_0008: ldc.i4.0 IL_0009: stloc.1 IL_000a: br.s IL_003f IL_000c: ldloc.0 IL_000d: ldloc.1 IL_000e: ldelem ""System.ValueTuple<int, System.ValueTuple<bool, double>>"" IL_0013: dup IL_0014: ldfld ""System.ValueTuple<bool, double> System.ValueTuple<int, System.ValueTuple<bool, double>>.Item2"" IL_0019: stloc.s V_5 IL_001b: ldfld ""int System.ValueTuple<int, System.ValueTuple<bool, double>>.Item1"" IL_0020: stloc.2 IL_0021: ldloc.s V_5 IL_0023: ldfld ""bool System.ValueTuple<bool, double>.Item1"" IL_0028: stloc.3 IL_0029: ldloc.s V_5 IL_002b: ldfld ""double System.ValueTuple<bool, double>.Item2"" IL_0030: stloc.s V_4 IL_0032: nop IL_0033: ldloc.2 IL_0034: call ""void System.Console.WriteLine(int)"" IL_0039: nop IL_003a: nop IL_003b: ldloc.1 IL_003c: ldc.i4.1 IL_003d: add IL_003e: stloc.1 IL_003f: ldloc.1 IL_0040: ldloc.0 IL_0041: ldlen IL_0042: conv.i4 IL_0043: blt.s IL_000c IL_0045: ret } "); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true))); diff1.VerifyIL("C.G", @" { // Code size 78 (0x4e) .maxstack 2 .locals init ([unchanged] V_0, [int] V_1, int V_2, //x1 bool V_3, //y double V_4, //z [unchanged] V_5, System.ValueTuple<int, System.ValueTuple<bool, double>>[] V_6, int V_7, System.ValueTuple<bool, double> V_8) IL_0000: nop IL_0001: nop IL_0002: call ""System.ValueTuple<int, System.ValueTuple<bool, double>>[] C.F()"" IL_0007: stloc.s V_6 IL_0009: ldc.i4.0 IL_000a: stloc.s V_7 IL_000c: br.s IL_0045 IL_000e: ldloc.s V_6 IL_0010: ldloc.s V_7 IL_0012: ldelem ""System.ValueTuple<int, System.ValueTuple<bool, double>>"" IL_0017: dup IL_0018: ldfld ""System.ValueTuple<bool, double> System.ValueTuple<int, System.ValueTuple<bool, double>>.Item2"" IL_001d: stloc.s V_8 IL_001f: ldfld ""int System.ValueTuple<int, System.ValueTuple<bool, double>>.Item1"" IL_0024: stloc.2 IL_0025: ldloc.s V_8 IL_0027: ldfld ""bool System.ValueTuple<bool, double>.Item1"" IL_002c: stloc.3 IL_002d: ldloc.s V_8 IL_002f: ldfld ""double System.ValueTuple<bool, double>.Item2"" IL_0034: stloc.s V_4 IL_0036: nop IL_0037: ldloc.2 IL_0038: call ""void System.Console.WriteLine(int)"" IL_003d: nop IL_003e: nop IL_003f: ldloc.s V_7 IL_0041: ldc.i4.1 IL_0042: add IL_0043: stloc.s V_7 IL_0045: ldloc.s V_7 IL_0047: ldloc.s V_6 IL_0049: ldlen IL_004a: conv.i4 IL_004b: blt.s IL_000e IL_004d: ret } "); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, f1, f2, GetSyntaxMapFromMarkers(source1, source2), preserveLocalVariables: true))); diff2.VerifyIL("C.G", @" { // Code size 61 (0x3d) .maxstack 2 .locals init ([unchanged] V_0, [int] V_1, int V_2, //x1 [bool] V_3, [unchanged] V_4, [unchanged] V_5, [unchanged] V_6, [int] V_7, [unchanged] V_8, System.ValueTuple<int, System.ValueTuple<bool, double>>[] V_9, int V_10, System.ValueTuple<bool, double> V_11) //yz IL_0000: nop IL_0001: nop IL_0002: call ""System.ValueTuple<int, System.ValueTuple<bool, double>>[] C.F()"" IL_0007: stloc.s V_9 IL_0009: ldc.i4.0 IL_000a: stloc.s V_10 IL_000c: br.s IL_0034 IL_000e: ldloc.s V_9 IL_0010: ldloc.s V_10 IL_0012: ldelem ""System.ValueTuple<int, System.ValueTuple<bool, double>>"" IL_0017: dup IL_0018: ldfld ""int System.ValueTuple<int, System.ValueTuple<bool, double>>.Item1"" IL_001d: stloc.2 IL_001e: ldfld ""System.ValueTuple<bool, double> System.ValueTuple<int, System.ValueTuple<bool, double>>.Item2"" IL_0023: stloc.s V_11 IL_0025: nop IL_0026: ldloc.2 IL_0027: call ""void System.Console.WriteLine(int)"" IL_002c: nop IL_002d: nop IL_002e: ldloc.s V_10 IL_0030: ldc.i4.1 IL_0031: add IL_0032: stloc.s V_10 IL_0034: ldloc.s V_10 IL_0036: ldloc.s V_9 IL_0038: ldlen IL_0039: conv.i4 IL_003a: blt.s IL_000e IL_003c: ret } "); } [Fact] public void OutVar() { var source0 = MarkedSource(@" class C { static void F(out int x, out int y) { x = 1; y = 2; } static int G() { F(out int <N:0>x</N:0>, out var <N:1>y</N:1>); return x + y; } }"); var source1 = MarkedSource(@" class C { static void F(out int x, out int y) { x = 1; y = 2; } static int G() { F(out int <N:0>x</N:0>, out var <N:1>z</N:1>); return x + z; } }"); var source2 = MarkedSource(@" class C { static void F(out int x, out int y) { x = 1; y = 2; } static int G() { F(out int <N:0>x</N:0>, out int <N:1>y</N:1>); return x + y; } }"); var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll); var compilation1 = compilation0.WithSource(source1.Tree); var compilation2 = compilation1.WithSource(source2.Tree); var f0 = compilation0.GetMember<MethodSymbol>("C.G"); var f1 = compilation1.GetMember<MethodSymbol>("C.G"); var f2 = compilation2.GetMember<MethodSymbol>("C.G"); var v0 = CompileAndVerify(compilation0); v0.VerifyIL("C.G", @" { // Code size 19 (0x13) .maxstack 2 .locals init (int V_0, //x int V_1, //y int V_2) IL_0000: nop IL_0001: ldloca.s V_0 IL_0003: ldloca.s V_1 IL_0005: call ""void C.F(out int, out int)"" IL_000a: nop IL_000b: ldloc.0 IL_000c: ldloc.1 IL_000d: add IL_000e: stloc.2 IL_000f: br.s IL_0011 IL_0011: ldloc.2 IL_0012: ret } "); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true))); diff1.VerifyIL("C.G", @" { // Code size 19 (0x13) .maxstack 2 .locals init (int V_0, //x int V_1, //z [int] V_2, int V_3) IL_0000: nop IL_0001: ldloca.s V_0 IL_0003: ldloca.s V_1 IL_0005: call ""void C.F(out int, out int)"" IL_000a: nop IL_000b: ldloc.0 IL_000c: ldloc.1 IL_000d: add IL_000e: stloc.3 IL_000f: br.s IL_0011 IL_0011: ldloc.3 IL_0012: ret } "); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, f1, f2, GetSyntaxMapFromMarkers(source1, source2), preserveLocalVariables: true))); diff2.VerifyIL("C.G", @" { // Code size 21 (0x15) .maxstack 2 .locals init (int V_0, //x int V_1, //y [int] V_2, [int] V_3, int V_4) IL_0000: nop IL_0001: ldloca.s V_0 IL_0003: ldloca.s V_1 IL_0005: call ""void C.F(out int, out int)"" IL_000a: nop IL_000b: ldloc.0 IL_000c: ldloc.1 IL_000d: add IL_000e: stloc.s V_4 IL_0010: br.s IL_0012 IL_0012: ldloc.s V_4 IL_0014: ret } "); } [Fact] public void OutVar_InConstructorInitializer() { var baseClass = "public class Base { public Base(int x) { } }"; var source0 = MarkedSource(@" public class C : Base { public C() : base(M(out int <N:0>x</N:0>) + x + M(out int <N:1>y</N:1>)) { System.Console.Write(y); } static int M(out int x) => throw null; }" + baseClass); var source1 = MarkedSource(@" public class C : Base { public C() : base(M(out int <N:0>x</N:0>) + x) { } static int M(out int x) => throw null; }" + baseClass); var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll); var compilation1 = compilation0.WithSource(source1.Tree); var compilation2 = compilation1.WithSource(source0.Tree); var ctor0 = compilation0.GetMember<MethodSymbol>("C..ctor"); var ctor1 = compilation1.GetMember<MethodSymbol>("C..ctor"); var ctor2 = compilation2.GetMember<MethodSymbol>("C..ctor"); var v0 = CompileAndVerify(compilation0); v0.VerifyIL("C..ctor", @" { // Code size 33 (0x21) .maxstack 3 .locals init (int V_0, //x int V_1) //y IL_0000: ldarg.0 IL_0001: ldloca.s V_0 IL_0003: call ""int C.M(out int)"" IL_0008: ldloc.0 IL_0009: add IL_000a: ldloca.s V_1 IL_000c: call ""int C.M(out int)"" IL_0011: add IL_0012: call ""Base..ctor(int)"" IL_0017: nop IL_0018: nop IL_0019: ldloc.1 IL_001a: call ""void System.Console.Write(int)"" IL_001f: nop IL_0020: ret } "); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, ctor0, ctor1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true))); diff1.VerifyIL("C..ctor", @" { // Code size 18 (0x12) .maxstack 3 .locals init (int V_0, //x [int] V_1) IL_0000: ldarg.0 IL_0001: ldloca.s V_0 IL_0003: call ""int C.M(out int)"" IL_0008: ldloc.0 IL_0009: add IL_000a: call ""Base..ctor(int)"" IL_000f: nop IL_0010: nop IL_0011: ret } "); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, ctor1, ctor2, GetSyntaxMapFromMarkers(source1, source0), preserveLocalVariables: true))); diff2.VerifyIL("C..ctor", @" { // Code size 33 (0x21) .maxstack 3 .locals init (int V_0, //x [int] V_1, int V_2) //y IL_0000: ldarg.0 IL_0001: ldloca.s V_0 IL_0003: call ""int C.M(out int)"" IL_0008: ldloc.0 IL_0009: add IL_000a: ldloca.s V_2 IL_000c: call ""int C.M(out int)"" IL_0011: add IL_0012: call ""Base..ctor(int)"" IL_0017: nop IL_0018: nop IL_0019: ldloc.2 IL_001a: call ""void System.Console.Write(int)"" IL_001f: nop IL_0020: ret } "); } [Fact] public void OutVar_InConstructorInitializer_WithLambda() { var baseClass = "public class Base { public Base(int x) { } }"; var source0 = MarkedSource(@" public class C : Base { <N:0>public C() : base(M(out int <N:1>x</N:1>) + M2(<N:2>() => x + 1</N:2>)) { }</N:0> static int M(out int x) => throw null; static int M2(System.Func<int> x) => throw null; }" + baseClass); var source1 = MarkedSource(@" public class C : Base { <N:0>public C() : base(M(out int <N:1>x</N:1>) + M2(<N:2>() => x - 1</N:2>)) { }</N:0> static int M(out int x) => throw null; static int M2(System.Func<int> x) => throw null; }" + baseClass); var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll); var compilation1 = compilation0.WithSource(source1.Tree); var compilation2 = compilation1.WithSource(source0.Tree); var ctor0 = compilation0.GetMember<MethodSymbol>("C..ctor"); var ctor1 = compilation1.GetMember<MethodSymbol>("C..ctor"); var ctor2 = compilation2.GetMember<MethodSymbol>("C..ctor"); var v0 = CompileAndVerify(compilation0); v0.VerifyIL("C..ctor", @" { // Code size 44 (0x2c) .maxstack 4 .locals init (C.<>c__DisplayClass0_0 V_0) //CS$<>8__locals0 IL_0000: newobj ""C.<>c__DisplayClass0_0..ctor()"" IL_0005: stloc.0 IL_0006: ldarg.0 IL_0007: ldloc.0 IL_0008: ldflda ""int C.<>c__DisplayClass0_0.x"" IL_000d: call ""int C.M(out int)"" IL_0012: ldloc.0 IL_0013: ldftn ""int C.<>c__DisplayClass0_0.<.ctor>b__0()"" IL_0019: newobj ""System.Func<int>..ctor(object, System.IntPtr)"" IL_001e: call ""int C.M2(System.Func<int>)"" IL_0023: add IL_0024: call ""Base..ctor(int)"" IL_0029: nop IL_002a: nop IL_002b: ret } "); v0.VerifyIL("C.<>c__DisplayClass0_0.<.ctor>b__0()", @" { // Code size 9 (0x9) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldfld ""int C.<>c__DisplayClass0_0.x"" IL_0006: ldc.i4.1 IL_0007: add IL_0008: ret } "); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var reader0 = md0.MetadataReader; var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, ctor0, ctor1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true))); using var md1 = diff1.GetMetadata(); var reader1 = md1.Reader; var readers = new[] { reader0, reader1 }; CheckNames(readers, diff1.EmitResult.ChangedTypes, "C", "<>c__DisplayClass0_0"); diff1.VerifySynthesizedMembers( "C: {<>c__DisplayClass0_0}", "C.<>c__DisplayClass0_0: {x, <.ctor>b__0}"); diff1.VerifyIL("C..ctor", @" { // Code size 44 (0x2c) .maxstack 4 .locals init (C.<>c__DisplayClass0_0 V_0) //CS$<>8__locals0 IL_0000: newobj ""C.<>c__DisplayClass0_0..ctor()"" IL_0005: stloc.0 IL_0006: ldarg.0 IL_0007: ldloc.0 IL_0008: ldflda ""int C.<>c__DisplayClass0_0.x"" IL_000d: call ""int C.M(out int)"" IL_0012: ldloc.0 IL_0013: ldftn ""int C.<>c__DisplayClass0_0.<.ctor>b__0()"" IL_0019: newobj ""System.Func<int>..ctor(object, System.IntPtr)"" IL_001e: call ""int C.M2(System.Func<int>)"" IL_0023: add IL_0024: call ""Base..ctor(int)"" IL_0029: nop IL_002a: nop IL_002b: ret } "); diff1.VerifyIL("C.<>c__DisplayClass0_0.<.ctor>b__0()", @" { // Code size 9 (0x9) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldfld ""int C.<>c__DisplayClass0_0.x"" IL_0006: ldc.i4.1 IL_0007: sub IL_0008: ret } "); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, ctor1, ctor2, GetSyntaxMapFromMarkers(source1, source0), preserveLocalVariables: true))); using var md2 = diff2.GetMetadata(); var reader2 = md2.Reader; readers = new[] { reader0, reader1, reader2 }; CheckNames(readers, diff2.EmitResult.ChangedTypes, "C", "<>c__DisplayClass0_0"); diff2.VerifySynthesizedMembers( "C: {<>c__DisplayClass0_0}", "C.<>c__DisplayClass0_0: {x, <.ctor>b__0}"); diff2.VerifyIL("C..ctor", @" { // Code size 44 (0x2c) .maxstack 4 .locals init (C.<>c__DisplayClass0_0 V_0) //CS$<>8__locals0 IL_0000: newobj ""C.<>c__DisplayClass0_0..ctor()"" IL_0005: stloc.0 IL_0006: ldarg.0 IL_0007: ldloc.0 IL_0008: ldflda ""int C.<>c__DisplayClass0_0.x"" IL_000d: call ""int C.M(out int)"" IL_0012: ldloc.0 IL_0013: ldftn ""int C.<>c__DisplayClass0_0.<.ctor>b__0()"" IL_0019: newobj ""System.Func<int>..ctor(object, System.IntPtr)"" IL_001e: call ""int C.M2(System.Func<int>)"" IL_0023: add IL_0024: call ""Base..ctor(int)"" IL_0029: nop IL_002a: nop IL_002b: ret } "); diff2.VerifyIL("C.<>c__DisplayClass0_0.<.ctor>b__0()", @" { // Code size 9 (0x9) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldfld ""int C.<>c__DisplayClass0_0.x"" IL_0006: ldc.i4.1 IL_0007: add IL_0008: ret } "); } [Fact] public void OutVar_InMethodBody_WithLambda() { var source0 = MarkedSource(@" public class C { public void Method() <N:0>{ int _ = M(out int <N:1>x</N:1>) + M2(<N:2>() => x + 1</N:2>); }</N:0> static int M(out int x) => throw null; static int M2(System.Func<int> x) => throw null; }"); var source1 = MarkedSource(@" public class C { public void Method() <N:0>{ int _ = M(out int <N:1>x</N:1>) + M2(<N:2>() => x - 1</N:2>); }</N:0> static int M(out int x) => throw null; static int M2(System.Func<int> x) => throw null; }"); var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll); var compilation1 = compilation0.WithSource(source1.Tree); var compilation2 = compilation1.WithSource(source0.Tree); var ctor0 = compilation0.GetMember<MethodSymbol>("C.Method"); var ctor1 = compilation1.GetMember<MethodSymbol>("C.Method"); var ctor2 = compilation2.GetMember<MethodSymbol>("C.Method"); var v0 = CompileAndVerify(compilation0); v0.VerifyIL("C.Method", @" { // Code size 38 (0x26) .maxstack 3 .locals init (C.<>c__DisplayClass0_0 V_0, //CS$<>8__locals0 int V_1) //_ IL_0000: newobj ""C.<>c__DisplayClass0_0..ctor()"" IL_0005: stloc.0 IL_0006: nop IL_0007: ldloc.0 IL_0008: ldflda ""int C.<>c__DisplayClass0_0.x"" IL_000d: call ""int C.M(out int)"" IL_0012: ldloc.0 IL_0013: ldftn ""int C.<>c__DisplayClass0_0.<Method>b__0()"" IL_0019: newobj ""System.Func<int>..ctor(object, System.IntPtr)"" IL_001e: call ""int C.M2(System.Func<int>)"" IL_0023: add IL_0024: stloc.1 IL_0025: ret } "); v0.VerifyIL("C.<>c__DisplayClass0_0.<Method>b__0()", @" { // Code size 9 (0x9) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldfld ""int C.<>c__DisplayClass0_0.x"" IL_0006: ldc.i4.1 IL_0007: add IL_0008: ret } "); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, ctor0, ctor1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true))); diff1.VerifySynthesizedMembers("C: {<>c__DisplayClass0_0}", "C.<>c__DisplayClass0_0: {x, <Method>b__0}"); diff1.VerifyIL("C.Method", @" { // Code size 38 (0x26) .maxstack 3 .locals init (C.<>c__DisplayClass0_0 V_0, //CS$<>8__locals0 [int] V_1, int V_2) //_ IL_0000: newobj ""C.<>c__DisplayClass0_0..ctor()"" IL_0005: stloc.0 IL_0006: nop IL_0007: ldloc.0 IL_0008: ldflda ""int C.<>c__DisplayClass0_0.x"" IL_000d: call ""int C.M(out int)"" IL_0012: ldloc.0 IL_0013: ldftn ""int C.<>c__DisplayClass0_0.<Method>b__0()"" IL_0019: newobj ""System.Func<int>..ctor(object, System.IntPtr)"" IL_001e: call ""int C.M2(System.Func<int>)"" IL_0023: add IL_0024: stloc.2 IL_0025: ret } "); diff1.VerifyIL("C.<>c__DisplayClass0_0.<Method>b__0()", @" { // Code size 9 (0x9) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldfld ""int C.<>c__DisplayClass0_0.x"" IL_0006: ldc.i4.1 IL_0007: sub IL_0008: ret } "); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, ctor1, ctor2, GetSyntaxMapFromMarkers(source1, source0), preserveLocalVariables: true))); diff2.VerifySynthesizedMembers("C: {<>c__DisplayClass0_0}", "C.<>c__DisplayClass0_0: {x, <Method>b__0}"); diff2.VerifyIL("C.Method", @" { // Code size 38 (0x26) .maxstack 3 .locals init (C.<>c__DisplayClass0_0 V_0, //CS$<>8__locals0 [int] V_1, [int] V_2, int V_3) //_ IL_0000: newobj ""C.<>c__DisplayClass0_0..ctor()"" IL_0005: stloc.0 IL_0006: nop IL_0007: ldloc.0 IL_0008: ldflda ""int C.<>c__DisplayClass0_0.x"" IL_000d: call ""int C.M(out int)"" IL_0012: ldloc.0 IL_0013: ldftn ""int C.<>c__DisplayClass0_0.<Method>b__0()"" IL_0019: newobj ""System.Func<int>..ctor(object, System.IntPtr)"" IL_001e: call ""int C.M2(System.Func<int>)"" IL_0023: add IL_0024: stloc.3 IL_0025: ret } "); diff2.VerifyIL("C.<>c__DisplayClass0_0.<Method>b__0()", @" { // Code size 9 (0x9) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldfld ""int C.<>c__DisplayClass0_0.x"" IL_0006: ldc.i4.1 IL_0007: add IL_0008: ret } "); } [Fact] public void OutVar_InFieldInitializer() { var source0 = MarkedSource(@" public class C { public int field = M(out int <N:0>x</N:0>) + x + M(out int <N:1>y</N:1>); static int M(out int x) => throw null; }"); var source1 = MarkedSource(@" public class C { public int field = M(out int <N:0>x</N:0>) + x; static int M(out int x) => throw null; }"); var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll); var compilation1 = compilation0.WithSource(source1.Tree); var compilation2 = compilation1.WithSource(source0.Tree); var ctor0 = compilation0.GetMember<MethodSymbol>("C..ctor"); var ctor1 = compilation1.GetMember<MethodSymbol>("C..ctor"); var ctor2 = compilation2.GetMember<MethodSymbol>("C..ctor"); var v0 = CompileAndVerify(compilation0); v0.VerifyIL("C..ctor", @" { // Code size 31 (0x1f) .maxstack 3 .locals init (int V_0, //x int V_1) //y IL_0000: ldarg.0 IL_0001: ldloca.s V_0 IL_0003: call ""int C.M(out int)"" IL_0008: ldloc.0 IL_0009: add IL_000a: ldloca.s V_1 IL_000c: call ""int C.M(out int)"" IL_0011: add IL_0012: stfld ""int C.field"" IL_0017: ldarg.0 IL_0018: call ""object..ctor()"" IL_001d: nop IL_001e: ret } "); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, ctor0, ctor1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true))); diff1.VerifyIL("C..ctor", @" { // Code size 23 (0x17) .maxstack 3 .locals init (int V_0, //x [int] V_1) IL_0000: ldarg.0 IL_0001: ldloca.s V_0 IL_0003: call ""int C.M(out int)"" IL_0008: ldloc.0 IL_0009: add IL_000a: stfld ""int C.field"" IL_000f: ldarg.0 IL_0010: call ""object..ctor()"" IL_0015: nop IL_0016: ret } "); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, ctor1, ctor2, GetSyntaxMapFromMarkers(source1, source0), preserveLocalVariables: true))); diff2.VerifyIL("C..ctor", @" { // Code size 31 (0x1f) .maxstack 3 .locals init (int V_0, //x [int] V_1, int V_2) //y IL_0000: ldarg.0 IL_0001: ldloca.s V_0 IL_0003: call ""int C.M(out int)"" IL_0008: ldloc.0 IL_0009: add IL_000a: ldloca.s V_2 IL_000c: call ""int C.M(out int)"" IL_0011: add IL_0012: stfld ""int C.field"" IL_0017: ldarg.0 IL_0018: call ""object..ctor()"" IL_001d: nop IL_001e: ret } "); } [Fact] public void OutVar_InFieldInitializer_WithLambda() { var source0 = MarkedSource(@" public class C { int field = <N:0>M(out int <N:1>x</N:1>) + M2(<N:2>() => x + 1</N:2>)</N:0>; static int M(out int x) => throw null; static int M2(System.Func<int> x) => throw null; }"); var source1 = MarkedSource(@" public class C { int field = <N:0>M(out int <N:1>x</N:1>) + M2(<N:2>() => x - 1</N:2>)</N:0>; static int M(out int x) => throw null; static int M2(System.Func<int> x) => throw null; }"); var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll); var compilation1 = compilation0.WithSource(source1.Tree); var compilation2 = compilation1.WithSource(source0.Tree); var ctor0 = compilation0.GetMember<MethodSymbol>("C..ctor"); var ctor1 = compilation1.GetMember<MethodSymbol>("C..ctor"); var ctor2 = compilation2.GetMember<MethodSymbol>("C..ctor"); var v0 = CompileAndVerify(compilation0); v0.VerifyIL("C..ctor", @" { // Code size 49 (0x31) .maxstack 4 .locals init (C.<>c__DisplayClass3_0 V_0) //CS$<>8__locals0 IL_0000: newobj ""C.<>c__DisplayClass3_0..ctor()"" IL_0005: stloc.0 IL_0006: ldarg.0 IL_0007: ldloc.0 IL_0008: ldflda ""int C.<>c__DisplayClass3_0.x"" IL_000d: call ""int C.M(out int)"" IL_0012: ldloc.0 IL_0013: ldftn ""int C.<>c__DisplayClass3_0.<.ctor>b__0()"" IL_0019: newobj ""System.Func<int>..ctor(object, System.IntPtr)"" IL_001e: call ""int C.M2(System.Func<int>)"" IL_0023: add IL_0024: stfld ""int C.field"" IL_0029: ldarg.0 IL_002a: call ""object..ctor()"" IL_002f: nop IL_0030: ret } "); v0.VerifyIL("C.<>c__DisplayClass3_0.<.ctor>b__0()", @" { // Code size 9 (0x9) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldfld ""int C.<>c__DisplayClass3_0.x"" IL_0006: ldc.i4.1 IL_0007: add IL_0008: ret } "); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, ctor0, ctor1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true))); diff1.VerifySynthesizedMembers( "C.<>c__DisplayClass3_0: {x, <.ctor>b__0}", "C: {<>c__DisplayClass3_0}"); diff1.VerifyIL("C..ctor", @" { // Code size 49 (0x31) .maxstack 4 .locals init (C.<>c__DisplayClass3_0 V_0) //CS$<>8__locals0 IL_0000: newobj ""C.<>c__DisplayClass3_0..ctor()"" IL_0005: stloc.0 IL_0006: ldarg.0 IL_0007: ldloc.0 IL_0008: ldflda ""int C.<>c__DisplayClass3_0.x"" IL_000d: call ""int C.M(out int)"" IL_0012: ldloc.0 IL_0013: ldftn ""int C.<>c__DisplayClass3_0.<.ctor>b__0()"" IL_0019: newobj ""System.Func<int>..ctor(object, System.IntPtr)"" IL_001e: call ""int C.M2(System.Func<int>)"" IL_0023: add IL_0024: stfld ""int C.field"" IL_0029: ldarg.0 IL_002a: call ""object..ctor()"" IL_002f: nop IL_0030: ret } "); diff1.VerifyIL("C.<>c__DisplayClass3_0.<.ctor>b__0()", @" { // Code size 9 (0x9) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldfld ""int C.<>c__DisplayClass3_0.x"" IL_0006: ldc.i4.1 IL_0007: sub IL_0008: ret } "); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, ctor1, ctor2, GetSyntaxMapFromMarkers(source1, source0), preserveLocalVariables: true))); diff2.VerifySynthesizedMembers( "C.<>c__DisplayClass3_0: {x, <.ctor>b__0}", "C: {<>c__DisplayClass3_0}"); diff2.VerifyIL("C..ctor", @" { // Code size 49 (0x31) .maxstack 4 .locals init (C.<>c__DisplayClass3_0 V_0) //CS$<>8__locals0 IL_0000: newobj ""C.<>c__DisplayClass3_0..ctor()"" IL_0005: stloc.0 IL_0006: ldarg.0 IL_0007: ldloc.0 IL_0008: ldflda ""int C.<>c__DisplayClass3_0.x"" IL_000d: call ""int C.M(out int)"" IL_0012: ldloc.0 IL_0013: ldftn ""int C.<>c__DisplayClass3_0.<.ctor>b__0()"" IL_0019: newobj ""System.Func<int>..ctor(object, System.IntPtr)"" IL_001e: call ""int C.M2(System.Func<int>)"" IL_0023: add IL_0024: stfld ""int C.field"" IL_0029: ldarg.0 IL_002a: call ""object..ctor()"" IL_002f: nop IL_0030: ret } "); diff2.VerifyIL("C.<>c__DisplayClass3_0.<.ctor>b__0()", @" { // Code size 9 (0x9) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldfld ""int C.<>c__DisplayClass3_0.x"" IL_0006: ldc.i4.1 IL_0007: add IL_0008: ret } "); } [Fact] public void OutVar_InQuery() { var source0 = MarkedSource(@" using System.Linq; public class Program { static int M(int x, out int y) { y = 42; return 43; } static void N() { var <N:0>query = from a in new int[] { 1, 2 } <N:1>select M(a, out int <N:2>x</N:2>) + x + M(a, out int <N:3>y</N:3></N:1>)</N:0>; } }"); var source1 = MarkedSource(@" using System.Linq; public class Program { static int M(int x, out int y) { y = 42; return 43; } static void N() { var <N:0>query = from a in new int[] { 1, 2 } <N:1>select M(a, out int <N:2>x</N:2>) + x</N:1></N:0>; } }"); var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll); var compilation1 = compilation0.WithSource(source1.Tree); var compilation2 = compilation1.WithSource(source0.Tree); var n0 = compilation0.GetMember<MethodSymbol>("Program.N"); var n1 = compilation1.GetMember<MethodSymbol>("Program.N"); var n2 = compilation2.GetMember<MethodSymbol>("Program.N"); var v0 = CompileAndVerify(compilation0); v0.VerifyIL("Program.N()", @" { // Code size 53 (0x35) .maxstack 4 .locals init (System.Collections.Generic.IEnumerable<int> V_0) //query IL_0000: nop IL_0001: ldc.i4.2 IL_0002: newarr ""int"" IL_0007: dup IL_0008: ldc.i4.0 IL_0009: ldc.i4.1 IL_000a: stelem.i4 IL_000b: dup IL_000c: ldc.i4.1 IL_000d: ldc.i4.2 IL_000e: stelem.i4 IL_000f: ldsfld ""System.Func<int, int> Program.<>c.<>9__1_0"" IL_0014: dup IL_0015: brtrue.s IL_002e IL_0017: pop IL_0018: ldsfld ""Program.<>c Program.<>c.<>9"" IL_001d: ldftn ""int Program.<>c.<N>b__1_0(int)"" IL_0023: newobj ""System.Func<int, int>..ctor(object, System.IntPtr)"" IL_0028: dup IL_0029: stsfld ""System.Func<int, int> Program.<>c.<>9__1_0"" IL_002e: call ""System.Collections.Generic.IEnumerable<int> System.Linq.Enumerable.Select<int, int>(System.Collections.Generic.IEnumerable<int>, System.Func<int, int>)"" IL_0033: stloc.0 IL_0034: ret } "); v0.VerifyIL("Program.<>c.<N>b__1_0(int)", @" { // Code size 20 (0x14) .maxstack 3 .locals init (int V_0, //x int V_1) //y IL_0000: ldarg.1 IL_0001: ldloca.s V_0 IL_0003: call ""int Program.M(int, out int)"" IL_0008: ldloc.0 IL_0009: add IL_000a: ldarg.1 IL_000b: ldloca.s V_1 IL_000d: call ""int Program.M(int, out int)"" IL_0012: add IL_0013: ret } "); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, n0, n1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true))); diff1.VerifySynthesizedMembers( "Program: {<>c}", "Program.<>c: {<>9__1_0, <N>b__1_0}"); diff1.VerifyIL("Program.N()", @" { // Code size 53 (0x35) .maxstack 4 .locals init (System.Collections.Generic.IEnumerable<int> V_0) //query IL_0000: nop IL_0001: ldc.i4.2 IL_0002: newarr ""int"" IL_0007: dup IL_0008: ldc.i4.0 IL_0009: ldc.i4.1 IL_000a: stelem.i4 IL_000b: dup IL_000c: ldc.i4.1 IL_000d: ldc.i4.2 IL_000e: stelem.i4 IL_000f: ldsfld ""System.Func<int, int> Program.<>c.<>9__1_0"" IL_0014: dup IL_0015: brtrue.s IL_002e IL_0017: pop IL_0018: ldsfld ""Program.<>c Program.<>c.<>9"" IL_001d: ldftn ""int Program.<>c.<N>b__1_0(int)"" IL_0023: newobj ""System.Func<int, int>..ctor(object, System.IntPtr)"" IL_0028: dup IL_0029: stsfld ""System.Func<int, int> Program.<>c.<>9__1_0"" IL_002e: call ""System.Collections.Generic.IEnumerable<int> System.Linq.Enumerable.Select<int, int>(System.Collections.Generic.IEnumerable<int>, System.Func<int, int>)"" IL_0033: stloc.0 IL_0034: ret } "); diff1.VerifyIL("Program.<>c.<N>b__1_0(int)", @" { // Code size 11 (0xb) .maxstack 2 .locals init (int V_0, //x [int] V_1) IL_0000: ldarg.1 IL_0001: ldloca.s V_0 IL_0003: call ""int Program.M(int, out int)"" IL_0008: ldloc.0 IL_0009: add IL_000a: ret } "); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, n1, n2, GetSyntaxMapFromMarkers(source1, source0), preserveLocalVariables: true))); diff2.VerifySynthesizedMembers( "Program: {<>c}", "Program.<>c: {<>9__1_0, <N>b__1_0}"); diff2.VerifyIL("Program.N()", @" { // Code size 53 (0x35) .maxstack 4 .locals init (System.Collections.Generic.IEnumerable<int> V_0) //query IL_0000: nop IL_0001: ldc.i4.2 IL_0002: newarr ""int"" IL_0007: dup IL_0008: ldc.i4.0 IL_0009: ldc.i4.1 IL_000a: stelem.i4 IL_000b: dup IL_000c: ldc.i4.1 IL_000d: ldc.i4.2 IL_000e: stelem.i4 IL_000f: ldsfld ""System.Func<int, int> Program.<>c.<>9__1_0"" IL_0014: dup IL_0015: brtrue.s IL_002e IL_0017: pop IL_0018: ldsfld ""Program.<>c Program.<>c.<>9"" IL_001d: ldftn ""int Program.<>c.<N>b__1_0(int)"" IL_0023: newobj ""System.Func<int, int>..ctor(object, System.IntPtr)"" IL_0028: dup IL_0029: stsfld ""System.Func<int, int> Program.<>c.<>9__1_0"" IL_002e: call ""System.Collections.Generic.IEnumerable<int> System.Linq.Enumerable.Select<int, int>(System.Collections.Generic.IEnumerable<int>, System.Func<int, int>)"" IL_0033: stloc.0 IL_0034: ret } "); diff2.VerifyIL("Program.<>c.<N>b__1_0(int)", @" { // Code size 20 (0x14) .maxstack 3 .locals init (int V_0, //x [int] V_1, int V_2) //y IL_0000: ldarg.1 IL_0001: ldloca.s V_0 IL_0003: call ""int Program.M(int, out int)"" IL_0008: ldloc.0 IL_0009: add IL_000a: ldarg.1 IL_000b: ldloca.s V_2 IL_000d: call ""int Program.M(int, out int)"" IL_0012: add IL_0013: ret } "); } [Fact] public void OutVar_InQuery_WithLambda() { var source0 = MarkedSource(@" using System.Linq; public class Program { static int M(int x, out int y) { y = 42; return 43; } static int M2(System.Func<int> x) => throw null; static void N() { var <N:0>query = from a in new int[] { 1, 2 } <N:1>select <N:2>M(a, out int <N:3>x</N:3>) + M2(<N:4>() => x + 1</N:4>)</N:2></N:1></N:0>; } }"); var source1 = MarkedSource(@" using System.Linq; public class Program { static int M(int x, out int y) { y = 42; return 43; } static int M2(System.Func<int> x) => throw null; static void N() { var <N:0>query = from a in new int[] { 1, 2 } <N:1>select <N:2>M(a, out int <N:3>x</N:3>) + M2(<N:4>() => x - 1</N:4>)</N:2></N:1></N:0>; } }"); var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll); var compilation1 = compilation0.WithSource(source1.Tree); var compilation2 = compilation1.WithSource(source0.Tree); var n0 = compilation0.GetMember<MethodSymbol>("Program.N"); var n1 = compilation1.GetMember<MethodSymbol>("Program.N"); var n2 = compilation2.GetMember<MethodSymbol>("Program.N"); var v0 = CompileAndVerify(compilation0); v0.VerifyIL("Program.N()", @" { // Code size 53 (0x35) .maxstack 4 .locals init (System.Collections.Generic.IEnumerable<int> V_0) //query IL_0000: nop IL_0001: ldc.i4.2 IL_0002: newarr ""int"" IL_0007: dup IL_0008: ldc.i4.0 IL_0009: ldc.i4.1 IL_000a: stelem.i4 IL_000b: dup IL_000c: ldc.i4.1 IL_000d: ldc.i4.2 IL_000e: stelem.i4 IL_000f: ldsfld ""System.Func<int, int> Program.<>c.<>9__2_0"" IL_0014: dup IL_0015: brtrue.s IL_002e IL_0017: pop IL_0018: ldsfld ""Program.<>c Program.<>c.<>9"" IL_001d: ldftn ""int Program.<>c.<N>b__2_0(int)"" IL_0023: newobj ""System.Func<int, int>..ctor(object, System.IntPtr)"" IL_0028: dup IL_0029: stsfld ""System.Func<int, int> Program.<>c.<>9__2_0"" IL_002e: call ""System.Collections.Generic.IEnumerable<int> System.Linq.Enumerable.Select<int, int>(System.Collections.Generic.IEnumerable<int>, System.Func<int, int>)"" IL_0033: stloc.0 IL_0034: ret } "); v0.VerifyIL("Program.<>c.<N>b__2_0(int)", @" { // Code size 37 (0x25) .maxstack 3 .locals init (Program.<>c__DisplayClass2_0 V_0) //CS$<>8__locals0 IL_0000: newobj ""Program.<>c__DisplayClass2_0..ctor()"" IL_0005: stloc.0 IL_0006: ldarg.1 IL_0007: ldloc.0 IL_0008: ldflda ""int Program.<>c__DisplayClass2_0.x"" IL_000d: call ""int Program.M(int, out int)"" IL_0012: ldloc.0 IL_0013: ldftn ""int Program.<>c__DisplayClass2_0.<N>b__1()"" IL_0019: newobj ""System.Func<int>..ctor(object, System.IntPtr)"" IL_001e: call ""int Program.M2(System.Func<int>)"" IL_0023: add IL_0024: ret } "); v0.VerifyIL("Program.<>c__DisplayClass2_0.<N>b__1()", @" { // Code size 9 (0x9) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldfld ""int Program.<>c__DisplayClass2_0.x"" IL_0006: ldc.i4.1 IL_0007: add IL_0008: ret } "); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, n0, n1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true))); diff1.VerifySynthesizedMembers( "Program: {<>c__DisplayClass2_0, <>c}", "Program.<>c__DisplayClass2_0: {x, <N>b__1}", "Program.<>c: {<>9__2_0, <N>b__2_0}"); diff1.VerifyIL("Program.N()", @" { // Code size 53 (0x35) .maxstack 4 .locals init (System.Collections.Generic.IEnumerable<int> V_0) //query IL_0000: nop IL_0001: ldc.i4.2 IL_0002: newarr ""int"" IL_0007: dup IL_0008: ldc.i4.0 IL_0009: ldc.i4.1 IL_000a: stelem.i4 IL_000b: dup IL_000c: ldc.i4.1 IL_000d: ldc.i4.2 IL_000e: stelem.i4 IL_000f: ldsfld ""System.Func<int, int> Program.<>c.<>9__2_0"" IL_0014: dup IL_0015: brtrue.s IL_002e IL_0017: pop IL_0018: ldsfld ""Program.<>c Program.<>c.<>9"" IL_001d: ldftn ""int Program.<>c.<N>b__2_0(int)"" IL_0023: newobj ""System.Func<int, int>..ctor(object, System.IntPtr)"" IL_0028: dup IL_0029: stsfld ""System.Func<int, int> Program.<>c.<>9__2_0"" IL_002e: call ""System.Collections.Generic.IEnumerable<int> System.Linq.Enumerable.Select<int, int>(System.Collections.Generic.IEnumerable<int>, System.Func<int, int>)"" IL_0033: stloc.0 IL_0034: ret } "); diff1.VerifyIL("Program.<>c.<N>b__2_0(int)", @" { // Code size 37 (0x25) .maxstack 3 .locals init (Program.<>c__DisplayClass2_0 V_0) //CS$<>8__locals0 IL_0000: newobj ""Program.<>c__DisplayClass2_0..ctor()"" IL_0005: stloc.0 IL_0006: ldarg.1 IL_0007: ldloc.0 IL_0008: ldflda ""int Program.<>c__DisplayClass2_0.x"" IL_000d: call ""int Program.M(int, out int)"" IL_0012: ldloc.0 IL_0013: ldftn ""int Program.<>c__DisplayClass2_0.<N>b__1()"" IL_0019: newobj ""System.Func<int>..ctor(object, System.IntPtr)"" IL_001e: call ""int Program.M2(System.Func<int>)"" IL_0023: add IL_0024: ret } "); diff1.VerifyIL("Program.<>c__DisplayClass2_0.<N>b__1()", @" { // Code size 9 (0x9) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldfld ""int Program.<>c__DisplayClass2_0.x"" IL_0006: ldc.i4.1 IL_0007: sub IL_0008: ret } "); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, n1, n2, GetSyntaxMapFromMarkers(source1, source0), preserveLocalVariables: true))); diff2.VerifySynthesizedMembers( "Program.<>c__DisplayClass2_0: {x, <N>b__1}", "Program: {<>c__DisplayClass2_0, <>c}", "Program.<>c: {<>9__2_0, <N>b__2_0}"); diff2.VerifyIL("Program.N()", @" { // Code size 53 (0x35) .maxstack 4 .locals init (System.Collections.Generic.IEnumerable<int> V_0) //query IL_0000: nop IL_0001: ldc.i4.2 IL_0002: newarr ""int"" IL_0007: dup IL_0008: ldc.i4.0 IL_0009: ldc.i4.1 IL_000a: stelem.i4 IL_000b: dup IL_000c: ldc.i4.1 IL_000d: ldc.i4.2 IL_000e: stelem.i4 IL_000f: ldsfld ""System.Func<int, int> Program.<>c.<>9__2_0"" IL_0014: dup IL_0015: brtrue.s IL_002e IL_0017: pop IL_0018: ldsfld ""Program.<>c Program.<>c.<>9"" IL_001d: ldftn ""int Program.<>c.<N>b__2_0(int)"" IL_0023: newobj ""System.Func<int, int>..ctor(object, System.IntPtr)"" IL_0028: dup IL_0029: stsfld ""System.Func<int, int> Program.<>c.<>9__2_0"" IL_002e: call ""System.Collections.Generic.IEnumerable<int> System.Linq.Enumerable.Select<int, int>(System.Collections.Generic.IEnumerable<int>, System.Func<int, int>)"" IL_0033: stloc.0 IL_0034: ret } "); diff2.VerifyIL("Program.<>c.<N>b__2_0(int)", @" { // Code size 37 (0x25) .maxstack 3 .locals init (Program.<>c__DisplayClass2_0 V_0) //CS$<>8__locals0 IL_0000: newobj ""Program.<>c__DisplayClass2_0..ctor()"" IL_0005: stloc.0 IL_0006: ldarg.1 IL_0007: ldloc.0 IL_0008: ldflda ""int Program.<>c__DisplayClass2_0.x"" IL_000d: call ""int Program.M(int, out int)"" IL_0012: ldloc.0 IL_0013: ldftn ""int Program.<>c__DisplayClass2_0.<N>b__1()"" IL_0019: newobj ""System.Func<int>..ctor(object, System.IntPtr)"" IL_001e: call ""int Program.M2(System.Func<int>)"" IL_0023: add IL_0024: ret } "); diff2.VerifyIL("Program.<>c__DisplayClass2_0.<N>b__1()", @" { // Code size 9 (0x9) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldfld ""int Program.<>c__DisplayClass2_0.x"" IL_0006: ldc.i4.1 IL_0007: add IL_0008: ret } "); } [Fact] public void OutVar_InSwitchExpression() { var source0 = MarkedSource(@" public class Program { static object G(int i) { return i switch { 0 => 0, _ => 1 }; } static object N(out int x) { x = 1; return null; } }"); var source1 = MarkedSource(@" public class Program { static object G(int i) { return i + N(out var x) switch { 0 => 0, _ => 1 }; } static int N(out int x) { x = 1; return 0; } }"); var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll); var compilation1 = compilation0.WithSource(source1.Tree); var compilation2 = compilation1.WithSource(source0.Tree); var n0 = compilation0.GetMember<MethodSymbol>("Program.G"); var n1 = compilation1.GetMember<MethodSymbol>("Program.G"); var n2 = compilation2.GetMember<MethodSymbol>("Program.G"); var v0 = CompileAndVerify(compilation0); v0.VerifyIL("Program.G(int)", @" { // Code size 33 (0x21) .maxstack 1 .locals init (int V_0, object V_1) IL_0000: nop IL_0001: ldc.i4.1 IL_0002: brtrue.s IL_0005 IL_0004: nop IL_0005: ldarg.0 IL_0006: brfalse.s IL_000a IL_0008: br.s IL_000e IL_000a: ldc.i4.0 IL_000b: stloc.0 IL_000c: br.s IL_0012 IL_000e: ldc.i4.1 IL_000f: stloc.0 IL_0010: br.s IL_0012 IL_0012: ldc.i4.1 IL_0013: brtrue.s IL_0016 IL_0015: nop IL_0016: ldloc.0 IL_0017: box ""int"" IL_001c: stloc.1 IL_001d: br.s IL_001f IL_001f: ldloc.1 IL_0020: ret } "); v0.VerifyIL("Program.N(out int)", @" { // Code size 10 (0xa) .maxstack 2 .locals init (object V_0) IL_0000: nop IL_0001: ldarg.0 IL_0002: ldc.i4.1 IL_0003: stind.i4 IL_0004: ldnull IL_0005: stloc.0 IL_0006: br.s IL_0008 IL_0008: ldloc.0 IL_0009: ret } "); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, n0, n1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true))); diff1.VerifySynthesizedMembers(); diff1.VerifyIL("Program.G(int)", @" { // Code size 52 (0x34) .maxstack 2 .locals init ([int] V_0, [object] V_1, int V_2, //x int V_3, int V_4, int V_5, object V_6) IL_0000: nop IL_0001: ldarg.0 IL_0002: stloc.3 IL_0003: ldloca.s V_2 IL_0005: call ""int Program.N(out int)"" IL_000a: stloc.s V_5 IL_000c: ldc.i4.1 IL_000d: brtrue.s IL_0010 IL_000f: nop IL_0010: ldloc.s V_5 IL_0012: brfalse.s IL_0016 IL_0014: br.s IL_001b IL_0016: ldc.i4.0 IL_0017: stloc.s V_4 IL_0019: br.s IL_0020 IL_001b: ldc.i4.1 IL_001c: stloc.s V_4 IL_001e: br.s IL_0020 IL_0020: ldc.i4.1 IL_0021: brtrue.s IL_0024 IL_0023: nop IL_0024: ldloc.3 IL_0025: ldloc.s V_4 IL_0027: add IL_0028: box ""int"" IL_002d: stloc.s V_6 IL_002f: br.s IL_0031 IL_0031: ldloc.s V_6 IL_0033: ret } "); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, n1, n2, GetSyntaxMapFromMarkers(source1, source0), preserveLocalVariables: true))); diff2.VerifySynthesizedMembers(); diff2.VerifyIL("Program.G(int)", @" { // Code size 38 (0x26) .maxstack 1 .locals init ([int] V_0, [object] V_1, [int] V_2, [int] V_3, [int] V_4, [int] V_5, [object] V_6, int V_7, object V_8) IL_0000: nop IL_0001: ldc.i4.1 IL_0002: brtrue.s IL_0005 IL_0004: nop IL_0005: ldarg.0 IL_0006: brfalse.s IL_000a IL_0008: br.s IL_000f IL_000a: ldc.i4.0 IL_000b: stloc.s V_7 IL_000d: br.s IL_0014 IL_000f: ldc.i4.1 IL_0010: stloc.s V_7 IL_0012: br.s IL_0014 IL_0014: ldc.i4.1 IL_0015: brtrue.s IL_0018 IL_0017: nop IL_0018: ldloc.s V_7 IL_001a: box ""int"" IL_001f: stloc.s V_8 IL_0021: br.s IL_0023 IL_0023: ldloc.s V_8 IL_0025: ret } "); } [Fact] public void AddUsing_AmbiguousCode() { var source0 = MarkedSource(@" using System.Threading; class C { static void E() { var t = new Timer(s => System.Console.WriteLine(s)); } }"); var source1 = MarkedSource(@" using System.Threading; using System.Timers; class C { static void E() { var t = new Timer(s => System.Console.WriteLine(s)); } static void G() { System.Console.WriteLine(new TimersDescriptionAttribute("""")); } }"); var compilation0 = CreateCompilation(source0.Tree, targetFramework: TargetFramework.NetStandard20, options: ComSafeDebugDll); var compilation1 = compilation0.WithSource(source1.Tree); var e0 = compilation0.GetMember<MethodSymbol>("C.E"); var e1 = compilation1.GetMember<MethodSymbol>("C.E"); var g1 = compilation1.GetMember<MethodSymbol>("C.G"); var v0 = CompileAndVerify(compilation0); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); // Pretend there was an update to C.E to ensure we haven't invalidated the test var diffError = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, e0, e1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true))); diffError.EmitResult.Diagnostics.Verify( // (9,21): error CS0104: 'Timer' is an ambiguous reference between 'System.Threading.Timer' and 'System.Timers.Timer' // var t = new Timer(s => System.Console.WriteLine(s)); Diagnostic(ErrorCode.ERR_AmbigContext, "Timer").WithArguments("Timer", "System.Threading.Timer", "System.Timers.Timer").WithLocation(9, 21)); // Semantic errors are reported only for the bodies of members being emitted so we shouldn't see any var diff = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Insert, null, g1))); diff.EmitResult.Diagnostics.Verify(); diff.VerifyIL(@"C.G", @" { // Code size 18 (0x12) .maxstack 1 IL_0000: nop IL_0001: ldstr """" IL_0006: newobj ""System.Timers.TimersDescriptionAttribute..ctor(string)"" IL_000b: call ""void System.Console.WriteLine(object)"" IL_0010: nop IL_0011: ret } "); } [Fact] public void Records_AddWellKnownMember() { var source0 = @" #nullable enable namespace N { record R(int X) { } } "; var source1 = @" #nullable enable namespace N { record R(int X) { protected virtual bool PrintMembers(System.Text.StringBuilder builder) { return true; } } } "; var compilation0 = CreateCompilation(new[] { source0, IsExternalInitTypeDefinition }, options: ComSafeDebugDll); var compilation1 = compilation0.WithSource(new[] { source1, IsExternalInitTypeDefinition }); var printMembers0 = compilation0.GetMember<MethodSymbol>("N.R.PrintMembers"); var printMembers1 = compilation1.GetMember<MethodSymbol>("N.R.PrintMembers"); var v0 = CompileAndVerify(compilation0, verify: Verification.Skipped); using var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); // Verify full metadata contains expected rows. var reader0 = md0.MetadataReader; CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "EmbeddedAttribute", "NullableAttribute", "NullableContextAttribute", "IsExternalInit", "R"); CheckNames(reader0, reader0.GetMethodDefNames(), /* EmbeddedAttribute */".ctor", /* NullableAttribute */ ".ctor", /* NullableContextAttribute */".ctor", /* IsExternalInit */".ctor", /* R: */ ".ctor", "get_EqualityContract", "get_X", "set_X", "ToString", "PrintMembers", "op_Inequality", "op_Equality", "GetHashCode", "Equals", "Equals", "<Clone>$", ".ctor", "Deconstruct"); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, printMembers0, printMembers1))); diff1.VerifySynthesizedMembers( "<global namespace>: {Microsoft}", "Microsoft: {CodeAnalysis}", "Microsoft.CodeAnalysis: {EmbeddedAttribute}", "System.Runtime.CompilerServices: {NullableAttribute, NullableContextAttribute}"); // Verify delta metadata contains expected rows. using var md1 = diff1.GetMetadata(); var reader1 = md1.Reader; var readers = new[] { reader0, reader1 }; EncValidation.VerifyModuleMvid(1, reader0, reader1); CheckNames(readers, reader1.GetTypeDefNames()); CheckNames(readers, reader1.GetMethodDefNames(), "PrintMembers"); CheckEncLog(reader1, Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default), Row(20, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(21, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(22, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(4, TableIndex.TypeSpec, EditAndContinueOperation.Default), Row(3, TableIndex.StandAloneSig, EditAndContinueOperation.Default), Row(10, TableIndex.MethodDef, EditAndContinueOperation.Default), // R.PrintMembers Row(3, TableIndex.Param, EditAndContinueOperation.Default)); CheckEncMap(reader1, Handle(20, TableIndex.TypeRef), Handle(21, TableIndex.TypeRef), Handle(22, TableIndex.TypeRef), Handle(10, TableIndex.MethodDef), Handle(3, TableIndex.Param), Handle(3, TableIndex.StandAloneSig), Handle(4, TableIndex.TypeSpec), Handle(2, TableIndex.AssemblyRef)); } [Fact] public void Records_RemoveWellKnownMember() { var source0 = @" namespace N { record R(int X) { protected virtual bool PrintMembers(System.Text.StringBuilder builder) { return true; } } } "; var source1 = @" namespace N { record R(int X) { } } "; var compilation0 = CreateCompilation(new[] { source0, IsExternalInitTypeDefinition }, options: ComSafeDebugDll); var compilation1 = compilation0.WithSource(new[] { source1, IsExternalInitTypeDefinition }); var method0 = compilation0.GetMember<MethodSymbol>("N.R.PrintMembers"); var method1 = compilation1.GetMember<MethodSymbol>("N.R.PrintMembers"); var v0 = CompileAndVerify(compilation0, verify: Verification.Skipped); using var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, method0, method1))); diff1.VerifySynthesizedMembers( "<global namespace>: {Microsoft}", "Microsoft: {CodeAnalysis}", "Microsoft.CodeAnalysis: {EmbeddedAttribute}", "System.Runtime.CompilerServices: {NullableAttribute, NullableContextAttribute}"); } [Fact] public void TopLevelStatement_Update() { var source0 = @" using System; Console.WriteLine(""Hello""); "; var source1 = @" using System; Console.WriteLine(""Hello World""); "; var compilation0 = CreateCompilation(source0, options: TestOptions.DebugExe); var compilation1 = compilation0.WithSource(source1); var method0 = compilation0.GetMember<MethodSymbol>("Program.<Main>$"); var method1 = compilation1.GetMember<MethodSymbol>("Program.<Main>$"); // Verify full metadata contains expected rows. var bytes0 = compilation0.EmitToArray(); using var md0 = ModuleMetadata.CreateFromImage(bytes0); var reader0 = md0.MetadataReader; CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "Program"); CheckNames(reader0, reader0.GetMethodDefNames(), "<Main>$", ".ctor"); CheckNames(reader0, reader0.GetMemberRefNames(), /*CompilationRelaxationsAttribute.*/".ctor", /*RuntimeCompatibilityAttribute.*/".ctor", /*Object.*/".ctor", /*DebuggableAttribute*/".ctor", /*Console.*/"WriteLine", /*Program.*/".ctor"); var generation0 = EmitBaseline.CreateInitialBaseline( md0, EmptyLocalsProvider); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(SemanticEdit.Create(SemanticEditKind.Update, method0, method1))); // Verify delta metadata contains expected rows. using var md1 = diff1.GetMetadata(); var reader1 = md1.Reader; var readers = new[] { reader0, reader1 }; EncValidation.VerifyModuleMvid(1, reader0, reader1); CheckNames(readers, reader1.GetTypeDefNames()); CheckNames(readers, reader1.GetMethodDefNames(), "<Main>$"); CheckNames(readers, reader1.GetMemberRefNames(), /*CompilerGenerated*/".ctor", /*Console.*/"WriteLine"); CheckEncLog(reader1, Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default), Row(7, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(8, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(8, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(9, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(10, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(1, TableIndex.MethodDef, EditAndContinueOperation.Default), // Synthesized Main method Row(1, TableIndex.Param, EditAndContinueOperation.Default)); CheckEncMap(reader1, Handle(8, TableIndex.TypeRef), Handle(9, TableIndex.TypeRef), Handle(10, TableIndex.TypeRef), Handle(1, TableIndex.MethodDef), Handle(1, TableIndex.Param), Handle(7, TableIndex.MemberRef), Handle(8, TableIndex.MemberRef), Handle(2, TableIndex.AssemblyRef)); } [Fact] public void LambdaParameterToDiscard() { var source0 = MarkedSource(@" using System; class C { void M() { var x = new Func<int, int, int>(<N:0>(a, b) => a + b + 1</N:0>); Console.WriteLine(x(1, 2)); } }"); var source1 = MarkedSource(@" using System; class C { void M() { var x = new Func<int, int, int>(<N:0>(_, _) => 10</N:0>); Console.WriteLine(x(1, 2)); } }"); var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll); var compilation1 = compilation0.WithSource(source1.Tree); var method0 = compilation0.GetMember<MethodSymbol>("C.M"); var method1 = compilation1.GetMember<MethodSymbol>("C.M"); var v0 = CompileAndVerify(compilation0, verify: Verification.Skipped); using var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); var diff = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, method0, method1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables: true))); // There should be no diagnostics from rude edits diff.EmitResult.Diagnostics.Verify(); diff.VerifySynthesizedMembers( "C: {<>c}", "C.<>c: {<>9__0_0, <M>b__0_0}"); diff.VerifyIL("C.M", @" { // Code size 48 (0x30) .maxstack 3 .locals init ([unchanged] V_0, System.Func<int, int, int> V_1) //x IL_0000: nop IL_0001: ldsfld ""System.Func<int, int, int> C.<>c.<>9__0_0"" IL_0006: dup IL_0007: brtrue.s IL_0020 IL_0009: pop IL_000a: ldsfld ""C.<>c C.<>c.<>9"" IL_000f: ldftn ""int C.<>c.<M>b__0_0(int, int)"" IL_0015: newobj ""System.Func<int, int, int>..ctor(object, System.IntPtr)"" IL_001a: dup IL_001b: stsfld ""System.Func<int, int, int> C.<>c.<>9__0_0"" IL_0020: stloc.1 IL_0021: ldloc.1 IL_0022: ldc.i4.1 IL_0023: ldc.i4.2 IL_0024: callvirt ""int System.Func<int, int, int>.Invoke(int, int)"" IL_0029: call ""void System.Console.WriteLine(int)"" IL_002e: nop IL_002f: ret }"); diff.VerifyIL("C.<>c.<M>b__0_0(int, int)", @" { // Code size 3 (0x3) .maxstack 1 IL_0000: ldc.i4.s 10 IL_0002: ret }"); } } }
1
dotnet/roslyn
55,428
Test adding nested namespaces
Fixes https://github.com/dotnet/roslyn/issues/54939 The "workaround" that's already implemented is actually the correct behavior.
tmat
2021-08-05T01:19:03Z
2021-08-11T18:38:54Z
bc874ebc5111a2a33221409f895953b1536f6612
1cbbd423e17b186a8f1de89febb4db9a386d180d
Test adding nested namespaces. Fixes https://github.com/dotnet/roslyn/issues/54939 The "workaround" that's already implemented is actually the correct behavior.
./src/Compilers/VisualBasic/Portable/Emit/EditAndContinue/VisualBasicSymbolMatcher.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Concurrent Imports System.Collections.Immutable Imports System.Runtime.InteropServices Imports System.Threading Imports Microsoft.CodeAnalysis.Emit Imports Microsoft.CodeAnalysis.PooledObjects Imports Microsoft.CodeAnalysis.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Symbols.Metadata.PE Namespace Microsoft.CodeAnalysis.VisualBasic.Emit Friend NotInheritable Class VisualBasicSymbolMatcher Inherits SymbolMatcher Private Shared ReadOnly s_nameComparer As StringComparer = IdentifierComparison.Comparer Private ReadOnly _defs As MatchDefs Private ReadOnly _symbols As MatchSymbols Public Sub New(anonymousTypeMap As IReadOnlyDictionary(Of AnonymousTypeKey, AnonymousTypeValue), sourceAssembly As SourceAssemblySymbol, sourceContext As EmitContext, otherAssembly As SourceAssemblySymbol, otherContext As EmitContext, otherSynthesizedMembersOpt As ImmutableDictionary(Of ISymbolInternal, ImmutableArray(Of ISymbolInternal))) _defs = New MatchDefsToSource(sourceContext, otherContext) _symbols = New MatchSymbols(anonymousTypeMap, sourceAssembly, otherAssembly, otherSynthesizedMembersOpt, New DeepTranslator(otherAssembly.GetSpecialType(SpecialType.System_Object))) End Sub Public Sub New(anonymousTypeMap As IReadOnlyDictionary(Of AnonymousTypeKey, AnonymousTypeValue), sourceAssembly As SourceAssemblySymbol, sourceContext As EmitContext, otherAssembly As PEAssemblySymbol) _defs = New MatchDefsToMetadata(sourceContext, otherAssembly) _symbols = New MatchSymbols(anonymousTypeMap, sourceAssembly, otherAssembly, otherSynthesizedMembersOpt:=Nothing, deepTranslatorOpt:=Nothing) End Sub Public Overrides Function MapDefinition(definition As Cci.IDefinition) As Cci.IDefinition Dim symbol As Symbol = TryCast(definition.GetInternalSymbol(), Symbol) If symbol IsNot Nothing Then Return DirectCast(_symbols.Visit(symbol)?.GetCciAdapter(), Cci.IDefinition) End If ' TODO: this appears to be dead code, remove (https://github.com/dotnet/roslyn/issues/51595) Return _defs.VisitDef(definition) End Function Public Overrides Function MapNamespace([namespace] As Cci.INamespace) As Cci.INamespace Debug.Assert(TypeOf [namespace].GetInternalSymbol() Is NamespaceSymbol) Return DirectCast(_symbols.Visit(DirectCast([namespace]?.GetInternalSymbol(), NamespaceSymbol))?.GetCciAdapter(), Cci.INamespace) End Function Public Overrides Function MapReference(reference As Cci.ITypeReference) As Cci.ITypeReference Dim symbol As Symbol = TryCast(reference.GetInternalSymbol(), Symbol) If symbol IsNot Nothing Then Return DirectCast(_symbols.Visit(symbol)?.GetCciAdapter(), Cci.ITypeReference) End If Return Nothing End Function Friend Function TryGetAnonymousTypeName(template As AnonymousTypeManager.AnonymousTypeOrDelegateTemplateSymbol, <Out> ByRef name As String, <Out> ByRef index As Integer) As Boolean Return _symbols.TryGetAnonymousTypeName(template, name, index) End Function Private MustInherit Class MatchDefs Private ReadOnly _sourceContext As EmitContext Private ReadOnly _matches As ConcurrentDictionary(Of Cci.IDefinition, Cci.IDefinition) Private _lazyTopLevelTypes As IReadOnlyDictionary(Of String, Cci.INamespaceTypeDefinition) Public Sub New(sourceContext As EmitContext) Me._sourceContext = sourceContext Me._matches = New ConcurrentDictionary(Of Cci.IDefinition, Cci.IDefinition)(ReferenceEqualityComparer.Instance) End Sub Public Function VisitDef(def As Cci.IDefinition) As Cci.IDefinition Return Me._matches.GetOrAdd(def, AddressOf Me.VisitDefInternal) End Function Private Function VisitDefInternal(def As Cci.IDefinition) As Cci.IDefinition Dim type = TryCast(def, Cci.ITypeDefinition) If type IsNot Nothing Then Dim namespaceType As Cci.INamespaceTypeDefinition = type.AsNamespaceTypeDefinition(Me._sourceContext) If namespaceType IsNot Nothing Then Return Me.VisitNamespaceType(namespaceType) End If Dim nestedType As Cci.INestedTypeDefinition = type.AsNestedTypeDefinition(Me._sourceContext) Debug.Assert(nestedType IsNot Nothing) Dim otherContainer = DirectCast(Me.VisitDef(nestedType.ContainingTypeDefinition), Cci.ITypeDefinition) If otherContainer Is Nothing Then Return Nothing End If Return VisitTypeMembers(otherContainer, nestedType, AddressOf GetNestedTypes, Function(a, b) s_nameComparer.Equals(a.Name, b.Name)) End If Dim member = TryCast(def, Cci.ITypeDefinitionMember) If member IsNot Nothing Then Dim otherContainer = DirectCast(Me.VisitDef(member.ContainingTypeDefinition), Cci.ITypeDefinition) If otherContainer Is Nothing Then Return Nothing End If Dim field = TryCast(def, Cci.IFieldDefinition) If field IsNot Nothing Then Return VisitTypeMembers(otherContainer, field, AddressOf GetFields, Function(a, b) s_nameComparer.Equals(a.Name, b.Name)) End If End If ' We are only expecting types and fields currently. Throw ExceptionUtilities.UnexpectedValue(def) End Function Protected MustOverride Function GetTopLevelTypes() As IEnumerable(Of Cci.INamespaceTypeDefinition) Protected MustOverride Function GetNestedTypes(def As Cci.ITypeDefinition) As IEnumerable(Of Cci.INestedTypeDefinition) Protected MustOverride Function GetFields(def As Cci.ITypeDefinition) As IEnumerable(Of Cci.IFieldDefinition) Private Function VisitNamespaceType(def As Cci.INamespaceTypeDefinition) As Cci.INamespaceTypeDefinition ' All generated top-level types are assumed to be in the global namespace. ' However, this may be an embedded NoPIA type within a namespace. ' Since we do not support edits that include references to NoPIA types ' (see #855640), it's reasonable to simply drop such cases. If Not String.IsNullOrEmpty(def.NamespaceName) Then Return Nothing End If Dim otherDef As Cci.INamespaceTypeDefinition = Nothing Me.GetTopLevelTypesByName().TryGetValue(def.Name, otherDef) Return otherDef End Function Private Function GetTopLevelTypesByName() As IReadOnlyDictionary(Of String, Cci.INamespaceTypeDefinition) If Me._lazyTopLevelTypes Is Nothing Then Dim typesByName As Dictionary(Of String, Cci.INamespaceTypeDefinition) = New Dictionary(Of String, Cci.INamespaceTypeDefinition)(s_nameComparer) For Each type As Cci.INamespaceTypeDefinition In Me.GetTopLevelTypes() ' All generated top-level types are assumed to be in the global namespace. If String.IsNullOrEmpty(type.NamespaceName) Then typesByName.Add(type.Name, type) End If Next Interlocked.CompareExchange(Me._lazyTopLevelTypes, typesByName, Nothing) End If Return Me._lazyTopLevelTypes End Function Private Shared Function VisitTypeMembers(Of T As {Class, Cci.ITypeDefinitionMember})( otherContainer As Cci.ITypeDefinition, member As T, getMembers As Func(Of Cci.ITypeDefinition, IEnumerable(Of T)), predicate As Func(Of T, T, Boolean)) As T ' We could cache the members by name (see Matcher.VisitNamedTypeMembers) ' but the assumption is this class is only used for types with few members ' so caching is not necessary and linear search is acceptable. Return getMembers(otherContainer).FirstOrDefault(Function(otherMember As T) predicate(member, otherMember)) End Function End Class Private NotInheritable Class MatchDefsToMetadata Inherits MatchDefs Private ReadOnly _otherAssembly As PEAssemblySymbol Public Sub New(sourceContext As EmitContext, otherAssembly As PEAssemblySymbol) MyBase.New(sourceContext) Me._otherAssembly = otherAssembly End Sub Protected Overrides Function GetTopLevelTypes() As IEnumerable(Of Cci.INamespaceTypeDefinition) Dim builder As ArrayBuilder(Of Cci.INamespaceTypeDefinition) = ArrayBuilder(Of Cci.INamespaceTypeDefinition).GetInstance() GetTopLevelTypes(builder, Me._otherAssembly.GlobalNamespace) Return builder.ToArrayAndFree() End Function Protected Overrides Function GetNestedTypes(def As Cci.ITypeDefinition) As IEnumerable(Of Cci.INestedTypeDefinition) Return (DirectCast(def, PENamedTypeSymbol)).GetTypeMembers().Cast(Of Cci.INestedTypeDefinition)() End Function Protected Overrides Function GetFields(def As Cci.ITypeDefinition) As IEnumerable(Of Cci.IFieldDefinition) Return (DirectCast(def, PENamedTypeSymbol)).GetFieldsToEmit().Cast(Of Cci.IFieldDefinition)() End Function Private Overloads Shared Sub GetTopLevelTypes(builder As ArrayBuilder(Of Cci.INamespaceTypeDefinition), [namespace] As NamespaceSymbol) For Each member In [namespace].GetMembers() If member.Kind = SymbolKind.Namespace Then GetTopLevelTypes(builder, DirectCast(member, NamespaceSymbol)) Else builder.Add(DirectCast(member.GetCciAdapter(), Cci.INamespaceTypeDefinition)) End If Next End Sub End Class Private NotInheritable Class MatchDefsToSource Inherits MatchDefs Private ReadOnly _otherContext As EmitContext Public Sub New(sourceContext As EmitContext, otherContext As EmitContext) MyBase.New(sourceContext) _otherContext = otherContext End Sub Protected Overrides Function GetTopLevelTypes() As IEnumerable(Of Cci.INamespaceTypeDefinition) Return _otherContext.Module.GetTopLevelTypeDefinitions(_otherContext) End Function Protected Overrides Function GetNestedTypes(def As Cci.ITypeDefinition) As IEnumerable(Of Cci.INestedTypeDefinition) Return def.GetNestedTypes(_otherContext) End Function Protected Overrides Function GetFields(def As Cci.ITypeDefinition) As IEnumerable(Of Cci.IFieldDefinition) Return def.GetFields(_otherContext) End Function End Class Private NotInheritable Class MatchSymbols Inherits VisualBasicSymbolVisitor(Of Symbol) Private ReadOnly _anonymousTypeMap As IReadOnlyDictionary(Of AnonymousTypeKey, AnonymousTypeValue) Private ReadOnly _comparer As SymbolComparer Private ReadOnly _matches As ConcurrentDictionary(Of Symbol, Symbol) Private ReadOnly _sourceAssembly As SourceAssemblySymbol Private ReadOnly _otherAssembly As AssemblySymbol Private ReadOnly _otherSynthesizedMembersOpt As ImmutableDictionary(Of ISymbolInternal, ImmutableArray(Of ISymbolInternal)) ' A cache of members per type, populated when the first member for a given ' type Is needed. Within each type, members are indexed by name. The reason ' for caching, And indexing by name, Is to avoid searching sequentially ' through all members of a given kind each time a member Is matched. Private ReadOnly _otherMembers As ConcurrentDictionary(Of ISymbolInternal, IReadOnlyDictionary(Of String, ImmutableArray(Of ISymbolInternal))) Public Sub New(anonymousTypeMap As IReadOnlyDictionary(Of AnonymousTypeKey, AnonymousTypeValue), sourceAssembly As SourceAssemblySymbol, otherAssembly As AssemblySymbol, otherSynthesizedMembersOpt As ImmutableDictionary(Of ISymbolInternal, ImmutableArray(Of ISymbolInternal)), deepTranslatorOpt As DeepTranslator) _anonymousTypeMap = anonymousTypeMap _sourceAssembly = sourceAssembly _otherAssembly = otherAssembly _otherSynthesizedMembersOpt = otherSynthesizedMembersOpt _comparer = New SymbolComparer(Me, deepTranslatorOpt) _matches = New ConcurrentDictionary(Of Symbol, Symbol)(ReferenceEqualityComparer.Instance) _otherMembers = New ConcurrentDictionary(Of ISymbolInternal, IReadOnlyDictionary(Of String, ImmutableArray(Of ISymbolInternal)))(ReferenceEqualityComparer.Instance) End Sub Friend Function TryGetAnonymousTypeName(type As AnonymousTypeManager.AnonymousTypeOrDelegateTemplateSymbol, <Out> ByRef name As String, <Out> ByRef index As Integer) As Boolean Dim otherType As AnonymousTypeValue = Nothing If TryFindAnonymousType(type, otherType) Then name = otherType.Name index = otherType.UniqueIndex Return True End If name = Nothing index = -1 Return False End Function Public Overrides Function DefaultVisit(symbol As Symbol) As Symbol ' Symbol should have been handled elsewhere. Throw ExceptionUtilities.Unreachable End Function Public Overrides Function Visit(symbol As Symbol) As Symbol Debug.Assert(symbol.ContainingAssembly IsNot Me._otherAssembly) ' Add an entry for the match, even if there Is no match, to avoid ' matching the same symbol unsuccessfully multiple times. Return Me._matches.GetOrAdd(symbol, AddressOf MyBase.Visit) End Function Public Overrides Function VisitArrayType(symbol As ArrayTypeSymbol) As Symbol Dim otherElementType As TypeSymbol = DirectCast(Me.Visit(symbol.ElementType), TypeSymbol) If otherElementType Is Nothing Then ' For a newly added type, there is no match in the previous generation, so it could be Nothing. Return Nothing End If Dim otherModifiers = VisitCustomModifiers(symbol.CustomModifiers) If symbol.IsSZArray Then Return ArrayTypeSymbol.CreateSZArray(otherElementType, otherModifiers, Me._otherAssembly) End If Return ArrayTypeSymbol.CreateMDArray(otherElementType, otherModifiers, symbol.Rank, symbol.Sizes, symbol.LowerBounds, Me._otherAssembly) End Function Public Overrides Function VisitEvent(symbol As EventSymbol) As Symbol Return Me.VisitNamedTypeMember(symbol, AddressOf Me.AreEventsEqual) End Function Public Overrides Function VisitField(symbol As FieldSymbol) As Symbol Return Me.VisitNamedTypeMember(symbol, AddressOf Me.AreFieldsEqual) End Function Public Overrides Function VisitMethod(symbol As MethodSymbol) As Symbol ' Not expecting constructed method. Debug.Assert(symbol.IsDefinition) Return Me.VisitNamedTypeMember(symbol, AddressOf Me.AreMethodsEqual) End Function Public Overrides Function VisitModule([module] As ModuleSymbol) As Symbol Dim otherAssembly = DirectCast(Visit([module].ContainingAssembly), AssemblySymbol) If otherAssembly Is Nothing Then Return Nothing End If ' manifest module: If [module].Ordinal = 0 Then Return otherAssembly.Modules(0) End If ' match non-manifest module by name: For i = 1 To otherAssembly.Modules.Length - 1 Dim otherModule = otherAssembly.Modules(i) ' use case sensitive comparison -- modules whose names differ in casing are considered distinct If StringComparer.Ordinal.Equals(otherModule.Name, [module].Name) Then Return otherModule End If Next Return Nothing End Function Public Overrides Function VisitAssembly(assembly As AssemblySymbol) As Symbol If assembly.IsLinked Then Return assembly End If ' When we map synthesized symbols from previous generations to the latest compilation ' we might encounter a symbol that is defined in arbitrary preceding generation, ' not just the immediately preceding generation. If the source assembly uses time-based ' versioning assemblies of preceding generations might differ in their version number. If IdentityEqualIgnoringVersionWildcard(assembly, _sourceAssembly) Then Return _otherAssembly End If ' find a referenced assembly with the exactly same source identity: For Each otherReferencedAssembly In _otherAssembly.Modules(0).ReferencedAssemblySymbols If IdentityEqualIgnoringVersionWildcard(assembly, otherReferencedAssembly) Then Return otherReferencedAssembly End If Next Return Nothing End Function Private Shared Function IdentityEqualIgnoringVersionWildcard(left As AssemblySymbol, right As AssemblySymbol) As Boolean Dim leftIdentity = left.Identity Dim rightIdentity = right.Identity Return AssemblyIdentityComparer.SimpleNameComparer.Equals(leftIdentity.Name, rightIdentity.Name) AndAlso If(left.AssemblyVersionPattern, leftIdentity.Version).Equals(If(right.AssemblyVersionPattern, rightIdentity.Version)) AndAlso AssemblyIdentity.EqualIgnoringNameAndVersion(leftIdentity, rightIdentity) End Function Public Overrides Function VisitNamespace([namespace] As NamespaceSymbol) As Symbol Dim otherContainer As Symbol = Visit([namespace].ContainingSymbol) ' TODO: Workaround for https//github.com/dotnet/roslyn/issues/54939. ' We should fail if the container can't be mapped. ' Currently this only occurs when determining reloadable type name for a type added to a new namespace, ' which is a rude edit. ' Debug.Assert(otherContainer IsNot Nothing) If otherContainer Is Nothing Then Return Nothing End If Select Case otherContainer.Kind Case SymbolKind.NetModule Return DirectCast(otherContainer, ModuleSymbol).GlobalNamespace Case SymbolKind.Namespace Return FindMatchingMember(otherContainer, [namespace], AddressOf AreNamespacesEqual) Case Else Throw ExceptionUtilities.UnexpectedValue(otherContainer.Kind) End Select End Function Public Overrides Function VisitNamedType(type As NamedTypeSymbol) As Symbol Dim originalDef As NamedTypeSymbol = type.OriginalDefinition If originalDef IsNot type Then Dim otherDef As NamedTypeSymbol = DirectCast(Me.Visit(originalDef), NamedTypeSymbol) ' For anonymous delegates the rewriter generates a _ClosureCache$_N field ' of the constructed delegate type. For those cases, the matched result will ' be Nothing if the anonymous delegate is new to this compilation. If otherDef Is Nothing Then Return Nothing End If Dim otherTypeParameters As ImmutableArray(Of TypeParameterSymbol) = otherDef.GetAllTypeParameters() Dim translationFailed As Boolean = False Dim otherTypeArguments = type.GetAllTypeArgumentsWithModifiers().SelectAsArray(Function(t, v) Dim newType = DirectCast(v.Visit(t.Type), TypeSymbol) If newType Is Nothing Then ' For a newly added type, there is no match in the previous generation, so it could be Nothing. translationFailed = True newType = t.Type End If Return New TypeWithModifiers(newType, v.VisitCustomModifiers(t.CustomModifiers)) End Function, Me) If translationFailed Then ' There is no match in the previous generation. Return Nothing End If Dim typeMap = TypeSubstitution.Create(otherDef, otherTypeParameters, otherTypeArguments, False) Return otherDef.Construct(typeMap) ElseIf type.IsTupleType Then Dim otherDef = DirectCast(Me.Visit(type.TupleUnderlyingType), NamedTypeSymbol) If otherDef Is Nothing OrElse Not otherDef.IsTupleOrCompatibleWithTupleOfCardinality(type.TupleElementTypes.Length) Then Return Nothing End If Return otherDef End If Debug.Assert(type.IsDefinition) Dim otherContainer As Symbol = Me.Visit(type.ContainingSymbol) ' Containing type will be missing from other assembly ' if the type was added in the (newer) source assembly. If otherContainer Is Nothing Then Return Nothing End If Select Case otherContainer.Kind Case SymbolKind.Namespace Dim template = TryCast(type, AnonymousTypeManager.AnonymousTypeOrDelegateTemplateSymbol) If template IsNot Nothing Then Debug.Assert(otherContainer Is _otherAssembly.GlobalNamespace) Dim value As AnonymousTypeValue = Nothing TryFindAnonymousType(template, value) Return DirectCast(value.Type?.GetInternalSymbol(), NamedTypeSymbol) End If If type.IsAnonymousType Then Return Visit(AnonymousTypeManager.TranslateAnonymousTypeSymbol(type)) End If Return FindMatchingMember(otherContainer, type, AddressOf AreNamedTypesEqual) Case SymbolKind.NamedType Return FindMatchingMember(otherContainer, type, AddressOf AreNamedTypesEqual) Case Else Throw ExceptionUtilities.UnexpectedValue(otherContainer.Kind) End Select End Function Public Overrides Function VisitParameter(parameter As ParameterSymbol) As Symbol Throw ExceptionUtilities.Unreachable End Function Public Overrides Function VisitProperty(symbol As PropertySymbol) As Symbol Return Me.VisitNamedTypeMember(symbol, AddressOf Me.ArePropertiesEqual) End Function Public Overrides Function VisitTypeParameter(symbol As TypeParameterSymbol) As Symbol Dim indexed = TryCast(symbol, IndexedTypeParameterSymbol) If indexed IsNot Nothing Then Return indexed End If Dim otherContainer As Symbol = Me.Visit(symbol.ContainingSymbol) Debug.Assert(otherContainer IsNot Nothing) Dim otherTypeParameters As ImmutableArray(Of TypeParameterSymbol) Select Case otherContainer.Kind Case SymbolKind.NamedType, SymbolKind.ErrorType otherTypeParameters = DirectCast(otherContainer, NamedTypeSymbol).TypeParameters Case SymbolKind.Method otherTypeParameters = DirectCast(otherContainer, MethodSymbol).TypeParameters Case Else Throw ExceptionUtilities.UnexpectedValue(otherContainer.Kind) End Select Return otherTypeParameters(symbol.Ordinal) End Function Private Function VisitCustomModifiers(modifiers As ImmutableArray(Of CustomModifier)) As ImmutableArray(Of CustomModifier) Return modifiers.SelectAsArray(AddressOf VisitCustomModifier) End Function Private Function VisitCustomModifier(modifier As CustomModifier) As CustomModifier Dim type = DirectCast(Me.Visit(DirectCast(modifier.Modifier, Symbol)), NamedTypeSymbol) Debug.Assert(type IsNot Nothing) Return If(modifier.IsOptional, VisualBasicCustomModifier.CreateOptional(type), VisualBasicCustomModifier.CreateRequired(type)) End Function Friend Function TryFindAnonymousType(type As AnonymousTypeManager.AnonymousTypeOrDelegateTemplateSymbol, <Out> ByRef otherType As AnonymousTypeValue) As Boolean Debug.Assert(type.ContainingSymbol Is _sourceAssembly.GlobalNamespace) Return _anonymousTypeMap.TryGetValue(type.GetAnonymousTypeKey(), otherType) End Function Private Function VisitNamedTypeMember(Of T As Symbol)(member As T, predicate As Func(Of T, T, Boolean)) As Symbol Dim otherType As NamedTypeSymbol = DirectCast(Visit(member.ContainingType), NamedTypeSymbol) If otherType Is Nothing Then Return Nothing End If Return FindMatchingMember(otherType, member, predicate) End Function Private Function FindMatchingMember(Of T As Symbol)(otherTypeOrNamespace As ISymbolInternal, sourceMember As T, predicate As Func(Of T, T, Boolean)) As T Dim otherMembersByName = _otherMembers.GetOrAdd(otherTypeOrNamespace, AddressOf GetAllEmittedMembers) Dim otherMembers As ImmutableArray(Of ISymbolInternal) = Nothing If otherMembersByName.TryGetValue(sourceMember.Name, otherMembers) Then For Each otherMember In otherMembers Dim other = TryCast(otherMember, T) If other IsNot Nothing AndAlso predicate(sourceMember, other) Then Return other End If Next End If Return Nothing End Function Private Function AreArrayTypesEqual(type As ArrayTypeSymbol, other As ArrayTypeSymbol) As Boolean Debug.Assert(type.CustomModifiers.IsEmpty) Debug.Assert(other.CustomModifiers.IsEmpty) Return type.HasSameShapeAs(other) AndAlso Me.AreTypesEqual(type.ElementType, other.ElementType) End Function Private Function AreEventsEqual([event] As EventSymbol, other As EventSymbol) As Boolean Debug.Assert(s_nameComparer.Equals([event].Name, other.Name)) Return Me._comparer.Equals([event].Type, other.Type) End Function Private Function AreFieldsEqual(field As FieldSymbol, other As FieldSymbol) As Boolean Debug.Assert(s_nameComparer.Equals(field.Name, other.Name)) Return Me._comparer.Equals(field.Type, other.Type) End Function Private Function AreMethodsEqual(method As MethodSymbol, other As MethodSymbol) As Boolean Debug.Assert(s_nameComparer.Equals(method.Name, other.Name)) Debug.Assert(method.IsDefinition) Debug.Assert(other.IsDefinition) method = SubstituteTypeParameters(method) other = SubstituteTypeParameters(other) Return Me._comparer.Equals(method.ReturnType, other.ReturnType) AndAlso method.Parameters.SequenceEqual(other.Parameters, AddressOf Me.AreParametersEqual) AndAlso method.TypeParameters.SequenceEqual(other.TypeParameters, AddressOf Me.AreTypesEqual) End Function Private Shared Function SubstituteTypeParameters(method As MethodSymbol) As MethodSymbol Debug.Assert(method.IsDefinition) Dim i As Integer = method.TypeParameters.Length If i = 0 Then Return method End If Return method.Construct(ImmutableArrayExtensions.Cast(Of TypeParameterSymbol, TypeSymbol)(IndexedTypeParameterSymbol.Take(i))) End Function Private Function AreNamedTypesEqual(type As NamedTypeSymbol, other As NamedTypeSymbol) As Boolean Debug.Assert(s_nameComparer.Equals(type.Name, other.Name)) Debug.Assert(Not type.HasTypeArgumentsCustomModifiers) Debug.Assert(Not other.HasTypeArgumentsCustomModifiers) ' Tuple types should be unwrapped to their underlying type before getting here (see MatchSymbols.VisitNamedType) Debug.Assert(Not type.IsTupleType) Debug.Assert(Not other.IsTupleType) Return type.TypeArgumentsNoUseSiteDiagnostics.SequenceEqual(other.TypeArgumentsNoUseSiteDiagnostics, AddressOf Me.AreTypesEqual) End Function Private Function AreNamespacesEqual([namespace] As NamespaceSymbol, other As NamespaceSymbol) As Boolean Debug.Assert(s_nameComparer.Equals([namespace].Name, other.Name)) Return True End Function Private Function AreParametersEqual(parameter As ParameterSymbol, other As ParameterSymbol) As Boolean Debug.Assert(parameter.Ordinal = other.Ordinal) Return parameter.IsByRef = other.IsByRef AndAlso Me._comparer.Equals(parameter.Type, other.Type) End Function Private Function ArePropertiesEqual([property] As PropertySymbol, other As PropertySymbol) As Boolean Debug.Assert(s_nameComparer.Equals([property].Name, other.Name)) Return Me._comparer.Equals([property].Type, other.Type) AndAlso [property].Parameters.SequenceEqual(other.Parameters, AddressOf Me.AreParametersEqual) End Function Private Shared Function AreTypeParametersEqual(type As TypeParameterSymbol, other As TypeParameterSymbol) As Boolean Debug.Assert(type.Ordinal = other.Ordinal) Debug.Assert(s_nameComparer.Equals(type.Name, other.Name)) ' Comparing constraints is unnecessary: two methods cannot differ by ' constraints alone and changing the signature of a method is a rude ' edit. Furthermore, comparing constraint types might lead to a cycle. Debug.Assert(type.HasConstructorConstraint = other.HasConstructorConstraint) Debug.Assert(type.HasValueTypeConstraint = other.HasValueTypeConstraint) Debug.Assert(type.HasReferenceTypeConstraint = other.HasReferenceTypeConstraint) Debug.Assert(type.ConstraintTypesNoUseSiteDiagnostics.Length = other.ConstraintTypesNoUseSiteDiagnostics.Length) Return True End Function Private Function AreTypesEqual(type As TypeSymbol, other As TypeSymbol) As Boolean If type.Kind <> other.Kind Then Return False End If Select Case type.Kind Case SymbolKind.ArrayType Return AreArrayTypesEqual(DirectCast(type, ArrayTypeSymbol), DirectCast(other, ArrayTypeSymbol)) Case SymbolKind.NamedType, SymbolKind.ErrorType Return AreNamedTypesEqual(DirectCast(type, NamedTypeSymbol), DirectCast(other, NamedTypeSymbol)) Case SymbolKind.TypeParameter Return AreTypeParametersEqual(DirectCast(type, TypeParameterSymbol), DirectCast(other, TypeParameterSymbol)) Case Else Throw ExceptionUtilities.UnexpectedValue(type.Kind) End Select End Function Private Function GetAllEmittedMembers(symbol As ISymbolInternal) As IReadOnlyDictionary(Of String, ImmutableArray(Of ISymbolInternal)) Dim members = ArrayBuilder(Of ISymbolInternal).GetInstance() If symbol.Kind = SymbolKind.NamedType Then Dim type = CType(symbol, NamedTypeSymbol) members.AddRange(type.GetEventsToEmit()) members.AddRange(type.GetFieldsToEmit()) members.AddRange(type.GetMethodsToEmit()) members.AddRange(type.GetTypeMembers()) members.AddRange(type.GetPropertiesToEmit()) Else members.AddRange(CType(symbol, NamespaceSymbol).GetMembers()) End If Dim synthesizedMembers As ImmutableArray(Of ISymbolInternal) = Nothing If _otherSynthesizedMembersOpt IsNot Nothing AndAlso _otherSynthesizedMembersOpt.TryGetValue(symbol, synthesizedMembers) Then members.AddRange(synthesizedMembers) End If Dim result = members.ToDictionary(Function(s) s.Name, s_nameComparer) members.Free() Return result End Function Private Class SymbolComparer Private ReadOnly _matcher As MatchSymbols Private ReadOnly _deepTranslatorOpt As DeepTranslator Public Sub New(matcher As MatchSymbols, deepTranslatorOpt As DeepTranslator) Debug.Assert(matcher IsNot Nothing) _matcher = matcher _deepTranslatorOpt = deepTranslatorOpt End Sub Public Overloads Function Equals(source As TypeSymbol, other As TypeSymbol) As Boolean Dim visitedSource = DirectCast(_matcher.Visit(source), TypeSymbol) Dim visitedOther = If(_deepTranslatorOpt IsNot Nothing, DirectCast(_deepTranslatorOpt.Visit(other), TypeSymbol), other) ' If both visitedSource and visitedOther are Nothing, return false meaning that the method was not able to verify the equality. Return visitedSource IsNot Nothing AndAlso visitedOther IsNot Nothing AndAlso visitedSource.IsSameType(visitedOther, TypeCompareKind.IgnoreTupleNames) End Function End Class End Class Friend NotInheritable Class DeepTranslator Inherits VisualBasicSymbolVisitor(Of Symbol) Private ReadOnly _matches As ConcurrentDictionary(Of Symbol, Symbol) Private ReadOnly _systemObject As NamedTypeSymbol Public Sub New(systemObject As NamedTypeSymbol) _matches = New ConcurrentDictionary(Of Symbol, Symbol)(ReferenceEqualityComparer.Instance) _systemObject = systemObject End Sub Public Overrides Function DefaultVisit(symbol As Symbol) As Symbol ' Symbol should have been handled elsewhere. Throw ExceptionUtilities.Unreachable End Function Public Overrides Function Visit(symbol As Symbol) As Symbol Return _matches.GetOrAdd(symbol, AddressOf MyBase.Visit) End Function Public Overrides Function VisitArrayType(symbol As ArrayTypeSymbol) As Symbol Dim translatedElementType As TypeSymbol = DirectCast(Me.Visit(symbol.ElementType), TypeSymbol) Dim translatedModifiers = VisitCustomModifiers(symbol.CustomModifiers) If symbol.IsSZArray Then Return ArrayTypeSymbol.CreateSZArray(translatedElementType, translatedModifiers, symbol.BaseTypeNoUseSiteDiagnostics.ContainingAssembly) End If Return ArrayTypeSymbol.CreateMDArray(translatedElementType, translatedModifiers, symbol.Rank, symbol.Sizes, symbol.LowerBounds, symbol.BaseTypeNoUseSiteDiagnostics.ContainingAssembly) End Function Public Overrides Function VisitNamedType(type As NamedTypeSymbol) As Symbol If type.IsTupleType Then type = type.TupleUnderlyingType Debug.Assert(Not type.IsTupleType) End If Dim originalDef As NamedTypeSymbol = type.OriginalDefinition If originalDef IsNot type Then Dim translatedTypeArguments = type.GetAllTypeArgumentsWithModifiers().SelectAsArray(Function(t, v) New TypeWithModifiers(DirectCast(v.Visit(t.Type), TypeSymbol), v.VisitCustomModifiers(t.CustomModifiers)), Me) Dim translatedOriginalDef = DirectCast(Me.Visit(originalDef), NamedTypeSymbol) Dim typeMap = TypeSubstitution.Create(translatedOriginalDef, translatedOriginalDef.GetAllTypeParameters(), translatedTypeArguments, False) Return translatedOriginalDef.Construct(typeMap) End If Debug.Assert(type.IsDefinition) If type.IsAnonymousType Then Return Me.Visit(AnonymousTypeManager.TranslateAnonymousTypeSymbol(type)) End If Return type End Function Public Overrides Function VisitTypeParameter(symbol As TypeParameterSymbol) As Symbol Return symbol End Function Private Function VisitCustomModifiers(modifiers As ImmutableArray(Of CustomModifier)) As ImmutableArray(Of CustomModifier) Return modifiers.SelectAsArray(AddressOf VisitCustomModifier) End Function Private Function VisitCustomModifier(modifier As CustomModifier) As CustomModifier Dim translatedType = DirectCast(Me.Visit(DirectCast(modifier.Modifier, Symbol)), NamedTypeSymbol) Debug.Assert(translatedType IsNot Nothing) Return If(modifier.IsOptional, VisualBasicCustomModifier.CreateOptional(translatedType), VisualBasicCustomModifier.CreateRequired(translatedType)) 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.Concurrent Imports System.Collections.Immutable Imports System.Runtime.InteropServices Imports System.Threading Imports Microsoft.CodeAnalysis.Emit Imports Microsoft.CodeAnalysis.PooledObjects Imports Microsoft.CodeAnalysis.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Symbols.Metadata.PE Namespace Microsoft.CodeAnalysis.VisualBasic.Emit Friend NotInheritable Class VisualBasicSymbolMatcher Inherits SymbolMatcher Private Shared ReadOnly s_nameComparer As StringComparer = IdentifierComparison.Comparer Private ReadOnly _defs As MatchDefs Private ReadOnly _symbols As MatchSymbols Public Sub New(anonymousTypeMap As IReadOnlyDictionary(Of AnonymousTypeKey, AnonymousTypeValue), sourceAssembly As SourceAssemblySymbol, sourceContext As EmitContext, otherAssembly As SourceAssemblySymbol, otherContext As EmitContext, otherSynthesizedMembersOpt As ImmutableDictionary(Of ISymbolInternal, ImmutableArray(Of ISymbolInternal))) _defs = New MatchDefsToSource(sourceContext, otherContext) _symbols = New MatchSymbols(anonymousTypeMap, sourceAssembly, otherAssembly, otherSynthesizedMembersOpt, New DeepTranslator(otherAssembly.GetSpecialType(SpecialType.System_Object))) End Sub Public Sub New(anonymousTypeMap As IReadOnlyDictionary(Of AnonymousTypeKey, AnonymousTypeValue), sourceAssembly As SourceAssemblySymbol, sourceContext As EmitContext, otherAssembly As PEAssemblySymbol) _defs = New MatchDefsToMetadata(sourceContext, otherAssembly) _symbols = New MatchSymbols(anonymousTypeMap, sourceAssembly, otherAssembly, otherSynthesizedMembersOpt:=Nothing, deepTranslatorOpt:=Nothing) End Sub Public Overrides Function MapDefinition(definition As Cci.IDefinition) As Cci.IDefinition Dim symbol As Symbol = TryCast(definition.GetInternalSymbol(), Symbol) If symbol IsNot Nothing Then Return DirectCast(_symbols.Visit(symbol)?.GetCciAdapter(), Cci.IDefinition) End If ' TODO: this appears to be dead code, remove (https://github.com/dotnet/roslyn/issues/51595) Return _defs.VisitDef(definition) End Function Public Overrides Function MapNamespace([namespace] As Cci.INamespace) As Cci.INamespace Debug.Assert(TypeOf [namespace].GetInternalSymbol() Is NamespaceSymbol) Return DirectCast(_symbols.Visit(DirectCast([namespace]?.GetInternalSymbol(), NamespaceSymbol))?.GetCciAdapter(), Cci.INamespace) End Function Public Overrides Function MapReference(reference As Cci.ITypeReference) As Cci.ITypeReference Dim symbol As Symbol = TryCast(reference.GetInternalSymbol(), Symbol) If symbol IsNot Nothing Then Return DirectCast(_symbols.Visit(symbol)?.GetCciAdapter(), Cci.ITypeReference) End If Return Nothing End Function Friend Function TryGetAnonymousTypeName(template As AnonymousTypeManager.AnonymousTypeOrDelegateTemplateSymbol, <Out> ByRef name As String, <Out> ByRef index As Integer) As Boolean Return _symbols.TryGetAnonymousTypeName(template, name, index) End Function Private MustInherit Class MatchDefs Private ReadOnly _sourceContext As EmitContext Private ReadOnly _matches As ConcurrentDictionary(Of Cci.IDefinition, Cci.IDefinition) Private _lazyTopLevelTypes As IReadOnlyDictionary(Of String, Cci.INamespaceTypeDefinition) Public Sub New(sourceContext As EmitContext) Me._sourceContext = sourceContext Me._matches = New ConcurrentDictionary(Of Cci.IDefinition, Cci.IDefinition)(ReferenceEqualityComparer.Instance) End Sub Public Function VisitDef(def As Cci.IDefinition) As Cci.IDefinition Return Me._matches.GetOrAdd(def, AddressOf Me.VisitDefInternal) End Function Private Function VisitDefInternal(def As Cci.IDefinition) As Cci.IDefinition Dim type = TryCast(def, Cci.ITypeDefinition) If type IsNot Nothing Then Dim namespaceType As Cci.INamespaceTypeDefinition = type.AsNamespaceTypeDefinition(Me._sourceContext) If namespaceType IsNot Nothing Then Return Me.VisitNamespaceType(namespaceType) End If Dim nestedType As Cci.INestedTypeDefinition = type.AsNestedTypeDefinition(Me._sourceContext) Debug.Assert(nestedType IsNot Nothing) Dim otherContainer = DirectCast(Me.VisitDef(nestedType.ContainingTypeDefinition), Cci.ITypeDefinition) If otherContainer Is Nothing Then Return Nothing End If Return VisitTypeMembers(otherContainer, nestedType, AddressOf GetNestedTypes, Function(a, b) s_nameComparer.Equals(a.Name, b.Name)) End If Dim member = TryCast(def, Cci.ITypeDefinitionMember) If member IsNot Nothing Then Dim otherContainer = DirectCast(Me.VisitDef(member.ContainingTypeDefinition), Cci.ITypeDefinition) If otherContainer Is Nothing Then Return Nothing End If Dim field = TryCast(def, Cci.IFieldDefinition) If field IsNot Nothing Then Return VisitTypeMembers(otherContainer, field, AddressOf GetFields, Function(a, b) s_nameComparer.Equals(a.Name, b.Name)) End If End If ' We are only expecting types and fields currently. Throw ExceptionUtilities.UnexpectedValue(def) End Function Protected MustOverride Function GetTopLevelTypes() As IEnumerable(Of Cci.INamespaceTypeDefinition) Protected MustOverride Function GetNestedTypes(def As Cci.ITypeDefinition) As IEnumerable(Of Cci.INestedTypeDefinition) Protected MustOverride Function GetFields(def As Cci.ITypeDefinition) As IEnumerable(Of Cci.IFieldDefinition) Private Function VisitNamespaceType(def As Cci.INamespaceTypeDefinition) As Cci.INamespaceTypeDefinition ' All generated top-level types are assumed to be in the global namespace. ' However, this may be an embedded NoPIA type within a namespace. ' Since we do not support edits that include references to NoPIA types ' (see #855640), it's reasonable to simply drop such cases. If Not String.IsNullOrEmpty(def.NamespaceName) Then Return Nothing End If Dim otherDef As Cci.INamespaceTypeDefinition = Nothing Me.GetTopLevelTypesByName().TryGetValue(def.Name, otherDef) Return otherDef End Function Private Function GetTopLevelTypesByName() As IReadOnlyDictionary(Of String, Cci.INamespaceTypeDefinition) If Me._lazyTopLevelTypes Is Nothing Then Dim typesByName As Dictionary(Of String, Cci.INamespaceTypeDefinition) = New Dictionary(Of String, Cci.INamespaceTypeDefinition)(s_nameComparer) For Each type As Cci.INamespaceTypeDefinition In Me.GetTopLevelTypes() ' All generated top-level types are assumed to be in the global namespace. If String.IsNullOrEmpty(type.NamespaceName) Then typesByName.Add(type.Name, type) End If Next Interlocked.CompareExchange(Me._lazyTopLevelTypes, typesByName, Nothing) End If Return Me._lazyTopLevelTypes End Function Private Shared Function VisitTypeMembers(Of T As {Class, Cci.ITypeDefinitionMember})( otherContainer As Cci.ITypeDefinition, member As T, getMembers As Func(Of Cci.ITypeDefinition, IEnumerable(Of T)), predicate As Func(Of T, T, Boolean)) As T ' We could cache the members by name (see Matcher.VisitNamedTypeMembers) ' but the assumption is this class is only used for types with few members ' so caching is not necessary and linear search is acceptable. Return getMembers(otherContainer).FirstOrDefault(Function(otherMember As T) predicate(member, otherMember)) End Function End Class Private NotInheritable Class MatchDefsToMetadata Inherits MatchDefs Private ReadOnly _otherAssembly As PEAssemblySymbol Public Sub New(sourceContext As EmitContext, otherAssembly As PEAssemblySymbol) MyBase.New(sourceContext) Me._otherAssembly = otherAssembly End Sub Protected Overrides Function GetTopLevelTypes() As IEnumerable(Of Cci.INamespaceTypeDefinition) Dim builder As ArrayBuilder(Of Cci.INamespaceTypeDefinition) = ArrayBuilder(Of Cci.INamespaceTypeDefinition).GetInstance() GetTopLevelTypes(builder, Me._otherAssembly.GlobalNamespace) Return builder.ToArrayAndFree() End Function Protected Overrides Function GetNestedTypes(def As Cci.ITypeDefinition) As IEnumerable(Of Cci.INestedTypeDefinition) Return (DirectCast(def, PENamedTypeSymbol)).GetTypeMembers().Cast(Of Cci.INestedTypeDefinition)() End Function Protected Overrides Function GetFields(def As Cci.ITypeDefinition) As IEnumerable(Of Cci.IFieldDefinition) Return (DirectCast(def, PENamedTypeSymbol)).GetFieldsToEmit().Cast(Of Cci.IFieldDefinition)() End Function Private Overloads Shared Sub GetTopLevelTypes(builder As ArrayBuilder(Of Cci.INamespaceTypeDefinition), [namespace] As NamespaceSymbol) For Each member In [namespace].GetMembers() If member.Kind = SymbolKind.Namespace Then GetTopLevelTypes(builder, DirectCast(member, NamespaceSymbol)) Else builder.Add(DirectCast(member.GetCciAdapter(), Cci.INamespaceTypeDefinition)) End If Next End Sub End Class Private NotInheritable Class MatchDefsToSource Inherits MatchDefs Private ReadOnly _otherContext As EmitContext Public Sub New(sourceContext As EmitContext, otherContext As EmitContext) MyBase.New(sourceContext) _otherContext = otherContext End Sub Protected Overrides Function GetTopLevelTypes() As IEnumerable(Of Cci.INamespaceTypeDefinition) Return _otherContext.Module.GetTopLevelTypeDefinitions(_otherContext) End Function Protected Overrides Function GetNestedTypes(def As Cci.ITypeDefinition) As IEnumerable(Of Cci.INestedTypeDefinition) Return def.GetNestedTypes(_otherContext) End Function Protected Overrides Function GetFields(def As Cci.ITypeDefinition) As IEnumerable(Of Cci.IFieldDefinition) Return def.GetFields(_otherContext) End Function End Class Private NotInheritable Class MatchSymbols Inherits VisualBasicSymbolVisitor(Of Symbol) Private ReadOnly _anonymousTypeMap As IReadOnlyDictionary(Of AnonymousTypeKey, AnonymousTypeValue) Private ReadOnly _comparer As SymbolComparer Private ReadOnly _matches As ConcurrentDictionary(Of Symbol, Symbol) Private ReadOnly _sourceAssembly As SourceAssemblySymbol Private ReadOnly _otherAssembly As AssemblySymbol Private ReadOnly _otherSynthesizedMembersOpt As ImmutableDictionary(Of ISymbolInternal, ImmutableArray(Of ISymbolInternal)) ' A cache of members per type, populated when the first member for a given ' type Is needed. Within each type, members are indexed by name. The reason ' for caching, And indexing by name, Is to avoid searching sequentially ' through all members of a given kind each time a member Is matched. Private ReadOnly _otherMembers As ConcurrentDictionary(Of ISymbolInternal, IReadOnlyDictionary(Of String, ImmutableArray(Of ISymbolInternal))) Public Sub New(anonymousTypeMap As IReadOnlyDictionary(Of AnonymousTypeKey, AnonymousTypeValue), sourceAssembly As SourceAssemblySymbol, otherAssembly As AssemblySymbol, otherSynthesizedMembersOpt As ImmutableDictionary(Of ISymbolInternal, ImmutableArray(Of ISymbolInternal)), deepTranslatorOpt As DeepTranslator) _anonymousTypeMap = anonymousTypeMap _sourceAssembly = sourceAssembly _otherAssembly = otherAssembly _otherSynthesizedMembersOpt = otherSynthesizedMembersOpt _comparer = New SymbolComparer(Me, deepTranslatorOpt) _matches = New ConcurrentDictionary(Of Symbol, Symbol)(ReferenceEqualityComparer.Instance) _otherMembers = New ConcurrentDictionary(Of ISymbolInternal, IReadOnlyDictionary(Of String, ImmutableArray(Of ISymbolInternal)))(ReferenceEqualityComparer.Instance) End Sub Friend Function TryGetAnonymousTypeName(type As AnonymousTypeManager.AnonymousTypeOrDelegateTemplateSymbol, <Out> ByRef name As String, <Out> ByRef index As Integer) As Boolean Dim otherType As AnonymousTypeValue = Nothing If TryFindAnonymousType(type, otherType) Then name = otherType.Name index = otherType.UniqueIndex Return True End If name = Nothing index = -1 Return False End Function Public Overrides Function DefaultVisit(symbol As Symbol) As Symbol ' Symbol should have been handled elsewhere. Throw ExceptionUtilities.Unreachable End Function Public Overrides Function Visit(symbol As Symbol) As Symbol Debug.Assert(symbol.ContainingAssembly IsNot Me._otherAssembly) ' Add an entry for the match, even if there Is no match, to avoid ' matching the same symbol unsuccessfully multiple times. Return Me._matches.GetOrAdd(symbol, AddressOf MyBase.Visit) End Function Public Overrides Function VisitArrayType(symbol As ArrayTypeSymbol) As Symbol Dim otherElementType As TypeSymbol = DirectCast(Me.Visit(symbol.ElementType), TypeSymbol) If otherElementType Is Nothing Then ' For a newly added type, there is no match in the previous generation, so it could be Nothing. Return Nothing End If Dim otherModifiers = VisitCustomModifiers(symbol.CustomModifiers) If symbol.IsSZArray Then Return ArrayTypeSymbol.CreateSZArray(otherElementType, otherModifiers, Me._otherAssembly) End If Return ArrayTypeSymbol.CreateMDArray(otherElementType, otherModifiers, symbol.Rank, symbol.Sizes, symbol.LowerBounds, Me._otherAssembly) End Function Public Overrides Function VisitEvent(symbol As EventSymbol) As Symbol Return Me.VisitNamedTypeMember(symbol, AddressOf Me.AreEventsEqual) End Function Public Overrides Function VisitField(symbol As FieldSymbol) As Symbol Return Me.VisitNamedTypeMember(symbol, AddressOf Me.AreFieldsEqual) End Function Public Overrides Function VisitMethod(symbol As MethodSymbol) As Symbol ' Not expecting constructed method. Debug.Assert(symbol.IsDefinition) Return Me.VisitNamedTypeMember(symbol, AddressOf Me.AreMethodsEqual) End Function Public Overrides Function VisitModule([module] As ModuleSymbol) As Symbol Dim otherAssembly = DirectCast(Visit([module].ContainingAssembly), AssemblySymbol) If otherAssembly Is Nothing Then Return Nothing End If ' manifest module: If [module].Ordinal = 0 Then Return otherAssembly.Modules(0) End If ' match non-manifest module by name: For i = 1 To otherAssembly.Modules.Length - 1 Dim otherModule = otherAssembly.Modules(i) ' use case sensitive comparison -- modules whose names differ in casing are considered distinct If StringComparer.Ordinal.Equals(otherModule.Name, [module].Name) Then Return otherModule End If Next Return Nothing End Function Public Overrides Function VisitAssembly(assembly As AssemblySymbol) As Symbol If assembly.IsLinked Then Return assembly End If ' When we map synthesized symbols from previous generations to the latest compilation ' we might encounter a symbol that is defined in arbitrary preceding generation, ' not just the immediately preceding generation. If the source assembly uses time-based ' versioning assemblies of preceding generations might differ in their version number. If IdentityEqualIgnoringVersionWildcard(assembly, _sourceAssembly) Then Return _otherAssembly End If ' find a referenced assembly with the exactly same source identity: For Each otherReferencedAssembly In _otherAssembly.Modules(0).ReferencedAssemblySymbols If IdentityEqualIgnoringVersionWildcard(assembly, otherReferencedAssembly) Then Return otherReferencedAssembly End If Next Return Nothing End Function Private Shared Function IdentityEqualIgnoringVersionWildcard(left As AssemblySymbol, right As AssemblySymbol) As Boolean Dim leftIdentity = left.Identity Dim rightIdentity = right.Identity Return AssemblyIdentityComparer.SimpleNameComparer.Equals(leftIdentity.Name, rightIdentity.Name) AndAlso If(left.AssemblyVersionPattern, leftIdentity.Version).Equals(If(right.AssemblyVersionPattern, rightIdentity.Version)) AndAlso AssemblyIdentity.EqualIgnoringNameAndVersion(leftIdentity, rightIdentity) End Function Public Overrides Function VisitNamespace([namespace] As NamespaceSymbol) As Symbol Dim otherContainer As Symbol = Visit([namespace].ContainingSymbol) ' Containing namespace will be missing from other assembly ' if its was added in the (newer) source assembly. If otherContainer Is Nothing Then Return Nothing End If Select Case otherContainer.Kind Case SymbolKind.NetModule Return DirectCast(otherContainer, ModuleSymbol).GlobalNamespace Case SymbolKind.Namespace Return FindMatchingMember(otherContainer, [namespace], AddressOf AreNamespacesEqual) Case Else Throw ExceptionUtilities.UnexpectedValue(otherContainer.Kind) End Select End Function Public Overrides Function VisitNamedType(type As NamedTypeSymbol) As Symbol Dim originalDef As NamedTypeSymbol = type.OriginalDefinition If originalDef IsNot type Then Dim otherDef As NamedTypeSymbol = DirectCast(Me.Visit(originalDef), NamedTypeSymbol) ' For anonymous delegates the rewriter generates a _ClosureCache$_N field ' of the constructed delegate type. For those cases, the matched result will ' be Nothing if the anonymous delegate is new to this compilation. If otherDef Is Nothing Then Return Nothing End If Dim otherTypeParameters As ImmutableArray(Of TypeParameterSymbol) = otherDef.GetAllTypeParameters() Dim translationFailed As Boolean = False Dim otherTypeArguments = type.GetAllTypeArgumentsWithModifiers().SelectAsArray(Function(t, v) Dim newType = DirectCast(v.Visit(t.Type), TypeSymbol) If newType Is Nothing Then ' For a newly added type, there is no match in the previous generation, so it could be Nothing. translationFailed = True newType = t.Type End If Return New TypeWithModifiers(newType, v.VisitCustomModifiers(t.CustomModifiers)) End Function, Me) If translationFailed Then ' There is no match in the previous generation. Return Nothing End If Dim typeMap = TypeSubstitution.Create(otherDef, otherTypeParameters, otherTypeArguments, False) Return otherDef.Construct(typeMap) ElseIf type.IsTupleType Then Dim otherDef = DirectCast(Me.Visit(type.TupleUnderlyingType), NamedTypeSymbol) If otherDef Is Nothing OrElse Not otherDef.IsTupleOrCompatibleWithTupleOfCardinality(type.TupleElementTypes.Length) Then Return Nothing End If Return otherDef End If Debug.Assert(type.IsDefinition) Dim otherContainer As Symbol = Me.Visit(type.ContainingSymbol) ' Containing type will be missing from other assembly ' if the type was added in the (newer) source assembly. If otherContainer Is Nothing Then Return Nothing End If Select Case otherContainer.Kind Case SymbolKind.Namespace Dim template = TryCast(type, AnonymousTypeManager.AnonymousTypeOrDelegateTemplateSymbol) If template IsNot Nothing Then Debug.Assert(otherContainer Is _otherAssembly.GlobalNamespace) Dim value As AnonymousTypeValue = Nothing TryFindAnonymousType(template, value) Return DirectCast(value.Type?.GetInternalSymbol(), NamedTypeSymbol) End If If type.IsAnonymousType Then Return Visit(AnonymousTypeManager.TranslateAnonymousTypeSymbol(type)) End If Return FindMatchingMember(otherContainer, type, AddressOf AreNamedTypesEqual) Case SymbolKind.NamedType Return FindMatchingMember(otherContainer, type, AddressOf AreNamedTypesEqual) Case Else Throw ExceptionUtilities.UnexpectedValue(otherContainer.Kind) End Select End Function Public Overrides Function VisitParameter(parameter As ParameterSymbol) As Symbol Throw ExceptionUtilities.Unreachable End Function Public Overrides Function VisitProperty(symbol As PropertySymbol) As Symbol Return Me.VisitNamedTypeMember(symbol, AddressOf Me.ArePropertiesEqual) End Function Public Overrides Function VisitTypeParameter(symbol As TypeParameterSymbol) As Symbol Dim indexed = TryCast(symbol, IndexedTypeParameterSymbol) If indexed IsNot Nothing Then Return indexed End If Dim otherContainer As Symbol = Me.Visit(symbol.ContainingSymbol) Debug.Assert(otherContainer IsNot Nothing) Dim otherTypeParameters As ImmutableArray(Of TypeParameterSymbol) Select Case otherContainer.Kind Case SymbolKind.NamedType, SymbolKind.ErrorType otherTypeParameters = DirectCast(otherContainer, NamedTypeSymbol).TypeParameters Case SymbolKind.Method otherTypeParameters = DirectCast(otherContainer, MethodSymbol).TypeParameters Case Else Throw ExceptionUtilities.UnexpectedValue(otherContainer.Kind) End Select Return otherTypeParameters(symbol.Ordinal) End Function Private Function VisitCustomModifiers(modifiers As ImmutableArray(Of CustomModifier)) As ImmutableArray(Of CustomModifier) Return modifiers.SelectAsArray(AddressOf VisitCustomModifier) End Function Private Function VisitCustomModifier(modifier As CustomModifier) As CustomModifier Dim type = DirectCast(Me.Visit(DirectCast(modifier.Modifier, Symbol)), NamedTypeSymbol) Debug.Assert(type IsNot Nothing) Return If(modifier.IsOptional, VisualBasicCustomModifier.CreateOptional(type), VisualBasicCustomModifier.CreateRequired(type)) End Function Friend Function TryFindAnonymousType(type As AnonymousTypeManager.AnonymousTypeOrDelegateTemplateSymbol, <Out> ByRef otherType As AnonymousTypeValue) As Boolean Debug.Assert(type.ContainingSymbol Is _sourceAssembly.GlobalNamespace) Return _anonymousTypeMap.TryGetValue(type.GetAnonymousTypeKey(), otherType) End Function Private Function VisitNamedTypeMember(Of T As Symbol)(member As T, predicate As Func(Of T, T, Boolean)) As Symbol Dim otherType As NamedTypeSymbol = DirectCast(Visit(member.ContainingType), NamedTypeSymbol) If otherType Is Nothing Then Return Nothing End If Return FindMatchingMember(otherType, member, predicate) End Function Private Function FindMatchingMember(Of T As Symbol)(otherTypeOrNamespace As ISymbolInternal, sourceMember As T, predicate As Func(Of T, T, Boolean)) As T Dim otherMembersByName = _otherMembers.GetOrAdd(otherTypeOrNamespace, AddressOf GetAllEmittedMembers) Dim otherMembers As ImmutableArray(Of ISymbolInternal) = Nothing If otherMembersByName.TryGetValue(sourceMember.Name, otherMembers) Then For Each otherMember In otherMembers Dim other = TryCast(otherMember, T) If other IsNot Nothing AndAlso predicate(sourceMember, other) Then Return other End If Next End If Return Nothing End Function Private Function AreArrayTypesEqual(type As ArrayTypeSymbol, other As ArrayTypeSymbol) As Boolean Debug.Assert(type.CustomModifiers.IsEmpty) Debug.Assert(other.CustomModifiers.IsEmpty) Return type.HasSameShapeAs(other) AndAlso Me.AreTypesEqual(type.ElementType, other.ElementType) End Function Private Function AreEventsEqual([event] As EventSymbol, other As EventSymbol) As Boolean Debug.Assert(s_nameComparer.Equals([event].Name, other.Name)) Return Me._comparer.Equals([event].Type, other.Type) End Function Private Function AreFieldsEqual(field As FieldSymbol, other As FieldSymbol) As Boolean Debug.Assert(s_nameComparer.Equals(field.Name, other.Name)) Return Me._comparer.Equals(field.Type, other.Type) End Function Private Function AreMethodsEqual(method As MethodSymbol, other As MethodSymbol) As Boolean Debug.Assert(s_nameComparer.Equals(method.Name, other.Name)) Debug.Assert(method.IsDefinition) Debug.Assert(other.IsDefinition) method = SubstituteTypeParameters(method) other = SubstituteTypeParameters(other) Return Me._comparer.Equals(method.ReturnType, other.ReturnType) AndAlso method.Parameters.SequenceEqual(other.Parameters, AddressOf Me.AreParametersEqual) AndAlso method.TypeParameters.SequenceEqual(other.TypeParameters, AddressOf Me.AreTypesEqual) End Function Private Shared Function SubstituteTypeParameters(method As MethodSymbol) As MethodSymbol Debug.Assert(method.IsDefinition) Dim i As Integer = method.TypeParameters.Length If i = 0 Then Return method End If Return method.Construct(ImmutableArrayExtensions.Cast(Of TypeParameterSymbol, TypeSymbol)(IndexedTypeParameterSymbol.Take(i))) End Function Private Function AreNamedTypesEqual(type As NamedTypeSymbol, other As NamedTypeSymbol) As Boolean Debug.Assert(s_nameComparer.Equals(type.Name, other.Name)) Debug.Assert(Not type.HasTypeArgumentsCustomModifiers) Debug.Assert(Not other.HasTypeArgumentsCustomModifiers) ' Tuple types should be unwrapped to their underlying type before getting here (see MatchSymbols.VisitNamedType) Debug.Assert(Not type.IsTupleType) Debug.Assert(Not other.IsTupleType) Return type.TypeArgumentsNoUseSiteDiagnostics.SequenceEqual(other.TypeArgumentsNoUseSiteDiagnostics, AddressOf Me.AreTypesEqual) End Function Private Function AreNamespacesEqual([namespace] As NamespaceSymbol, other As NamespaceSymbol) As Boolean Debug.Assert(s_nameComparer.Equals([namespace].Name, other.Name)) Return True End Function Private Function AreParametersEqual(parameter As ParameterSymbol, other As ParameterSymbol) As Boolean Debug.Assert(parameter.Ordinal = other.Ordinal) Return parameter.IsByRef = other.IsByRef AndAlso Me._comparer.Equals(parameter.Type, other.Type) End Function Private Function ArePropertiesEqual([property] As PropertySymbol, other As PropertySymbol) As Boolean Debug.Assert(s_nameComparer.Equals([property].Name, other.Name)) Return Me._comparer.Equals([property].Type, other.Type) AndAlso [property].Parameters.SequenceEqual(other.Parameters, AddressOf Me.AreParametersEqual) End Function Private Shared Function AreTypeParametersEqual(type As TypeParameterSymbol, other As TypeParameterSymbol) As Boolean Debug.Assert(type.Ordinal = other.Ordinal) Debug.Assert(s_nameComparer.Equals(type.Name, other.Name)) ' Comparing constraints is unnecessary: two methods cannot differ by ' constraints alone and changing the signature of a method is a rude ' edit. Furthermore, comparing constraint types might lead to a cycle. Debug.Assert(type.HasConstructorConstraint = other.HasConstructorConstraint) Debug.Assert(type.HasValueTypeConstraint = other.HasValueTypeConstraint) Debug.Assert(type.HasReferenceTypeConstraint = other.HasReferenceTypeConstraint) Debug.Assert(type.ConstraintTypesNoUseSiteDiagnostics.Length = other.ConstraintTypesNoUseSiteDiagnostics.Length) Return True End Function Private Function AreTypesEqual(type As TypeSymbol, other As TypeSymbol) As Boolean If type.Kind <> other.Kind Then Return False End If Select Case type.Kind Case SymbolKind.ArrayType Return AreArrayTypesEqual(DirectCast(type, ArrayTypeSymbol), DirectCast(other, ArrayTypeSymbol)) Case SymbolKind.NamedType, SymbolKind.ErrorType Return AreNamedTypesEqual(DirectCast(type, NamedTypeSymbol), DirectCast(other, NamedTypeSymbol)) Case SymbolKind.TypeParameter Return AreTypeParametersEqual(DirectCast(type, TypeParameterSymbol), DirectCast(other, TypeParameterSymbol)) Case Else Throw ExceptionUtilities.UnexpectedValue(type.Kind) End Select End Function Private Function GetAllEmittedMembers(symbol As ISymbolInternal) As IReadOnlyDictionary(Of String, ImmutableArray(Of ISymbolInternal)) Dim members = ArrayBuilder(Of ISymbolInternal).GetInstance() If symbol.Kind = SymbolKind.NamedType Then Dim type = CType(symbol, NamedTypeSymbol) members.AddRange(type.GetEventsToEmit()) members.AddRange(type.GetFieldsToEmit()) members.AddRange(type.GetMethodsToEmit()) members.AddRange(type.GetTypeMembers()) members.AddRange(type.GetPropertiesToEmit()) Else members.AddRange(CType(symbol, NamespaceSymbol).GetMembers()) End If Dim synthesizedMembers As ImmutableArray(Of ISymbolInternal) = Nothing If _otherSynthesizedMembersOpt IsNot Nothing AndAlso _otherSynthesizedMembersOpt.TryGetValue(symbol, synthesizedMembers) Then members.AddRange(synthesizedMembers) End If Dim result = members.ToDictionary(Function(s) s.Name, s_nameComparer) members.Free() Return result End Function Private Class SymbolComparer Private ReadOnly _matcher As MatchSymbols Private ReadOnly _deepTranslatorOpt As DeepTranslator Public Sub New(matcher As MatchSymbols, deepTranslatorOpt As DeepTranslator) Debug.Assert(matcher IsNot Nothing) _matcher = matcher _deepTranslatorOpt = deepTranslatorOpt End Sub Public Overloads Function Equals(source As TypeSymbol, other As TypeSymbol) As Boolean Dim visitedSource = DirectCast(_matcher.Visit(source), TypeSymbol) Dim visitedOther = If(_deepTranslatorOpt IsNot Nothing, DirectCast(_deepTranslatorOpt.Visit(other), TypeSymbol), other) ' If both visitedSource and visitedOther are Nothing, return false meaning that the method was not able to verify the equality. Return visitedSource IsNot Nothing AndAlso visitedOther IsNot Nothing AndAlso visitedSource.IsSameType(visitedOther, TypeCompareKind.IgnoreTupleNames) End Function End Class End Class Friend NotInheritable Class DeepTranslator Inherits VisualBasicSymbolVisitor(Of Symbol) Private ReadOnly _matches As ConcurrentDictionary(Of Symbol, Symbol) Private ReadOnly _systemObject As NamedTypeSymbol Public Sub New(systemObject As NamedTypeSymbol) _matches = New ConcurrentDictionary(Of Symbol, Symbol)(ReferenceEqualityComparer.Instance) _systemObject = systemObject End Sub Public Overrides Function DefaultVisit(symbol As Symbol) As Symbol ' Symbol should have been handled elsewhere. Throw ExceptionUtilities.Unreachable End Function Public Overrides Function Visit(symbol As Symbol) As Symbol Return _matches.GetOrAdd(symbol, AddressOf MyBase.Visit) End Function Public Overrides Function VisitArrayType(symbol As ArrayTypeSymbol) As Symbol Dim translatedElementType As TypeSymbol = DirectCast(Me.Visit(symbol.ElementType), TypeSymbol) Dim translatedModifiers = VisitCustomModifiers(symbol.CustomModifiers) If symbol.IsSZArray Then Return ArrayTypeSymbol.CreateSZArray(translatedElementType, translatedModifiers, symbol.BaseTypeNoUseSiteDiagnostics.ContainingAssembly) End If Return ArrayTypeSymbol.CreateMDArray(translatedElementType, translatedModifiers, symbol.Rank, symbol.Sizes, symbol.LowerBounds, symbol.BaseTypeNoUseSiteDiagnostics.ContainingAssembly) End Function Public Overrides Function VisitNamedType(type As NamedTypeSymbol) As Symbol If type.IsTupleType Then type = type.TupleUnderlyingType Debug.Assert(Not type.IsTupleType) End If Dim originalDef As NamedTypeSymbol = type.OriginalDefinition If originalDef IsNot type Then Dim translatedTypeArguments = type.GetAllTypeArgumentsWithModifiers().SelectAsArray(Function(t, v) New TypeWithModifiers(DirectCast(v.Visit(t.Type), TypeSymbol), v.VisitCustomModifiers(t.CustomModifiers)), Me) Dim translatedOriginalDef = DirectCast(Me.Visit(originalDef), NamedTypeSymbol) Dim typeMap = TypeSubstitution.Create(translatedOriginalDef, translatedOriginalDef.GetAllTypeParameters(), translatedTypeArguments, False) Return translatedOriginalDef.Construct(typeMap) End If Debug.Assert(type.IsDefinition) If type.IsAnonymousType Then Return Me.Visit(AnonymousTypeManager.TranslateAnonymousTypeSymbol(type)) End If Return type End Function Public Overrides Function VisitTypeParameter(symbol As TypeParameterSymbol) As Symbol Return symbol End Function Private Function VisitCustomModifiers(modifiers As ImmutableArray(Of CustomModifier)) As ImmutableArray(Of CustomModifier) Return modifiers.SelectAsArray(AddressOf VisitCustomModifier) End Function Private Function VisitCustomModifier(modifier As CustomModifier) As CustomModifier Dim translatedType = DirectCast(Me.Visit(DirectCast(modifier.Modifier, Symbol)), NamedTypeSymbol) Debug.Assert(translatedType IsNot Nothing) Return If(modifier.IsOptional, VisualBasicCustomModifier.CreateOptional(translatedType), VisualBasicCustomModifier.CreateRequired(translatedType)) End Function End Class End Class End Namespace
1
dotnet/roslyn
55,428
Test adding nested namespaces
Fixes https://github.com/dotnet/roslyn/issues/54939 The "workaround" that's already implemented is actually the correct behavior.
tmat
2021-08-05T01:19:03Z
2021-08-11T18:38:54Z
bc874ebc5111a2a33221409f895953b1536f6612
1cbbd423e17b186a8f1de89febb4db9a386d180d
Test adding nested namespaces. Fixes https://github.com/dotnet/roslyn/issues/54939 The "workaround" that's already implemented is actually the correct behavior.
./src/Compilers/VisualBasic/Test/Emit/Emit/EditAndContinue/EditAndContinueTests.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.IO Imports System.Reflection.Metadata Imports System.Reflection.Metadata.Ecma335 Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.CodeGen Imports Microsoft.CodeAnalysis.Emit Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.CodeAnalysis.VisualBasic.Emit Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Roslyn.Test.MetadataUtilities Imports Roslyn.Test.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests Public Class EditAndContinueTests Inherits EditAndContinueTestBase <Fact> Public Sub SemanticErrors_MethodBody() Dim source0 = MarkedSource(" Class C Shared Sub E() Dim x As Integer = 1 System.Console.WriteLine(x) End Sub Shared Sub G() System.Console.WriteLine(1) End Sub End Class ") Dim source1 = MarkedSource(" Class C Shared Sub E() Dim x = Unknown(2) System.Console.WriteLine(x) End Sub Shared Sub G() System.Console.WriteLine(2) End Sub End Class ") Dim compilation0 = CreateCompilationWithMscorlib40(source0.Tree, options:=ComSafeDebugDll) Dim compilation1 = compilation0.WithSource(source1.Tree) Dim e0 = compilation0.GetMember(Of MethodSymbol)("C.E") Dim e1 = compilation1.GetMember(Of MethodSymbol)("C.E") Dim g0 = compilation0.GetMember(Of MethodSymbol)("C.G") Dim g1 = compilation1.GetMember(Of MethodSymbol)("C.G") Dim v0 = CompileAndVerify(compilation0) Dim md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData) Dim generation0 = EmitBaseline.CreateInitialBaseline(md0, AddressOf v0.CreateSymReader().GetEncMethodDebugInfo) ' Semantic errors are reported only for the bodies of members being emitted. Dim diffError = compilation1.EmitDifference( generation0, ImmutableArray.Create(New SemanticEdit(SemanticEditKind.Update, e0, e1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables:=True))) diffError.EmitResult.Diagnostics.Verify( Diagnostic(ERRID.ERR_NameNotDeclared1, "Unknown").WithArguments("Unknown").WithLocation(4, 17)) Dim diffGood = compilation1.EmitDifference( generation0, ImmutableArray.Create(New SemanticEdit(SemanticEditKind.Update, g0, g1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables:=True))) diffGood.EmitResult.Diagnostics.Verify() diffGood.VerifyIL("C.G", " { // Code size 9 (0x9) .maxstack 1 IL_0000: nop IL_0001: ldc.i4.2 IL_0002: call ""Sub System.Console.WriteLine(Integer)"" IL_0007: nop IL_0008: ret }") End Sub <Fact> Public Sub SemanticErrors_Declaration() Dim source0 = MarkedSource(" Class C Sub G() System.Console.WriteLine(1) End Sub End Class ") Dim source1 = MarkedSource(" Class C Sub G() System.Console.WriteLine(1) End Sub End Class Class Bad Inherits Bad End Class ") Dim compilation0 = CreateCompilationWithMscorlib40(source0.Tree, options:=ComSafeDebugDll) Dim compilation1 = compilation0.WithSource(source1.Tree) Dim g0 = compilation0.GetMember(Of MethodSymbol)("C.G") Dim g1 = compilation1.GetMember(Of MethodSymbol)("C.G") Dim v0 = CompileAndVerify(compilation0) Dim md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData) Dim generation0 = EmitBaseline.CreateInitialBaseline(md0, AddressOf v0.CreateSymReader().GetEncMethodDebugInfo) Dim diff = compilation1.EmitDifference( generation0, ImmutableArray.Create(New SemanticEdit(SemanticEditKind.Update, g0, g1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables:=True))) diff.EmitResult.Diagnostics.Verify( Diagnostic(ERRID.ERR_TypeInItsInheritsClause1, "Bad").WithArguments("Bad").WithLocation(9, 12)) End Sub <Fact> Public Sub ModifyMethod_WithTuples() Dim source0 = " Class C Shared Sub Main End Sub Shared Function F() As (Integer, Integer) Return (1, 2) End Function End Class " Dim source1 = " Class C Shared Sub Main End Sub Shared Function F() As (Integer, Integer) Return (2, 3) End Function End Class " Dim compilation0 = CreateCompilationWithMscorlib40({source0}, options:=TestOptions.DebugExe, references:={ValueTupleRef, SystemRuntimeFacadeRef}) Dim compilation1 = compilation0.WithSource(source1) Dim bytes0 = compilation0.EmitToArray() Using md0 = ModuleMetadata.CreateFromImage(bytes0) Dim reader0 = md0.MetadataReader Dim method0 = compilation0.GetMember(Of MethodSymbol)("C.F") Dim generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider) Dim method1 = compilation1.GetMember(Of MethodSymbol)("C.F") Dim diff1 = compilation1.EmitDifference(generation0, ImmutableArray.Create(New SemanticEdit(SemanticEditKind.Update, method0, method1))) ' Verify delta metadata contains expected rows. Using md1 = diff1.GetMetadata() Dim reader1 = md1.Reader Dim readers = {reader0, reader1} EncValidation.VerifyModuleMvid(1, reader0, reader1) CheckNames(readers, reader1.GetTypeDefNames()) CheckNames(readers, reader1.GetMethodDefNames(), "F") CheckNames(readers, reader1.GetMemberRefNames(), ".ctor") ' System.ValueTuple ctor CheckEncLog(reader1, Row(3, TableIndex.AssemblyRef, EditAndContinueOperation.Default), Row(4, TableIndex.AssemblyRef, EditAndContinueOperation.Default), Row(7, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(8, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(9, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(2, TableIndex.TypeSpec, EditAndContinueOperation.Default), Row(2, TableIndex.StandAloneSig, EditAndContinueOperation.Default), Row(3, TableIndex.MethodDef, EditAndContinueOperation.Default)) ' C.F CheckEncMap(reader1, Handle(8, TableIndex.TypeRef), Handle(9, TableIndex.TypeRef), Handle(3, TableIndex.MethodDef), Handle(7, TableIndex.MemberRef), Handle(2, TableIndex.StandAloneSig), Handle(2, TableIndex.TypeSpec), Handle(3, TableIndex.AssemblyRef), Handle(4, TableIndex.AssemblyRef)) End Using End Using End Sub <Fact> Public Sub ModifyMethod_RenameParameter() Dim source0 = " Class C Shared Function F(i As Integer) As Integer Return i End Function End Class " Dim source1 = " Class C Shared Function F(x As Integer) As Integer Return x End Function End Class " Dim compilation0 = CreateCompilationWithMscorlib40({source0}, options:=TestOptions.DebugDll, references:={ValueTupleRef, SystemRuntimeFacadeRef}) Dim compilation1 = compilation0.WithSource(source1) Dim bytes0 = compilation0.EmitToArray() Using md0 = ModuleMetadata.CreateFromImage(bytes0) Dim reader0 = md0.MetadataReader Dim method0 = compilation0.GetMember(Of MethodSymbol)("C.F") Dim generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider) CheckNames(reader0, reader0.GetParameterDefNames(), "i") Dim method1 = compilation1.GetMember(Of MethodSymbol)("C.F") Dim diff1 = compilation1.EmitDifference(generation0, ImmutableArray.Create(New SemanticEdit(SemanticEditKind.Update, method0, method1))) ' Verify delta metadata contains expected rows. Using md1 = diff1.GetMetadata() Dim reader1 = md1.Reader Dim readers = {reader0, reader1} EncValidation.VerifyModuleMvid(1, reader0, reader1) CheckNames(readers, reader1.GetTypeDefNames()) CheckNames(readers, reader1.GetMethodDefNames(), "F") CheckNames(readers, reader1.GetParameterDefNames(), "x") CheckEncLogDefinitions(reader1, Row(2, TableIndex.StandAloneSig, EditAndContinueOperation.Default), Row(2, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(1, TableIndex.Param, EditAndContinueOperation.Default)) CheckEncMapDefinitions(reader1, Handle(2, TableIndex.MethodDef), Handle(1, TableIndex.Param), Handle(2, TableIndex.StandAloneSig)) End Using End Using End Sub <WorkItem(962219, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/962219")> <Fact> Public Sub PartialMethod() Dim source = <compilation> <file name="a.vb"> Partial Class C Private Shared Partial Sub M1() End Sub Private Shared Partial Sub M2() End Sub Private Shared Partial Sub M3() End Sub Private Shared Sub M1() End Sub Private Shared Sub M2() End Sub End Class </file> </compilation> Dim compilation0 = CreateCompilationWithMscorlib40AndVBRuntime(source, TestOptions.DebugDll) Dim compilation1 = compilation0.Clone() Dim bytes0 = compilation0.EmitToArray() Using md0 = ModuleMetadata.CreateFromImage(bytes0) Dim reader0 = md0.MetadataReader CheckNames(reader0, reader0.GetMethodDefNames(), ".ctor", "M1", "M2") Dim method0 = compilation0.GetMember(Of MethodSymbol)("C.M2").PartialImplementationPart Dim method1 = compilation1.GetMember(Of MethodSymbol)("C.M2").PartialImplementationPart Dim generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), EmptyLocalsProvider) Dim diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(New SemanticEdit(SemanticEditKind.Update, method0, method1))) Dim methods = diff1.TestData.GetMethodsByName() Assert.Equal(methods.Count, 1) Assert.True(methods.ContainsKey("C.M2()")) Using md1 = diff1.GetMetadata() Dim reader1 = md1.Reader Dim readers = {reader0, reader1} CheckNames(readers, reader1.GetMethodDefNames(), "M2") CheckEncLog(reader1, Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default), Row(6, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(3, TableIndex.MethodDef, EditAndContinueOperation.Default)) CheckEncMap(reader1, Handle(6, TableIndex.TypeRef), Handle(3, TableIndex.MethodDef), Handle(2, TableIndex.AssemblyRef)) End Using End Using End Sub <Fact> Public Sub AddThenModifyExplicitImplementation() Dim source0 = <compilation> <file name="a.vb"> Interface I(Of T) Sub M() End Interface </file> </compilation> Dim source1 = <compilation> <file name="a.vb"> Interface I(Of T) Sub M() End Interface Class A Implements I(Of Integer), I(Of Object) Public Sub New() End Sub Sub M() Implements I(Of Integer).M, I(Of Object).M End Sub End Class </file> </compilation> Dim source2 = source1 Dim source3 = <compilation> <file name="a.vb"> Interface I(Of T) Sub M() End Interface Class A Implements I(Of Integer), I(Of Object) Public Sub New() End Sub Sub M() Implements I(Of Integer).M, I(Of Object).M End Sub End Class Class B Implements I(Of Object) Public Sub New() End Sub Sub M() Implements I(Of Object).M End Sub End Class </file> </compilation> Dim compilation0 = CreateCompilationWithMscorlib40AndVBRuntime(source0, TestOptions.DebugDll) Dim compilation1 = compilation0.WithSource(source1) Dim compilation2 = compilation1.WithSource(source2) Dim compilation3 = compilation2.WithSource(source3) Dim bytes0 = compilation0.EmitToArray() Using md0 = ModuleMetadata.CreateFromImage(bytes0) Dim reader0 = md0.MetadataReader Dim type1 = compilation1.GetMember(Of NamedTypeSymbol)("A") Dim method1 = compilation1.GetMember(Of MethodSymbol)("A.M") Dim generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), EmptyLocalsProvider) Dim diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(New SemanticEdit(SemanticEditKind.Insert, Nothing, type1))) Using md1 = diff1.GetMetadata() Dim reader1 = md1.Reader Dim readers = {reader0, reader1} CheckNames(readers, reader1.GetMethodDefNames(), ".ctor", "M") CheckEncLog(reader1, Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default), Row(4, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(5, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(6, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(5, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(1, TableIndex.TypeSpec, EditAndContinueOperation.Default), Row(2, TableIndex.TypeSpec, EditAndContinueOperation.Default), Row(3, TableIndex.TypeDef, EditAndContinueOperation.Default), Row(3, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(2, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(3, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(3, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(1, TableIndex.MethodImpl, EditAndContinueOperation.Default), Row(2, TableIndex.MethodImpl, EditAndContinueOperation.Default), Row(1, TableIndex.InterfaceImpl, EditAndContinueOperation.Default), Row(2, TableIndex.InterfaceImpl, EditAndContinueOperation.Default)) CheckEncMap(reader1, Handle(5, TableIndex.TypeRef), Handle(3, TableIndex.TypeDef), Handle(2, TableIndex.MethodDef), Handle(3, TableIndex.MethodDef), Handle(1, TableIndex.InterfaceImpl), Handle(2, TableIndex.InterfaceImpl), Handle(4, TableIndex.MemberRef), Handle(5, TableIndex.MemberRef), Handle(6, TableIndex.MemberRef), Handle(1, TableIndex.MethodImpl), Handle(2, TableIndex.MethodImpl), Handle(1, TableIndex.TypeSpec), Handle(2, TableIndex.TypeSpec), Handle(2, TableIndex.AssemblyRef)) Dim generation1 = diff1.NextGeneration Dim method2 = compilation2.GetMember(Of MethodSymbol)("A.M") Dim diff2 = compilation2.EmitDifference( generation1, ImmutableArray.Create(New SemanticEdit(SemanticEditKind.Update, method1, method2))) Using md2 = diff2.GetMetadata() Dim reader2 = md2.Reader readers = {reader0, reader1, reader2} CheckNames(readers, reader2.GetMethodDefNames(), "M") CheckEncLog(reader2, Row(3, TableIndex.AssemblyRef, EditAndContinueOperation.Default), Row(6, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(3, TableIndex.TypeSpec, EditAndContinueOperation.Default), Row(4, TableIndex.TypeSpec, EditAndContinueOperation.Default), Row(3, TableIndex.MethodDef, EditAndContinueOperation.Default)) CheckEncMap(reader2, Handle(6, TableIndex.TypeRef), Handle(3, TableIndex.MethodDef), Handle(3, TableIndex.TypeSpec), Handle(4, TableIndex.TypeSpec), Handle(3, TableIndex.AssemblyRef)) Dim generation2 = diff2.NextGeneration Dim type3 = compilation3.GetMember(Of NamedTypeSymbol)("B") Dim diff3 = compilation3.EmitDifference( generation1, ImmutableArray.Create(New SemanticEdit(SemanticEditKind.Insert, Nothing, type3))) Using md3 = diff3.GetMetadata() Dim reader3 = md3.Reader readers = {reader0, reader1, reader3} CheckNames(readers, reader3.GetMethodDefNames(), ".ctor", "M") CheckEncLog(reader3, Row(3, TableIndex.AssemblyRef, EditAndContinueOperation.Default), Row(7, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(8, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(6, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(3, TableIndex.TypeSpec, EditAndContinueOperation.Default), Row(4, TableIndex.TypeDef, EditAndContinueOperation.Default), Row(4, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(4, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(4, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(5, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(3, TableIndex.MethodImpl, EditAndContinueOperation.Default), Row(3, TableIndex.InterfaceImpl, EditAndContinueOperation.Default)) CheckEncMap(reader3, Handle(6, TableIndex.TypeRef), Handle(4, TableIndex.TypeDef), Handle(4, TableIndex.MethodDef), Handle(5, TableIndex.MethodDef), Handle(3, TableIndex.InterfaceImpl), Handle(7, TableIndex.MemberRef), Handle(8, TableIndex.MemberRef), Handle(3, TableIndex.MethodImpl), Handle(3, TableIndex.TypeSpec), Handle(3, TableIndex.AssemblyRef)) End Using End Using End Using End Using End Sub <Fact, WorkItem(930065, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/930065")> Public Sub ModifyConstructorBodyInPresenceOfExplicitInterfaceImplementation() Dim source = <compilation> <file name="a.vb"> Interface I Sub M1() Sub M2() End Interface Class C Implements I Public Sub New() End Sub Sub M() Implements I.M1, I.M2 End Sub End Class </file> </compilation> Dim compilation0 = CreateCompilationWithMscorlib40AndVBRuntime(source, TestOptions.DebugDll) Dim compilation1 = compilation0.Clone() Dim bytes0 = compilation0.EmitToArray() Using md0 = ModuleMetadata.CreateFromImage(bytes0) Dim reader0 = md0.MetadataReader Dim method0 = compilation0.GetMember(Of NamedTypeSymbol)("C").InstanceConstructors.Single() Dim method1 = compilation1.GetMember(Of NamedTypeSymbol)("C").InstanceConstructors.Single() Dim generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), EmptyLocalsProvider) Dim diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(New SemanticEdit(SemanticEditKind.Update, method0, method1))) Using md1 = diff1.GetMetadata() Dim reader1 = md1.Reader Dim readers = {reader0, reader1} CheckNames(readers, reader1.GetTypeDefNames()) CheckNames(readers, reader1.GetMethodDefNames(), ".ctor") CheckEncLog(reader1, Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default), Row(5, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(6, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(3, TableIndex.MethodDef, EditAndContinueOperation.Default)) CheckEncMap(reader1, Handle(6, TableIndex.TypeRef), Handle(3, TableIndex.MethodDef), Handle(5, TableIndex.MemberRef), Handle(2, TableIndex.AssemblyRef)) End Using End Using End Sub <Fact> Public Sub NamespacesAndOverloads() Dim compilation0 = CreateCompilationWithMscorlib40AndVBRuntime(options:=TestOptions.DebugDll, source:= <compilation> <file name="a.vb"><![CDATA[ Class C End Class Namespace N Class C End Class End Namespace Namespace M Class C Sub M1(o As N.C) End Sub Sub M1(o As M.C) End Sub Sub M2(a As N.C, b As M.C, c As Global.C) M1(a) End Sub End Class End Namespace ]]></file> </compilation>) Dim bytes = compilation0.EmitToArray() Dim generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes), EmptyLocalsProvider) Dim compilation1 = compilation0.WithSource( <compilation> <file name="a.vb"><![CDATA[ Class C End Class Namespace N Class C End Class End Namespace Namespace M Class C Sub M1(o As N.C) End Sub Sub M1(o As M.C) End Sub Sub M1(o As Global.C) End Sub Sub M2(a As N.C, b As M.C, c As Global.C) M1(a) M1(b) End Sub End Class End Namespace ]]></file> </compilation>) Dim diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(New SemanticEdit(SemanticEditKind.Insert, Nothing, compilation1.GetMembers("M.C.M1")(2)), New SemanticEdit(SemanticEditKind.Update, compilation0.GetMembers("M.C.M2")(0), compilation1.GetMembers("M.C.M2")(0)))) diff1.VerifyIL(" { // Code size 18 (0x12) .maxstack 8 IL_0000: nop IL_0001: ldarg.0 IL_0002: ldarg.1 IL_0003: call 0x06000004 IL_0008: nop IL_0009: ldarg.0 IL_000a: ldarg.2 IL_000b: call 0x06000005 IL_0010: nop IL_0011: ret } { // Code size 2 (0x2) .maxstack 8 IL_0000: nop IL_0001: ret } ") Dim compilation2 = compilation1.WithSource( <compilation> <file name="a.vb"><![CDATA[ Class C End Class Namespace N Class C End Class End Namespace Namespace M Class C Sub M1(o As N.C) End Sub Sub M1(o As M.C) End Sub Sub M1(o As Global.C) End Sub Sub M2(a As N.C, b As M.C, c As Global.C) M1(a) M1(b) M1(c) End Sub End Class End Namespace ]]></file> </compilation>) Dim diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create(New SemanticEdit(SemanticEditKind.Update, compilation1.GetMembers("M.C.M2")(0), compilation2.GetMembers("M.C.M2")(0)))) diff2.VerifyIL(" { // Code size 26 (0x1a) .maxstack 8 IL_0000: nop IL_0001: ldarg.0 IL_0002: ldarg.1 IL_0003: call 0x06000004 IL_0008: nop IL_0009: ldarg.0 IL_000a: ldarg.2 IL_000b: call 0x06000005 IL_0010: nop IL_0011: ldarg.0 IL_0012: ldarg.3 IL_0013: call 0x06000007 IL_0018: nop IL_0019: ret } ") End Sub <WorkItem(829353, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/829353")> <Fact()> Public Sub PrivateImplementationDetails_ArrayInitializer_FromMetadata() Dim sources0 = <compilation> <file name="a.vb"><![CDATA[ Class C Shared Sub M() Dim a As Integer() = {1, 2, 3} System.Console.Write(a(0)) End Sub End Class ]]></file> </compilation> Dim sources1 = <compilation> <file name="a.vb"><![CDATA[ Class C Shared Sub M() Dim a As Integer() = {1, 2, 3} System.Console.Write(a(1)) End Sub End Class ]]></file> </compilation> Dim compilation0 = CreateCompilationWithMscorlib40AndVBRuntime(sources0, TestOptions.DebugDll.WithModuleName("MODULE")) Dim compilation1 = compilation0.WithSource(sources1) Dim testData0 = New CompilationTestData() Dim bytes0 = compilation0.EmitToArray(testData:=testData0) Dim methodData0 = testData0.GetMethodData("C.M") methodData0.VerifyIL(" { // Code size 29 (0x1d) .maxstack 3 .locals init (Integer() V_0) //a IL_0000: nop IL_0001: ldc.i4.3 IL_0002: newarr ""Integer"" IL_0007: dup IL_0008: ldtoken ""<PrivateImplementationDetails>.__StaticArrayInitTypeSize=12 <PrivateImplementationDetails>.4636993D3E1DA4E9D6B8F87B79E8F7C6D018580D52661950EABC3845C5897A4D"" IL_000d: call ""Sub System.Runtime.CompilerServices.RuntimeHelpers.InitializeArray(System.Array, System.RuntimeFieldHandle)"" IL_0012: stloc.0 IL_0013: ldloc.0 IL_0014: ldc.i4.0 IL_0015: ldelem.i4 IL_0016: call ""Sub System.Console.Write(Integer)"" IL_001b: nop IL_001c: ret } ") Dim method0 = compilation0.GetMember(Of MethodSymbol)("C.M") Dim generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), methodData0.EncDebugInfoProvider) Dim testData1 = New CompilationTestData() Dim method1 = compilation1.GetMember(Of MethodSymbol)("C.M") Dim edit = New SemanticEdit(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables:=True) Dim diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(edit)) diff1.VerifyIL("C.M", " { // Code size 30 (0x1e) .maxstack 4 .locals init (Integer() V_0) //a IL_0000: nop IL_0001: ldc.i4.3 IL_0002: newarr ""Integer"" IL_0007: dup IL_0008: ldc.i4.0 IL_0009: ldc.i4.1 IL_000a: stelem.i4 IL_000b: dup IL_000c: ldc.i4.1 IL_000d: ldc.i4.2 IL_000e: stelem.i4 IL_000f: dup IL_0010: ldc.i4.2 IL_0011: ldc.i4.3 IL_0012: stelem.i4 IL_0013: stloc.0 IL_0014: ldloc.0 IL_0015: ldc.i4.1 IL_0016: ldelem.i4 IL_0017: call ""Sub System.Console.Write(Integer)"" IL_001c: nop IL_001d: ret } ") End Sub ''' <summary> ''' Should not generate method for string switch since ''' the CLR only allows adding private members. ''' </summary> <WorkItem(834086, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/834086")> <Fact()> Public Sub PrivateImplementationDetails_ComputeStringHash() Dim sources = <compilation> <file name="a.vb"><![CDATA[ Class C Shared Function F(s As String) Select Case s Case "1" Return 1 Case "2" Return 2 Case "3" Return 3 Case "4" Return 4 Case "5" Return 5 Case "6" Return 6 Case "7" Return 7 Case Else Return 0 End Select End Function End Class ]]></file> </compilation> Const ComputeStringHashName As String = "ComputeStringHash" Dim compilation0 = CreateCompilationWithMscorlib40AndVBRuntime(sources, TestOptions.DebugDll) Dim compilation1 = compilation0.WithSource(sources) Dim testData0 = New CompilationTestData() Dim bytes0 = compilation0.EmitToArray(testData:=testData0) Dim methodData0 = testData0.GetMethodData("C.F") Dim method0 = compilation0.GetMember(Of MethodSymbol)("C.F") Dim generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), methodData0.EncDebugInfoProvider) ' Should have generated call to ComputeStringHash and ' added the method to <PrivateImplementationDetails>. Dim actualIL0 = methodData0.GetMethodIL() Assert.True(actualIL0.Contains(ComputeStringHashName)) Using md0 = ModuleMetadata.CreateFromImage(bytes0) Dim reader0 = md0.MetadataReader CheckNames(reader0, reader0.GetMethodDefNames(), ".ctor", "F", ComputeStringHashName) Dim testData1 = New CompilationTestData() Dim method1 = compilation1.GetMember(Of MethodSymbol)("C.F") Dim edit = New SemanticEdit(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables:=True) Dim diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(edit)) ' Should not have generated call to ComputeStringHash nor ' added the method to <PrivateImplementationDetails>. Dim actualIL1 = diff1.GetMethodIL("C.F") Assert.False(actualIL1.Contains(ComputeStringHashName)) Using md1 = diff1.GetMetadata() Dim reader1 = md1.Reader Dim readers = {reader0, reader1} CheckNames(readers, reader1.GetMethodDefNames(), "F") End Using End Using End Sub ''' <summary> ''' Avoid adding references from method bodies ''' other than the changed methods. ''' </summary> <Fact> Public Sub ReferencesInIL() Dim sources0 = <compilation> <file name="a.vb"><![CDATA[ Module M Sub F() System.Console.WriteLine(1) End Sub Sub G() System.Console.WriteLine(2) End Sub End Module ]]></file> </compilation> Dim sources1 = <compilation> <file name="a.vb"><![CDATA[ Module M Sub F() System.Console.WriteLine(1) End Sub Sub G() System.Console.Write(2) End Sub End Module ]]></file> </compilation> Dim compilation0 = CreateCompilationWithMscorlib40AndVBRuntime(sources0, TestOptions.DebugDll) Dim compilation1 = compilation0.WithSource(sources1) ' Verify full metadata contains expected rows. Dim bytes0 = compilation0.EmitToArray() Using md0 = ModuleMetadata.CreateFromImage(bytes0) Dim reader0 = md0.MetadataReader CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "M") CheckNames(reader0, reader0.GetMethodDefNames(), "F", "G") CheckNames(reader0, reader0.GetMemberRefNames(), ".ctor", ".ctor", ".ctor", ".ctor", "WriteLine") Dim generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider) Dim diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(New SemanticEdit(SemanticEditKind.Insert, Nothing, compilation1.GetMember("M.G")))) ' "Write" should be included in string table, but "WriteLine" should not. Assert.True(diff1.MetadataDelta.IsIncluded("Write")) Assert.False(diff1.MetadataDelta.IsIncluded("WriteLine")) End Using End Sub <Fact> Public Sub ExceptionFilters() Dim source0 = MarkedSource(" Imports System Imports System.IO Class C Shared Function filter(e As Exception) Return True End Function Shared Sub F() Try Throw New InvalidOperationException() <N:0>Catch e As IOException <N:1>When filter(e)</N:1></N:0> Console.WriteLine() <N:2>Catch e As Exception <N:3>When filter(e)</N:3></N:2> Console.WriteLine() End Try End Sub End Class ") Dim source1 = MarkedSource(" Imports System Imports System.IO Class C Shared Function filter(e As Exception) Return True End Function Shared Sub F() Try Throw New InvalidOperationException() <N:0>Catch e As IOException <N:1>When filter(e)</N:1></N:0> Console.WriteLine() <N:2>Catch e As Exception <N:3>When filter(e)</N:3></N:2> Console.WriteLine() End Try Console.WriteLine() End Sub End Class ") Dim compilation0 = CreateCompilationWithMscorlib45AndVBRuntime({source0.Tree}, options:=ComSafeDebugDll) Dim compilation1 = compilation0.WithSource(source1.Tree) Dim v0 = CompileAndVerify(compilation0) Dim md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData) Dim f0 = compilation0.GetMember(Of MethodSymbol)("C.F") Dim f1 = compilation1.GetMember(Of MethodSymbol)("C.F") Dim generation0 = EmitBaseline.CreateInitialBaseline(md0, AddressOf v0.CreateSymReader().GetEncMethodDebugInfo) Dim diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( New SemanticEdit(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables:=True))) diff1.VerifyIL("C.F", " { // Code size 118 (0x76) .maxstack 2 .locals init (System.IO.IOException V_0, //e Boolean V_1, System.Exception V_2, //e Boolean V_3) IL_0000: nop .try { IL_0001: nop IL_0002: newobj ""Sub System.InvalidOperationException..ctor()"" IL_0007: throw } filter { IL_0008: isinst ""System.IO.IOException"" IL_000d: dup IL_000e: brtrue.s IL_0014 IL_0010: pop IL_0011: ldc.i4.0 IL_0012: br.s IL_002b IL_0014: dup IL_0015: call ""Sub Microsoft.VisualBasic.CompilerServices.ProjectData.SetProjectError(System.Exception)"" IL_001a: stloc.0 IL_001b: ldloc.0 IL_001c: call ""Function C.filter(System.Exception) As Object"" IL_0021: call ""Function Microsoft.VisualBasic.CompilerServices.Conversions.ToBoolean(Object) As Boolean"" IL_0026: stloc.1 IL_0027: ldloc.1 IL_0028: ldc.i4.0 IL_0029: cgt.un IL_002b: endfilter } // end filter { // handler IL_002d: pop IL_002e: call ""Sub System.Console.WriteLine()"" IL_0033: nop IL_0034: call ""Sub Microsoft.VisualBasic.CompilerServices.ProjectData.ClearProjectError()"" IL_0039: leave.s IL_006e } filter { IL_003b: isinst ""System.Exception"" IL_0040: dup IL_0041: brtrue.s IL_0047 IL_0043: pop IL_0044: ldc.i4.0 IL_0045: br.s IL_005e IL_0047: dup IL_0048: call ""Sub Microsoft.VisualBasic.CompilerServices.ProjectData.SetProjectError(System.Exception)"" IL_004d: stloc.2 IL_004e: ldloc.2 IL_004f: call ""Function C.filter(System.Exception) As Object"" IL_0054: call ""Function Microsoft.VisualBasic.CompilerServices.Conversions.ToBoolean(Object) As Boolean"" IL_0059: stloc.3 IL_005a: ldloc.3 IL_005b: ldc.i4.0 IL_005c: cgt.un IL_005e: endfilter } // end filter { // handler IL_0060: pop IL_0061: call ""Sub System.Console.WriteLine()"" IL_0066: nop IL_0067: call ""Sub Microsoft.VisualBasic.CompilerServices.ProjectData.ClearProjectError()"" IL_006c: leave.s IL_006e } IL_006e: nop IL_006f: call ""Sub System.Console.WriteLine()"" IL_0074: nop IL_0075: ret } ") End Sub <Fact> Public Sub SymbolMatcher_TypeArguments() Dim source = <compilation> <file name="c.vb"><![CDATA[ Class A(Of T) Class B(Of U) Shared Function M(Of V)(x As A(Of U).B(Of T), y As A(Of Object).S) As A(Of V) Return Nothing End Function Shared Function M(Of V)(x As A(Of U).B(Of T), y As A(Of V).S) As A(Of V) Return Nothing End Function End Class Structure S End Structure End Class ]]> </file> </compilation> Dim compilation0 = CreateCompilationWithMscorlib40AndVBRuntime(source, TestOptions.DebugDll) Dim compilation1 = compilation0.Clone() Dim matcher = CreateMatcher(compilation1, compilation0) Dim members = compilation1.GetMember(Of NamedTypeSymbol)("A.B").GetMembers("M") Assert.Equal(members.Length, 2) For Each member In members Dim other = DirectCast(matcher.MapDefinition(DirectCast(member.GetCciAdapter(), Cci.IMethodDefinition)).GetInternalSymbol(), MethodSymbol) Assert.NotNull(other) Next End Sub <Fact> Public Sub SymbolMatcher_Constraints() Dim source = <compilation> <file name="c.vb"><![CDATA[ Interface I(Of T As I(Of T)) End Interface Class C Shared Sub M(Of T As I(Of T))(o As I(Of T)) End Sub End Class ]]> </file> </compilation> Dim compilation0 = CreateCompilationWithMscorlib40AndVBRuntime(source, TestOptions.DebugDll) Dim compilation1 = compilation0.Clone() Dim matcher = CreateMatcher(compilation1, compilation0) Dim member = compilation1.GetMember(Of MethodSymbol)("C.M") Dim other = DirectCast(matcher.MapDefinition(DirectCast(member.GetCciAdapter(), Cci.IMethodDefinition)).GetInternalSymbol(), MethodSymbol) Assert.NotNull(other) End Sub <Fact> Public Sub SymbolMatcher_CustomModifiers() Dim ilSource = <![CDATA[ .class public abstract A { .method public hidebysig specialname rtspecialname instance void .ctor() { ret } .method public abstract virtual instance object modopt(A) [] F() { } } ]]>.Value Dim source = <compilation> <file name="c.vb"><![CDATA[ Class B Inherits A Public Overrides Function F() As Object() Return Nothing End Function End Class ]]> </file> </compilation> Dim metadata = CompileIL(ilSource) Dim compilation0 = CreateCompilationWithMscorlib40AndVBRuntime(source, {metadata}, TestOptions.DebugDll) Dim compilation1 = compilation0.Clone() Dim member1 = compilation1.GetMember(Of MethodSymbol)("B.F") Const nModifiers As Integer = 1 Assert.Equal(nModifiers, DirectCast(member1.ReturnType, ArrayTypeSymbol).CustomModifiers.Length) Dim matcher = CreateMatcher(compilation1, compilation0) Dim other = DirectCast(matcher.MapDefinition(DirectCast(member1.GetCciAdapter(), Cci.IMethodDefinition)).GetInternalSymbol(), MethodSymbol) Assert.NotNull(other) Assert.Equal(nModifiers, DirectCast(other.ReturnType, ArrayTypeSymbol).CustomModifiers.Length) End Sub <WorkItem(844472, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/844472")> <Fact()> Public Sub MethodSignatureWithNoPIAType() Dim sourcesPIA = <compilation> <file name="a.vb"><![CDATA[ Imports System Imports System.Runtime.InteropServices <Assembly: ImportedFromTypeLib("_.dll")> <Assembly: Guid("35DB1A6B-D635-4320-A062-28D42920F2A3")> <ComImport()> <Guid("35DB1A6B-D635-4320-A062-28D42920F2A4")> Public Interface I End Interface ]]></file> </compilation> Dim sources0 = <compilation> <file name="a.vb"><![CDATA[ Class C Shared Sub M(x As I) Dim y As I = Nothing M(Nothing) End Sub End Class ]]></file> </compilation> Dim sources1 = <compilation> <file name="a.vb"><![CDATA[ Class C Shared Sub M(x As I) Dim y As I = Nothing M(x) End Sub End Class ]]></file> </compilation> Dim compilationPIA = CreateCompilationWithMscorlib40AndVBRuntime(sourcesPIA) compilationPIA.AssertTheseDiagnostics() Dim referencePIA = compilationPIA.EmitToImageReference(embedInteropTypes:=True) Dim compilation0 = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(sources0, options:=TestOptions.DebugDll, references:={referencePIA}) Dim compilation1 = compilation0.WithSource(sources1) Dim testData0 = New CompilationTestData() Dim bytes0 = compilation0.EmitToArray(testData:=testData0) Dim methodData0 = testData0.GetMethodData("C.M") Using md0 = ModuleMetadata.CreateFromImage(bytes0) Dim generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider) Dim method0 = compilation0.GetMember(Of MethodSymbol)("C.M") Dim method1 = compilation1.GetMember(Of MethodSymbol)("C.M") Dim diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(New SemanticEdit(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables:=True))) diff1.VerifyIL("C.M", <![CDATA[ { // Code size 11 (0xb) .maxstack 1 .locals init ([unchanged] V_0, I V_1) //y IL_0000: nop IL_0001: ldnull IL_0002: stloc.1 IL_0003: ldarg.0 IL_0004: call "Sub C.M(I)" IL_0009: nop IL_000a: ret } ]]>.Value) End Using End Sub ''' <summary> ''' Disallow edits that require NoPIA references. ''' </summary> <Fact()> Public Sub NoPIAReferences() Dim sourcesPIA = <compilation> <file name="a.vb"><![CDATA[ Imports System Imports System.Runtime.InteropServices <Assembly: ImportedFromTypeLib("_.dll")> <Assembly: Guid("35DB1A6B-D635-4320-A062-28D42920F2B3")> <ComImport()> <Guid("35DB1A6B-D635-4320-A062-28D42920F2B4")> Public Interface IA Sub M() ReadOnly Property P As Integer Event E As Action End Interface <ComImport()> <Guid("35DB1A6B-D635-4320-A062-28D42920F2B5")> Public Interface IB End Interface <ComImport()> <Guid("35DB1A6B-D635-4320-A062-28D42920F2B6")> Public Interface IC End Interface Public Structure S Public F As Object End Structure ]]></file> </compilation> Dim sources0 = <compilation> <file name="a.vb"><![CDATA[ Class C(Of T) Shared Private F As Object = GetType(IC) Shared Sub M1() Dim o As IA = Nothing o.M() M2(o.P) AddHandler o.E, AddressOf M1 M2(C(Of IA).F) M2(New S()) End Sub Shared Sub M2(o As Object) End Sub End Class ]]></file> </compilation> Dim sources1A = sources0 Dim sources1B = <compilation> <file name="a.vb"><![CDATA[ Class C(Of T) Shared Private F As Object = GetType(IC) Shared Sub M1() M2(Nothing) End Sub Shared Sub M2(o As Object) End Sub End Class ]]></file> </compilation> Dim compilationPIA = CreateCompilationWithMscorlib40AndVBRuntime(sourcesPIA) compilationPIA.AssertTheseDiagnostics() Dim referencePIA = compilationPIA.EmitToImageReference(embedInteropTypes:=True) Dim compilation0 = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(sources0, options:=TestOptions.DebugDll, references:={referencePIA}) Dim compilation1A = compilation0.WithSource(sources1A) Dim compilation1B = compilation0.WithSource(sources1B) Dim testData0 = New CompilationTestData() Dim bytes0 = compilation0.EmitToArray(testData:=testData0) Dim methodData0 = testData0.GetMethodData("C(Of T).M1") Using md0 = ModuleMetadata.CreateFromImage(bytes0) Dim reader0 = md0.MetadataReader CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "C`1", "IA", "IC", "S") Dim generation0 = EmitBaseline.CreateInitialBaseline(md0, methodData0.EncDebugInfoProvider) Dim method0 = compilation0.GetMember(Of MethodSymbol)("C.M1") ' Disallow edits that require NoPIA references. Dim method1A = compilation1A.GetMember(Of MethodSymbol)("C.M1") Dim diff1A = compilation1A.EmitDifference( generation0, ImmutableArray.Create(New SemanticEdit(SemanticEditKind.Update, method0, method1A, GetEquivalentNodesMap(method1A, method0), preserveLocalVariables:=True))) diff1A.EmitResult.Diagnostics.AssertTheseDiagnostics(<errors><![CDATA[ BC37230: Cannot continue since the edit includes a reference to an embedded type: 'IA'. BC37230: Cannot continue since the edit includes a reference to an embedded type: 'S'. ]]></errors>) ' Allow edits that do not require NoPIA references, Dim method1B = compilation1B.GetMember(Of MethodSymbol)("C.M1") Dim diff1B = compilation1B.EmitDifference( generation0, ImmutableArray.Create(New SemanticEdit(SemanticEditKind.Update, method0, method1B, GetEquivalentNodesMap(method1B, method0), preserveLocalVariables:=True))) diff1B.VerifyIL("C(Of T).M1", <![CDATA[ { // Code size 9 (0x9) .maxstack 1 .locals init ([unchanged] V_0, [unchanged] V_1) IL_0000: nop IL_0001: ldnull IL_0002: call "Sub C(Of T).M2(Object)" IL_0007: nop IL_0008: ret } ]]>.Value) Using md1 = diff1B.GetMetadata() Dim reader1 = md1.Reader CheckNames({reader0, reader1}, reader1.GetTypeDefNames()) End Using End Using End Sub <WorkItem(844536, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/844536")> <Fact()> Public Sub NoPIATypeInNamespace() Dim sourcesPIA = <compilation> <file name="a.vb"><![CDATA[ Imports System Imports System.Runtime.InteropServices <Assembly: ImportedFromTypeLib("_.dll")> <Assembly: Guid("35DB1A6B-D635-4320-A062-28D42920F2A5")> Namespace N <ComImport()> <Guid("35DB1A6B-D635-4320-A062-28D42920F2A6")> Public Interface IA End Interface End Namespace <ComImport()> <Guid("35DB1A6B-D635-4320-A062-28D42920F2A6")> Public Interface IB End Interface ]]></file> </compilation> Dim sources = <compilation> <file name="a.vb"><![CDATA[ Class C(Of T) Shared Sub M(o As Object) M(C(Of N.IA).E.X) M(C(Of IB).E.X) End Sub Enum E X End Enum End Class ]]></file> </compilation> Dim compilationPIA = CreateCompilationWithMscorlib40AndVBRuntime(sourcesPIA) compilationPIA.AssertTheseDiagnostics() Dim referencePIA = AssemblyMetadata.CreateFromImage(compilationPIA.EmitToArray()).GetReference(embedInteropTypes:=True) Dim compilation0 = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(sources, options:=TestOptions.DebugDll, references:={referencePIA}) Dim compilation1 = compilation0.WithSource(sources) Dim bytes0 = compilation0.EmitToArray() Using md0 = ModuleMetadata.CreateFromImage(bytes0) Dim generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider) Dim method0 = compilation0.GetMember(Of MethodSymbol)("C.M") Dim method1 = compilation1.GetMember(Of MethodSymbol)("C.M") Dim diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(New SemanticEdit(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables:=True))) diff1.EmitResult.Diagnostics.AssertTheseDiagnostics(<errors><![CDATA[ BC37230: Cannot continue since the edit includes a reference to an embedded type: 'IA'. BC37230: Cannot continue since the edit includes a reference to an embedded type: 'IB'. ]]></errors>) diff1.VerifyIL("C(Of T).M", <![CDATA[ { // Code size 26 (0x1a) .maxstack 1 IL_0000: nop IL_0001: ldc.i4.0 IL_0002: box "C(Of N.IA).E" IL_0007: call "Sub C(Of T).M(Object)" IL_000c: nop IL_000d: ldc.i4.0 IL_000e: box "C(Of IB).E" IL_0013: call "Sub C(Of T).M(Object)" IL_0018: nop IL_0019: ret } ]]>.Value) End Using End Sub <Fact, WorkItem(1175704, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1175704")> Public Sub EventFields() Dim source0 = MarkedSource(" Imports System Class C Shared Event handler As EventHandler Shared Function F() As Integer RaiseEvent handler(Nothing, Nothing) Return 1 End Function End Class ") Dim source1 = MarkedSource(" Imports System Class C Shared Event handler As EventHandler Shared Function F() As Integer RaiseEvent handler(Nothing, Nothing) Return 10 End Function End Class ") Dim compilation0 = CreateCompilationWithMscorlib40(source0.Tree, options:=ComSafeDebugDll) compilation0.AssertNoDiagnostics() Dim compilation1 = compilation0.WithSource(source1.Tree) Dim f0 = compilation0.GetMember(Of MethodSymbol)("C.F") Dim f1 = compilation1.GetMember(Of MethodSymbol)("C.F") Dim v0 = CompileAndVerify(compilation0) Dim md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData) Dim generation0 = EmitBaseline.CreateInitialBaseline(md0, AddressOf v0.CreateSymReader().GetEncMethodDebugInfo) Dim diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( New SemanticEdit(SemanticEditKind.Update, f0, f1, preserveLocalVariables:=True))) diff1.VerifyIL("C.F", " { // Code size 26 (0x1a) .maxstack 3 .locals init (Integer V_0, //F [unchanged] V_1, System.EventHandler V_2) IL_0000: nop IL_0001: ldsfld ""C.handlerEvent As System.EventHandler"" IL_0006: stloc.2 IL_0007: ldloc.2 IL_0008: brfalse.s IL_0013 IL_000a: ldloc.2 IL_000b: ldnull IL_000c: ldnull IL_000d: callvirt ""Sub System.EventHandler.Invoke(Object, System.EventArgs)"" IL_0012: nop IL_0013: ldc.i4.s 10 IL_0015: stloc.0 IL_0016: br.s IL_0018 IL_0018: ldloc.0 IL_0019: ret } ") End Sub ''' <summary> ''' Should use TypeDef rather than TypeRef for unrecognized ''' local of a type defined in the original assembly. ''' </summary> <WorkItem(910777, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/910777")> <Fact()> Public Sub UnrecognizedLocalOfTypeFromAssembly() Dim source = <compilation> <file name="a.vb"><![CDATA[ Class E Inherits System.Exception End Class Class C Shared Sub M() Try Catch e As E End Try End Sub End Class ]]></file> </compilation> Dim compilation0 = CreateCompilationWithMscorlib40AndVBRuntime(source, options:=TestOptions.DebugDll) Dim compilation1 = compilation0.Clone() Dim bytes0 = compilation0.EmitToArray() Using md0 = ModuleMetadata.CreateFromImage(bytes0) Dim reader0 = md0.MetadataReader CheckNames(reader0, reader0.GetAssemblyRefNames(), "mscorlib", "Microsoft.VisualBasic") Dim method0 = compilation0.GetMember(Of MethodSymbol)("C.M") ' Use empty LocalVariableNameProvider for original locals and ' use preserveLocalVariables: true for the edit so that existing ' locals are retained even though all are unrecognized. Dim generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider) Dim method1 = compilation1.GetMember(Of MethodSymbol)("C.M") Dim diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(New SemanticEdit(SemanticEditKind.Update, method0, method1, syntaxMap:=Function(s) Nothing, preserveLocalVariables:=True))) Using md1 = diff1.GetMetadata() Dim reader1 = md1.Reader Dim readers = {reader0, reader1} CheckNames(readers, reader1.GetAssemblyRefNames(), "mscorlib", "Microsoft.VisualBasic") CheckNames(readers, reader1.GetTypeRefNames(), "Object", "ProjectData", "Exception") CheckEncLog(reader1, Row(3, TableIndex.AssemblyRef, EditAndContinueOperation.Default), Row(4, TableIndex.AssemblyRef, EditAndContinueOperation.Default), Row(8, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(9, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(8, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(9, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(10, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(2, TableIndex.StandAloneSig, EditAndContinueOperation.Default), Row(3, TableIndex.MethodDef, EditAndContinueOperation.Default)) CheckEncMap(reader1, Handle(8, TableIndex.TypeRef), Handle(9, TableIndex.TypeRef), Handle(10, TableIndex.TypeRef), Handle(3, TableIndex.MethodDef), Handle(8, TableIndex.MemberRef), Handle(9, TableIndex.MemberRef), Handle(2, TableIndex.StandAloneSig), Handle(3, TableIndex.AssemblyRef), Handle(4, TableIndex.AssemblyRef)) End Using End Using End Sub <Fact, WorkItem(837315, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/837315")> Public Sub AddingSetAccessor() Dim source0 = <compilation> <file name="a.vb"> Module Module1 Sub Main() System.Console.WriteLine("hello") End Sub Friend name As String Readonly Property GetName Get Return name End Get End Property End Module </file> </compilation> Dim source1 = <compilation> <file name="a.vb"> Module Module1 Sub Main() System.Console.WriteLine("hello") End Sub Friend name As String Property GetName Get Return name End Get Private Set(value) End Set End Property End Module</file> </compilation> Dim compilation0 = CreateCompilationWithMscorlib40AndVBRuntime(source0, TestOptions.DebugDll) Dim compilation1 = compilation0.WithSource(source1) Dim testData0 = New CompilationTestData() Dim bytes0 = compilation0.EmitToArray(testData:=testData0) Using md0 = ModuleMetadata.CreateFromImage(bytes0) Dim reader0 = md0.MetadataReader Dim prop0 = compilation0.GetMember(Of PropertySymbol)("Module1.GetName") Dim prop1 = compilation1.GetMember(Of PropertySymbol)("Module1.GetName") Dim method1 = prop1.SetMethod Dim generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), EmptyLocalsProvider) Dim diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(New SemanticEdit(SemanticEditKind.Insert, Nothing, method1, preserveLocalVariables:=True))) Using md1 = diff1.GetMetadata() Dim reader1 = md1.Reader CheckNames({reader0, reader1}, reader1.GetMethodDefNames(), "set_GetName") End Using diff1.VerifyIL("Module1.set_GetName", " { // Code size 2 (0x2) .maxstack 0 IL_0000: nop IL_0001: ret } ") End Using End Sub <Fact> Public Sub PropertyGetterReturnValueVariable() Dim source0 = <compilation> <file name="a.vb"> Module Module1 ReadOnly Property P Get P = 1 End Get End Property End Module </file> </compilation> Dim source1 = <compilation> <file name="a.vb"> Module Module1 ReadOnly Property P Get P = 2 End Get End Property End Module</file> </compilation> Dim compilation0 = CreateCompilationWithMscorlib40AndVBRuntime(source0, TestOptions.DebugDll) Dim compilation1 = compilation0.WithSource(source1) Dim testData0 = New CompilationTestData() Dim bytes0 = compilation0.EmitToArray(testData:=testData0) Using md0 = ModuleMetadata.CreateFromImage(bytes0) Dim getter0 = compilation0.GetMember(Of PropertySymbol)("Module1.P").GetMethod Dim getter1 = compilation1.GetMember(Of PropertySymbol)("Module1.P").GetMethod Dim generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), testData0.GetMethodData("Module1.get_P").EncDebugInfoProvider) Dim diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(New SemanticEdit(SemanticEditKind.Update, getter0, getter1, preserveLocalVariables:=True))) diff1.VerifyIL("Module1.get_P", " { // Code size 10 (0xa) .maxstack 1 .locals init (Object V_0) //P IL_0000: nop IL_0001: ldc.i4.2 IL_0002: box ""Integer"" IL_0007: stloc.0 IL_0008: ldloc.0 IL_0009: ret }") End Using End Sub #Region "Local Slots" <Fact, WorkItem(828389, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/828389")> Public Sub CatchClause() Dim source0 = <compilation> <file name="a.vb"> Class C Shared Sub M() Try System.Console.WriteLine(1) Catch ex As System.Exception End Try End Sub End Class </file> </compilation> Dim source1 = <compilation> <file name="a.vb"> Class C Shared Sub M() Try System.Console.WriteLine(2) Catch ex As System.Exception End Try End Sub End Class </file> </compilation> Dim compilation0 = CreateCompilationWithMscorlib40AndVBRuntime(source0, TestOptions.DebugDll) Dim compilation1 = compilation0.WithSource(source1) Dim testData0 = New CompilationTestData() Dim bytes0 = compilation0.EmitToArray(testData:=testData0) Dim method0 = compilation0.GetMember(Of MethodSymbol)("C.M") Dim method1 = compilation1.GetMember(Of MethodSymbol)("C.M") Dim generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), testData0.GetMethodData("C.M").EncDebugInfoProvider) Dim diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(New SemanticEdit(SemanticEditKind.Update, method0, method1, preserveLocalVariables:=True))) diff1.VerifyIL("C.M", " { // Code size 28 (0x1c) .maxstack 2 .locals init (System.Exception V_0) //ex IL_0000: nop .try { IL_0001: nop IL_0002: ldc.i4.2 IL_0003: call ""Sub System.Console.WriteLine(Integer)"" IL_0008: nop IL_0009: leave.s IL_001a } catch System.Exception { IL_000b: dup IL_000c: call ""Sub Microsoft.VisualBasic.CompilerServices.ProjectData.SetProjectError(System.Exception)"" IL_0011: stloc.0 IL_0012: nop IL_0013: call ""Sub Microsoft.VisualBasic.CompilerServices.ProjectData.ClearProjectError()"" IL_0018: leave.s IL_001a } IL_001a: nop IL_001b: ret } ") End Sub ''' <summary> ''' Local slots must be preserved based on signature. ''' </summary> <ConditionalFact(GetType(WindowsOnly), Reason:=ConditionalSkipReason.NativePdbRequiresDesktop)> Public Sub PreserveLocalSlots() Dim sources0 = <compilation> <file><![CDATA[ Class A(Of T) End Class Class B Inherits A(Of B) Shared Function F() As B Return Nothing End Function Shared Sub M(o As Object) Dim x As Object = F() Dim y As A(Of B) = F() Dim z As Object = F() M(x) M(y) M(z) End Sub Shared Sub N() Dim a As Object = F() Dim b As Object = F() M(a) M(b) End Sub End Class ]]></file> </compilation> Dim sources1 = <compilation> <file><![CDATA[ Class A(Of T) End Class Class B Inherits A(Of B) Shared Function F() As B Return Nothing End Function Shared Sub M(o As Object) Dim z As B = F() Dim y As A(Of B) = F() Dim w As Object = F() M(w) M(y) End Sub Shared Sub N() Dim a As Object = F() Dim b As Object = F() M(a) M(b) End Sub End Class ]]></file> </compilation> Dim sources2 = <compilation> <file><![CDATA[ Class A(Of T) End Class Class B Inherits A(Of B) Shared Function F() As B Return Nothing End Function Shared Sub M(o As Object) Dim x As Object = F() Dim z As B = F() M(x) M(z) End Sub Shared Sub N() Dim a As Object = F() Dim b As Object = F() M(a) M(b) End Sub End Class ]]></file> </compilation> Dim sources3 = <compilation> <file><![CDATA[ Class A(Of T) End Class Class B Inherits A(Of B) Shared Function F() As B Return Nothing End Function Shared Sub M(o As Object) Dim x As Object = F() Dim z As B = F() M(x) M(z) End Sub Shared Sub N() Dim c As Object = F() Dim b As Object = F() M(c) M(b) End Sub End Class ]]></file> </compilation> Dim compilation0 = CreateCompilationWithMscorlib40(sources0, options:=TestOptions.DebugDll) Dim compilation1 = compilation0.WithSource(sources1) Dim compilation2 = compilation1.WithSource(sources2) Dim compilation3 = compilation2.WithSource(sources3) ' Verify full metadata contains expected rows. Dim testData0 = New CompilationTestData() Dim bytes0 = compilation0.EmitToArray(testData:=testData0) Dim method0 = compilation0.GetMember(Of MethodSymbol)("B.M") Dim method1 = compilation1.GetMember(Of MethodSymbol)("B.M") Dim methodN = compilation0.GetMember(Of MethodSymbol)("B.N") Dim generation0 = EmitBaseline.CreateInitialBaseline( ModuleMetadata.CreateFromImage(bytes0), Function(m) Select Case MetadataTokens.GetRowNumber(m) Case 4 Return testData0.GetMethodData("B.M").GetEncDebugInfo() Case 5 Return testData0.GetMethodData("B.N").GetEncDebugInfo() Case Else Return Nothing End Select End Function) Dim diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(New SemanticEdit(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables:=True))) diff1.VerifyIL(" { // Code size 41 (0x29) .maxstack 1 IL_0000: nop IL_0001: call 0x06000003 IL_0006: stloc.3 IL_0007: call 0x06000003 IL_000c: stloc.1 IL_000d: call 0x06000003 IL_0012: stloc.s V_4 IL_0014: ldloc.s V_4 IL_0016: call 0x0A000007 IL_001b: call 0x06000004 IL_0020: nop IL_0021: ldloc.1 IL_0022: call 0x06000004 IL_0027: nop IL_0028: ret } ") diff1.VerifyPdb({&H06000001UI, &H06000002UI, &H06000003UI, &H06000004UI, &H06000005UI}, <symbols> <files> <file id="1" name="" language="VB"/> </files> <methods> <method token="0x6000004"> <sequencePoints> <entry offset="0x0" startLine="8" startColumn="5" endLine="8" endColumn="30" document="1"/> <entry offset="0x1" startLine="9" startColumn="13" endLine="9" endColumn="25" document="1"/> <entry offset="0x7" startLine="10" startColumn="13" endLine="10" endColumn="31" document="1"/> <entry offset="0xd" startLine="11" startColumn="13" endLine="11" endColumn="30" document="1"/> <entry offset="0x14" startLine="12" startColumn="9" endLine="12" endColumn="13" document="1"/> <entry offset="0x21" startLine="13" startColumn="9" endLine="13" endColumn="13" document="1"/> <entry offset="0x28" startLine="14" startColumn="5" endLine="14" endColumn="12" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x29"> <currentnamespace name=""/> <local name="z" il_index="3" il_start="0x0" il_end="0x29" attributes="0"/> <local name="y" il_index="1" il_start="0x0" il_end="0x29" attributes="0"/> <local name="w" il_index="4" il_start="0x0" il_end="0x29" attributes="0"/> </scope> </method> </methods> </symbols>) Dim method2 = compilation2.GlobalNamespace.GetMember(Of NamedTypeSymbol)("B").GetMember(Of MethodSymbol)("M") Dim diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create(New SemanticEdit(SemanticEditKind.Update, method1, method2, GetEquivalentNodesMap(method2, method1), preserveLocalVariables:=True))) diff2.VerifyIL(" { // Code size 35 (0x23) .maxstack 1 IL_0000: nop IL_0001: call 0x06000003 IL_0006: stloc.s V_5 IL_0008: call 0x06000003 IL_000d: stloc.3 IL_000e: ldloc.s V_5 IL_0010: call 0x0A000008 IL_0015: call 0x06000004 IL_001a: nop IL_001b: ldloc.3 IL_001c: call 0x06000004 IL_0021: nop IL_0022: ret } ") diff2.VerifyPdb({&H06000001UI, &H06000002UI, &H06000003UI, &H06000004UI, &H06000005UI}, <symbols> <files> <file id="1" name="" language="VB"/> </files> <methods> <method token="0x6000004"> <sequencePoints> <entry offset="0x0" startLine="8" startColumn="5" endLine="8" endColumn="30" document="1"/> <entry offset="0x1" startLine="9" startColumn="13" endLine="9" endColumn="30" document="1"/> <entry offset="0x8" startLine="10" startColumn="13" endLine="10" endColumn="25" document="1"/> <entry offset="0xe" startLine="11" startColumn="9" endLine="11" endColumn="13" document="1"/> <entry offset="0x1b" startLine="12" startColumn="9" endLine="12" endColumn="13" document="1"/> <entry offset="0x22" startLine="13" startColumn="5" endLine="13" endColumn="12" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x23"> <currentnamespace name=""/> <local name="x" il_index="5" il_start="0x0" il_end="0x23" attributes="0"/> <local name="z" il_index="3" il_start="0x0" il_end="0x23" attributes="0"/> </scope> </method> </methods> </symbols>) ' Modify different method. (Previous generations ' have not referenced method.) method2 = compilation2.GlobalNamespace.GetMember(Of NamedTypeSymbol)("B").GetMember(Of MethodSymbol)("N") Dim method3 = compilation3.GlobalNamespace.GetMember(Of NamedTypeSymbol)("B").GetMember(Of MethodSymbol)("N") Dim metadata3 As ImmutableArray(Of Byte) = Nothing Dim il3 As ImmutableArray(Of Byte) = Nothing Dim pdb3 As Stream = Nothing Dim diff3 = compilation3.EmitDifference( diff2.NextGeneration, ImmutableArray.Create(New SemanticEdit(SemanticEditKind.Update, method2, method3, GetEquivalentNodesMap(method3, method2), preserveLocalVariables:=True))) diff3.VerifyIL(" { // Code size 38 (0x26) .maxstack 1 IL_0000: nop IL_0001: call 0x06000003 IL_0006: stloc.2 IL_0007: call 0x06000003 IL_000c: stloc.1 IL_000d: ldloc.2 IL_000e: call 0x0A000009 IL_0013: call 0x06000004 IL_0018: nop IL_0019: ldloc.1 IL_001a: call 0x0A000009 IL_001f: call 0x06000004 IL_0024: nop IL_0025: ret } ") diff3.VerifyPdb({&H06000001UI, &H06000002UI, &H06000003UI, &H06000004UI, &H06000005UI}, <symbols> <files> <file id="1" name="" language="VB"/> </files> <methods> <method token="0x6000005"> <sequencePoints> <entry offset="0x0" startLine="14" startColumn="5" endLine="14" endColumn="19" document="1"/> <entry offset="0x1" startLine="15" startColumn="13" endLine="15" endColumn="30" document="1"/> <entry offset="0x7" startLine="16" startColumn="13" endLine="16" endColumn="30" document="1"/> <entry offset="0xd" startLine="17" startColumn="9" endLine="17" endColumn="13" document="1"/> <entry offset="0x19" startLine="18" startColumn="9" endLine="18" endColumn="13" document="1"/> <entry offset="0x25" startLine="19" startColumn="5" endLine="19" endColumn="12" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x26"> <currentnamespace name=""/> <local name="c" il_index="2" il_start="0x0" il_end="0x26" attributes="0"/> <local name="b" il_index="1" il_start="0x0" il_end="0x26" attributes="0"/> </scope> </method> </methods> </symbols>) End Sub ''' <summary> ''' Preserve locals for method added after initial compilation. ''' </summary> <ConditionalFact(GetType(WindowsOnly), Reason:=ConditionalSkipReason.NativePdbRequiresDesktop)> Public Sub PreserveLocalSlots_NewMethod() Dim sources0 = <compilation> <file><![CDATA[ Class C End Class ]]></file> </compilation> Dim sources1 = <compilation> <file><![CDATA[ Class C Shared Sub M() Dim a = New Object() Dim b = String.Empty End Sub End Class ]]></file> </compilation> Dim sources2 = <compilation> <file><![CDATA[ Class C Shared Sub M() Dim a = 1 Dim b = String.Empty End Sub End Class ]]></file> </compilation> Dim compilation0 = CreateCompilationWithMscorlib40(sources0, options:=TestOptions.DebugDll) Dim compilation1 = compilation0.WithSource(sources1) Dim compilation2 = compilation1.WithSource(sources2) Dim bytes0 = compilation0.EmitToArray() Dim generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), EmptyLocalsProvider) Dim method1 = compilation1.GetMember(Of MethodSymbol)("C.M") Dim diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(New SemanticEdit(SemanticEditKind.Insert, Nothing, method1, Nothing, preserveLocalVariables:=True))) Dim method2 = compilation2.GetMember(Of MethodSymbol)("C.M") Dim diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create(New SemanticEdit(SemanticEditKind.Update, method1, method2, GetEquivalentNodesMap(method2, method1), preserveLocalVariables:=True))) diff2.VerifyIL("C.M", <![CDATA[ { // Code size 10 (0xa) .maxstack 1 .locals init ([object] V_0, String V_1, //b Integer V_2) //a IL_0000: nop IL_0001: ldc.i4.1 IL_0002: stloc.2 IL_0003: ldsfld "String.Empty As String" IL_0008: stloc.1 IL_0009: ret } ]]>.Value) diff2.VerifyPdb({&H06000002UI}, <symbols> <files> <file id="1" name="" language="VB"/> </files> <methods> <method token="0x6000002"> <sequencePoints> <entry offset="0x0" startLine="2" startColumn="5" endLine="2" endColumn="19" document="1"/> <entry offset="0x1" startLine="3" startColumn="13" endLine="3" endColumn="18" document="1"/> <entry offset="0x3" startLine="4" startColumn="13" endLine="4" endColumn="29" document="1"/> <entry offset="0x9" startLine="5" startColumn="5" endLine="5" endColumn="12" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0xa"> <currentnamespace name=""/> <local name="a" il_index="2" il_start="0x0" il_end="0xa" attributes="0"/> <local name="b" il_index="1" il_start="0x0" il_end="0xa" attributes="0"/> </scope> </method> </methods> </symbols>) End Sub ''' <summary> ''' Local types should be retained, even if the local is no longer ''' used by the method body, since there may be existing ''' references to that slot, in a Watch window for instance. ''' </summary> <WorkItem(843320, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/843320")> <Fact> Public Sub PreserveLocalTypes() Dim sources0 = <compilation> <file><![CDATA[ Class C Shared Sub Main() Dim x = True Dim y = x System.Console.WriteLine(y) End Sub End Class ]]></file> </compilation> Dim sources1 = <compilation> <file><![CDATA[ Class C Shared Sub Main() Dim x = "A" Dim y = x System.Console.WriteLine(y) End Sub End Class ]]></file> </compilation> Dim compilation0 = CreateCompilationWithMscorlib40(sources0, options:=TestOptions.DebugDll) Dim compilation1 = compilation0.WithSource(sources1) Dim testData0 = New CompilationTestData() Dim bytes0 = compilation0.EmitToArray(testData:=testData0) Dim method0 = compilation0.GetMember(Of MethodSymbol)("C.Main") Dim method1 = compilation1.GetMember(Of MethodSymbol)("C.Main") Dim generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), testData0.GetMethodData("C.Main").EncDebugInfoProvider) Dim diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(New SemanticEdit(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables:=True))) diff1.VerifyIL("C.Main", " { // Code size 17 (0x11) .maxstack 1 .locals init ([bool] V_0, [bool] V_1, String V_2, //x String V_3) //y IL_0000: nop IL_0001: ldstr ""A"" IL_0006: stloc.2 IL_0007: ldloc.2 IL_0008: stloc.3 IL_0009: ldloc.3 IL_000a: call ""Sub System.Console.WriteLine(String)"" IL_000f: nop IL_0010: ret }") End Sub ''' <summary> ''' Local slots must be preserved based on signature. ''' </summary> <Fact> Public Sub PreserveLocalSlotsReferences() Dim sources0 = <compilation> <file><![CDATA[ Class A(Of T) End Class Class C Inherits A(Of C) Shared Function F() As C Return Nothing End Function Shared Sub M(o As Object) dim x = new system.collections.generic.stack(of Integer) x.Push(1) End Sub End Class ]]></file> </compilation> Dim compilation0 = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(sources0, XmlReferences, TestOptions.DebugDll) Dim compilation1 = compilation0.Clone() Dim testData0 = New CompilationTestData() Dim bytes0 = compilation0.EmitToArray(testData:=testData0) testData0.GetMethodData("C.M").VerifyIL(" { // Code size 16 (0x10) .maxstack 2 .locals init (System.Collections.Generic.Stack(Of Integer) V_0) //x IL_0000: nop IL_0001: newobj ""Sub System.Collections.Generic.Stack(Of Integer)..ctor()"" IL_0006: stloc.0 IL_0007: ldloc.0 IL_0008: ldc.i4.1 IL_0009: callvirt ""Sub System.Collections.Generic.Stack(Of Integer).Push(Integer)"" IL_000e: nop IL_000f: ret } ") Dim method0 = compilation0.GetMember(Of MethodSymbol)("C.M") Dim method1 = compilation1.GetMember(Of MethodSymbol)("C.M") Dim modMeta = ModuleMetadata.CreateFromImage(bytes0) Dim generation0 = EmitBaseline.CreateInitialBaseline(modMeta, testData0.GetMethodData("C.M").EncDebugInfoProvider) Dim diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(New SemanticEdit(SemanticEditKind.Update, method0, method1, preserveLocalVariables:=True))) diff1.VerifyIL("C.M", <![CDATA[ { // Code size 16 (0x10) .maxstack 2 .locals init (System.Collections.Generic.Stack(Of Integer) V_0) //x IL_0000: nop IL_0001: newobj "Sub System.Collections.Generic.Stack(Of Integer)..ctor()" IL_0006: stloc.0 IL_0007: ldloc.0 IL_0008: ldc.i4.1 IL_0009: callvirt "Sub System.Collections.Generic.Stack(Of Integer).Push(Integer)" IL_000e: nop IL_000f: ret } ]]>.Value) End Sub ''' <summary> ''' Local slots must be preserved based on signature. ''' </summary> <Fact> Public Sub PreserveLocalSlotsUsing() Dim sources0 = <compilation> <file><![CDATA[ Class A(Of T) End Class Class C Inherits A(Of C) Shared Function F() As C Return Nothing End Function Shared Sub M(o As Object) dim x as System.IDisposable = nothing Using x end using End Sub End Class ]]></file> </compilation> Dim compilation0 = CreateCompilationWithMscorlib40(sources0, options:=TestOptions.DebugDll) Dim compilation1 = compilation0.Clone() Dim testData0 = New CompilationTestData() Dim bytes0 = compilation0.EmitToArray(testData:=testData0) testData0.GetMethodData("C.M").VerifyIL(" { // Code size 21 (0x15) .maxstack 1 .locals init (System.IDisposable V_0, //x System.IDisposable V_1) IL_0000: nop IL_0001: ldnull IL_0002: stloc.0 IL_0003: nop IL_0004: ldloc.0 IL_0005: stloc.1 .try { IL_0006: leave.s IL_0014 } finally { IL_0008: nop IL_0009: ldloc.1 IL_000a: brfalse.s IL_0013 IL_000c: ldloc.1 IL_000d: callvirt ""Sub System.IDisposable.Dispose()"" IL_0012: nop IL_0013: endfinally } IL_0014: ret } ") Dim method0 = compilation0.GetMember(Of MethodSymbol)("C.M") Dim method1 = compilation1.GetMember(Of MethodSymbol)("C.M") Dim generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), testData0.GetMethodData("C.M").EncDebugInfoProvider) Dim diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(New SemanticEdit(SemanticEditKind.Update, method0, method1, preserveLocalVariables:=True))) diff1.VerifyIL("C.M", " { // Code size 21 (0x15) .maxstack 1 .locals init (System.IDisposable V_0, //x System.IDisposable V_1) IL_0000: nop IL_0001: ldnull IL_0002: stloc.0 IL_0003: nop IL_0004: ldloc.0 IL_0005: stloc.1 .try { IL_0006: leave.s IL_0014 } finally { IL_0008: nop IL_0009: ldloc.1 IL_000a: brfalse.s IL_0013 IL_000c: ldloc.1 IL_000d: callvirt ""Sub System.IDisposable.Dispose()"" IL_0012: nop IL_0013: endfinally } IL_0014: ret } ") End Sub ''' <summary> ''' Local slots must be preserved based on signature. ''' </summary> <Fact> Public Sub PreserveLocalSlotsWithByRef() Dim sources0 = <compilation> <file><![CDATA[ Class A(Of T) End Class Class C Inherits A(Of C) Shared Function F() As C Return Nothing End Function Shared Sub M(o As Object) dim x as System.Guid() = nothing With x(3) .ToString() end With End Sub End Class ]]></file> </compilation> Dim compilation0 = CreateCompilationWithMscorlib40(sources0, options:=TestOptions.DebugDll) Dim compilation1 = compilation0.Clone() Dim testData0 = New CompilationTestData() Dim bytes0 = compilation0.EmitToArray(testData:=testData0) testData0.GetMethodData("C.M").VerifyIL(" { // Code size 27 (0x1b) .maxstack 2 .locals init (System.Guid() V_0, //x System.Guid& V_1) //$W0 IL_0000: nop IL_0001: ldnull IL_0002: stloc.0 IL_0003: nop IL_0004: ldloc.0 IL_0005: ldc.i4.3 IL_0006: ldelema ""System.Guid"" IL_000b: stloc.1 IL_000c: ldloc.1 IL_000d: constrained. ""System.Guid"" IL_0013: callvirt ""Function Object.ToString() As String"" IL_0018: pop IL_0019: nop IL_001a: ret } ") Dim method0 = compilation0.GetMember(Of MethodSymbol)("C.M") Dim method1 = compilation1.GetMember(Of MethodSymbol)("C.M") Dim generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), testData0.GetMethodData("C.M").EncDebugInfoProvider) Dim diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(New SemanticEdit(SemanticEditKind.Update, method0, method1, preserveLocalVariables:=True))) diff1.VerifyIL("C.M", " { // Code size 27 (0x1b) .maxstack 2 .locals init (System.Guid() V_0, //x System.Guid& V_1) //$W0 IL_0000: nop IL_0001: ldnull IL_0002: stloc.0 IL_0003: nop IL_0004: ldloc.0 IL_0005: ldc.i4.3 IL_0006: ldelema ""System.Guid"" IL_000b: stloc.1 IL_000c: ldloc.1 IL_000d: constrained. ""System.Guid"" IL_0013: callvirt ""Function Object.ToString() As String"" IL_0018: pop IL_0019: nop IL_001a: ret } ") End Sub ''' <summary> ''' Local slots must be preserved based on signature. ''' </summary> <Fact> Public Sub PreserveLocalSlotsWithByVal() Dim sources0 = <compilation> <file name="a.vb"><![CDATA[ Class A(Of T) End Class Class C Inherits A(Of C) Shared Function F() As C Return Nothing End Function Shared Sub M(o As Object) dim x as System.Guid() = nothing With x .ToString() end With End Sub End Class ]]></file> </compilation> Dim compilation0 = CreateCompilationWithMscorlib40(sources0, options:=TestOptions.DebugDll) Dim compilation1 = compilation0.Clone() Dim testData0 = New CompilationTestData() Dim bytes0 = compilation0.EmitToArray(testData:=testData0) testData0.GetMethodData("C.M").VerifyIL(" { // Code size 17 (0x11) .maxstack 1 .locals init (System.Guid() V_0, //x System.Guid() V_1) //$W0 IL_0000: nop IL_0001: ldnull IL_0002: stloc.0 IL_0003: nop IL_0004: ldloc.0 IL_0005: stloc.1 IL_0006: ldloc.1 IL_0007: callvirt ""Function Object.ToString() As String"" IL_000c: pop IL_000d: nop IL_000e: ldnull IL_000f: stloc.1 IL_0010: ret } ") Dim method0 = compilation0.GetMember(Of MethodSymbol)("C.M") Dim method1 = compilation1.GetMember(Of MethodSymbol)("C.M") Dim generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), testData0.GetMethodData("C.M").EncDebugInfoProvider) Dim diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(New SemanticEdit(SemanticEditKind.Update, method0, method1, preserveLocalVariables:=True))) diff1.VerifyIL("C.M", " { // Code size 17 (0x11) .maxstack 1 .locals init (System.Guid() V_0, //x System.Guid() V_1) //$W0 IL_0000: nop IL_0001: ldnull IL_0002: stloc.0 IL_0003: nop IL_0004: ldloc.0 IL_0005: stloc.1 IL_0006: ldloc.1 IL_0007: callvirt ""Function Object.ToString() As String"" IL_000c: pop IL_000d: nop IL_000e: ldnull IL_000f: stloc.1 IL_0010: ret } ") End Sub ''' <summary> ''' Local slots must be preserved based on signature. ''' </summary> <Fact> Public Sub PreserveLocalSlotsSyncLock() Dim sources0 = <compilation> <file name="a.vb"><![CDATA[ Class A(Of T) End Class Class C Inherits A(Of C) Shared Function F() As C Return Nothing End Function Shared Sub M(o As Object) dim x as System.Guid() = nothing SyncLock x dim y as System.Guid() = nothing SyncLock y x.ToString() end SyncLock end SyncLock End Sub End Class ]]></file> </compilation> Dim compilation0 = CreateCompilationWithMscorlib40(sources0, options:=TestOptions.DebugDll) Dim compilation1 = compilation0.Clone() Dim testData0 = New CompilationTestData() Dim bytes0 = compilation0.EmitToArray(testData:=testData0) testData0.GetMethodData("C.M").VerifyIL(" { // Code size 76 (0x4c) .maxstack 2 .locals init (System.Guid() V_0, //x Object V_1, Boolean V_2, System.Guid() V_3, //y Object V_4, Boolean V_5) IL_0000: nop IL_0001: ldnull IL_0002: stloc.0 IL_0003: nop IL_0004: ldloc.0 IL_0005: stloc.1 IL_0006: ldc.i4.0 IL_0007: stloc.2 .try { IL_0008: ldloc.1 IL_0009: ldloca.s V_2 IL_000b: call ""Sub System.Threading.Monitor.Enter(Object, ByRef Boolean)"" IL_0010: nop IL_0011: ldnull IL_0012: stloc.3 IL_0013: nop IL_0014: ldloc.3 IL_0015: stloc.s V_4 IL_0017: ldc.i4.0 IL_0018: stloc.s V_5 .try { IL_001a: ldloc.s V_4 IL_001c: ldloca.s V_5 IL_001e: call ""Sub System.Threading.Monitor.Enter(Object, ByRef Boolean)"" IL_0023: nop IL_0024: ldloc.0 IL_0025: callvirt ""Function Object.ToString() As String"" IL_002a: pop IL_002b: leave.s IL_003b } finally { IL_002d: ldloc.s V_5 IL_002f: brfalse.s IL_0039 IL_0031: ldloc.s V_4 IL_0033: call ""Sub System.Threading.Monitor.Exit(Object)"" IL_0038: nop IL_0039: nop IL_003a: endfinally } IL_003b: nop IL_003c: leave.s IL_004a } finally { IL_003e: ldloc.2 IL_003f: brfalse.s IL_0048 IL_0041: ldloc.1 IL_0042: call ""Sub System.Threading.Monitor.Exit(Object)"" IL_0047: nop IL_0048: nop IL_0049: endfinally } IL_004a: nop IL_004b: ret } ") Dim method0 = compilation0.GetMember(Of MethodSymbol)("C.M") Dim method1 = compilation1.GetMember(Of MethodSymbol)("C.M") Dim generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), testData0.GetMethodData("C.M").EncDebugInfoProvider) Dim diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(New SemanticEdit(SemanticEditKind.Update, method0, method1, preserveLocalVariables:=True))) diff1.VerifyIL("C.M", " { // Code size 76 (0x4c) .maxstack 2 .locals init (System.Guid() V_0, //x Object V_1, Boolean V_2, System.Guid() V_3, //y Object V_4, Boolean V_5) IL_0000: nop IL_0001: ldnull IL_0002: stloc.0 IL_0003: nop IL_0004: ldloc.0 IL_0005: stloc.1 IL_0006: ldc.i4.0 IL_0007: stloc.2 .try { IL_0008: ldloc.1 IL_0009: ldloca.s V_2 IL_000b: call ""Sub System.Threading.Monitor.Enter(Object, ByRef Boolean)"" IL_0010: nop IL_0011: ldnull IL_0012: stloc.3 IL_0013: nop IL_0014: ldloc.3 IL_0015: stloc.s V_4 IL_0017: ldc.i4.0 IL_0018: stloc.s V_5 .try { IL_001a: ldloc.s V_4 IL_001c: ldloca.s V_5 IL_001e: call ""Sub System.Threading.Monitor.Enter(Object, ByRef Boolean)"" IL_0023: nop IL_0024: ldloc.0 IL_0025: callvirt ""Function Object.ToString() As String"" IL_002a: pop IL_002b: leave.s IL_003b } finally { IL_002d: ldloc.s V_5 IL_002f: brfalse.s IL_0039 IL_0031: ldloc.s V_4 IL_0033: call ""Sub System.Threading.Monitor.Exit(Object)"" IL_0038: nop IL_0039: nop IL_003a: endfinally } IL_003b: nop IL_003c: leave.s IL_004a } finally { IL_003e: ldloc.2 IL_003f: brfalse.s IL_0048 IL_0041: ldloc.1 IL_0042: call ""Sub System.Threading.Monitor.Exit(Object)"" IL_0047: nop IL_0048: nop IL_0049: endfinally } IL_004a: nop IL_004b: ret } ") End Sub ''' <summary> ''' Local slots must be preserved based on signature. ''' </summary> <Fact> Public Sub PreserveLocalSlotsForEach() Dim sources0 = <compilation> <file name="a.vb"><![CDATA[ Class A(Of T) End Class Class C Inherits A(Of C) Shared Function F() As C Return Nothing End Function Shared Sub M(o As Object) dim x as System.Collections.Generic.List(of integer) = nothing for each [i] in [x] Next for each i as integer in x Next End Sub End Class ]]></file> </compilation> Dim compilation0 = CreateCompilationWithMscorlib40(sources0, options:=TestOptions.DebugDll) Dim compilation1 = compilation0.Clone() Dim testData0 = New CompilationTestData() Dim bytes0 = compilation0.EmitToArray(testData:=testData0) testData0.GetMethodData("C.M").VerifyIL(" { // Code size 101 (0x65) .maxstack 1 .locals init (System.Collections.Generic.List(Of Integer) V_0, //x System.Collections.Generic.List(Of Integer).Enumerator V_1, Integer V_2, //i Boolean V_3, System.Collections.Generic.List(Of Integer).Enumerator V_4, Integer V_5, //i Boolean V_6) IL_0000: nop IL_0001: ldnull IL_0002: stloc.0 .try { IL_0003: ldloc.0 IL_0004: callvirt ""Function System.Collections.Generic.List(Of Integer).GetEnumerator() As System.Collections.Generic.List(Of Integer).Enumerator"" IL_0009: stloc.1 IL_000a: br.s IL_0015 IL_000c: ldloca.s V_1 IL_000e: call ""Function System.Collections.Generic.List(Of Integer).Enumerator.get_Current() As Integer"" IL_0013: stloc.2 IL_0014: nop IL_0015: ldloca.s V_1 IL_0017: call ""Function System.Collections.Generic.List(Of Integer).Enumerator.MoveNext() As Boolean"" IL_001c: stloc.3 IL_001d: ldloc.3 IL_001e: brtrue.s IL_000c IL_0020: leave.s IL_0031 } finally { IL_0022: ldloca.s V_1 IL_0024: constrained. ""System.Collections.Generic.List(Of Integer).Enumerator"" IL_002a: callvirt ""Sub System.IDisposable.Dispose()"" IL_002f: nop IL_0030: endfinally } IL_0031: nop .try { IL_0032: ldloc.0 IL_0033: callvirt ""Function System.Collections.Generic.List(Of Integer).GetEnumerator() As System.Collections.Generic.List(Of Integer).Enumerator"" IL_0038: stloc.s V_4 IL_003a: br.s IL_0046 IL_003c: ldloca.s V_4 IL_003e: call ""Function System.Collections.Generic.List(Of Integer).Enumerator.get_Current() As Integer"" IL_0043: stloc.s V_5 IL_0045: nop IL_0046: ldloca.s V_4 IL_0048: call ""Function System.Collections.Generic.List(Of Integer).Enumerator.MoveNext() As Boolean"" IL_004d: stloc.s V_6 IL_004f: ldloc.s V_6 IL_0051: brtrue.s IL_003c IL_0053: leave.s IL_0064 } finally { IL_0055: ldloca.s V_4 IL_0057: constrained. ""System.Collections.Generic.List(Of Integer).Enumerator"" IL_005d: callvirt ""Sub System.IDisposable.Dispose()"" IL_0062: nop IL_0063: endfinally } IL_0064: ret } ") Dim method0 = compilation0.GetMember(Of MethodSymbol)("C.M") Dim method1 = compilation1.GetMember(Of MethodSymbol)("C.M") Dim generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), testData0.GetMethodData("C.M").EncDebugInfoProvider) Dim diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(New SemanticEdit(SemanticEditKind.Update, method0, method1, preserveLocalVariables:=True))) diff1.VerifyIL("C.M", " { // Code size 101 (0x65) .maxstack 1 .locals init (System.Collections.Generic.List(Of Integer) V_0, //x System.Collections.Generic.List(Of Integer).Enumerator V_1, Integer V_2, //i Boolean V_3, System.Collections.Generic.List(Of Integer).Enumerator V_4, Integer V_5, //i Boolean V_6) IL_0000: nop IL_0001: ldnull IL_0002: stloc.0 .try { IL_0003: ldloc.0 IL_0004: callvirt ""Function System.Collections.Generic.List(Of Integer).GetEnumerator() As System.Collections.Generic.List(Of Integer).Enumerator"" IL_0009: stloc.1 IL_000a: br.s IL_0015 IL_000c: ldloca.s V_1 IL_000e: call ""Function System.Collections.Generic.List(Of Integer).Enumerator.get_Current() As Integer"" IL_0013: stloc.2 IL_0014: nop IL_0015: ldloca.s V_1 IL_0017: call ""Function System.Collections.Generic.List(Of Integer).Enumerator.MoveNext() As Boolean"" IL_001c: stloc.3 IL_001d: ldloc.3 IL_001e: brtrue.s IL_000c IL_0020: leave.s IL_0031 } finally { IL_0022: ldloca.s V_1 IL_0024: constrained. ""System.Collections.Generic.List(Of Integer).Enumerator"" IL_002a: callvirt ""Sub System.IDisposable.Dispose()"" IL_002f: nop IL_0030: endfinally } IL_0031: nop .try { IL_0032: ldloc.0 IL_0033: callvirt ""Function System.Collections.Generic.List(Of Integer).GetEnumerator() As System.Collections.Generic.List(Of Integer).Enumerator"" IL_0038: stloc.s V_4 IL_003a: br.s IL_0046 IL_003c: ldloca.s V_4 IL_003e: call ""Function System.Collections.Generic.List(Of Integer).Enumerator.get_Current() As Integer"" IL_0043: stloc.s V_5 IL_0045: nop IL_0046: ldloca.s V_4 IL_0048: call ""Function System.Collections.Generic.List(Of Integer).Enumerator.MoveNext() As Boolean"" IL_004d: stloc.s V_6 IL_004f: ldloc.s V_6 IL_0051: brtrue.s IL_003c IL_0053: leave.s IL_0064 } finally { IL_0055: ldloca.s V_4 IL_0057: constrained. ""System.Collections.Generic.List(Of Integer).Enumerator"" IL_005d: callvirt ""Sub System.IDisposable.Dispose()"" IL_0062: nop IL_0063: endfinally } IL_0064: ret } ") End Sub ''' <summary> ''' Local slots must be preserved based on signature. ''' </summary> <Fact> Public Sub PreserveLocalSlotsForEach001() Dim sources0 = <compilation> <file name="a.vb"><![CDATA[ Class A(Of T) End Class Class C Inherits A(Of C) Shared Function F() As C Return Nothing End Function Shared Sub M(o As Object) dim x as System.Collections.Generic.List(of integer) = nothing Dim i as integer for each i in x Next for each i in x Next End Sub End Class ]]></file> </compilation> Dim compilation0 = CreateCompilationWithMscorlib40(sources0, options:=TestOptions.DebugDll) Dim compilation1 = compilation0.Clone() Dim testData0 = New CompilationTestData() Dim bytes0 = compilation0.EmitToArray(testData:=testData0) testData0.GetMethodData("C.M").VerifyIL(" { // Code size 100 (0x64) .maxstack 1 .locals init (System.Collections.Generic.List(Of Integer) V_0, //x Integer V_1, //i System.Collections.Generic.List(Of Integer).Enumerator V_2, Boolean V_3, System.Collections.Generic.List(Of Integer).Enumerator V_4, Boolean V_5) IL_0000: nop IL_0001: ldnull IL_0002: stloc.0 .try { IL_0003: ldloc.0 IL_0004: callvirt ""Function System.Collections.Generic.List(Of Integer).GetEnumerator() As System.Collections.Generic.List(Of Integer).Enumerator"" IL_0009: stloc.2 IL_000a: br.s IL_0015 IL_000c: ldloca.s V_2 IL_000e: call ""Function System.Collections.Generic.List(Of Integer).Enumerator.get_Current() As Integer"" IL_0013: stloc.1 IL_0014: nop IL_0015: ldloca.s V_2 IL_0017: call ""Function System.Collections.Generic.List(Of Integer).Enumerator.MoveNext() As Boolean"" IL_001c: stloc.3 IL_001d: ldloc.3 IL_001e: brtrue.s IL_000c IL_0020: leave.s IL_0031 } finally { IL_0022: ldloca.s V_2 IL_0024: constrained. ""System.Collections.Generic.List(Of Integer).Enumerator"" IL_002a: callvirt ""Sub System.IDisposable.Dispose()"" IL_002f: nop IL_0030: endfinally } IL_0031: nop .try { IL_0032: ldloc.0 IL_0033: callvirt ""Function System.Collections.Generic.List(Of Integer).GetEnumerator() As System.Collections.Generic.List(Of Integer).Enumerator"" IL_0038: stloc.s V_4 IL_003a: br.s IL_0045 IL_003c: ldloca.s V_4 IL_003e: call ""Function System.Collections.Generic.List(Of Integer).Enumerator.get_Current() As Integer"" IL_0043: stloc.1 IL_0044: nop IL_0045: ldloca.s V_4 IL_0047: call ""Function System.Collections.Generic.List(Of Integer).Enumerator.MoveNext() As Boolean"" IL_004c: stloc.s V_5 IL_004e: ldloc.s V_5 IL_0050: brtrue.s IL_003c IL_0052: leave.s IL_0063 } finally { IL_0054: ldloca.s V_4 IL_0056: constrained. ""System.Collections.Generic.List(Of Integer).Enumerator"" IL_005c: callvirt ""Sub System.IDisposable.Dispose()"" IL_0061: nop IL_0062: endfinally } IL_0063: ret } ") Dim method0 = compilation0.GetMember(Of MethodSymbol)("C.M") Dim method1 = compilation1.GetMember(Of MethodSymbol)("C.M") Dim generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), testData0.GetMethodData("C.M").EncDebugInfoProvider) Dim diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(New SemanticEdit(SemanticEditKind.Update, method0, method1, preserveLocalVariables:=True))) diff1.VerifyIL("C.M", " { // Code size 100 (0x64) .maxstack 1 .locals init (System.Collections.Generic.List(Of Integer) V_0, //x Integer V_1, //i System.Collections.Generic.List(Of Integer).Enumerator V_2, Boolean V_3, System.Collections.Generic.List(Of Integer).Enumerator V_4, Boolean V_5) IL_0000: nop IL_0001: ldnull IL_0002: stloc.0 .try { IL_0003: ldloc.0 IL_0004: callvirt ""Function System.Collections.Generic.List(Of Integer).GetEnumerator() As System.Collections.Generic.List(Of Integer).Enumerator"" IL_0009: stloc.2 IL_000a: br.s IL_0015 IL_000c: ldloca.s V_2 IL_000e: call ""Function System.Collections.Generic.List(Of Integer).Enumerator.get_Current() As Integer"" IL_0013: stloc.1 IL_0014: nop IL_0015: ldloca.s V_2 IL_0017: call ""Function System.Collections.Generic.List(Of Integer).Enumerator.MoveNext() As Boolean"" IL_001c: stloc.3 IL_001d: ldloc.3 IL_001e: brtrue.s IL_000c IL_0020: leave.s IL_0031 } finally { IL_0022: ldloca.s V_2 IL_0024: constrained. ""System.Collections.Generic.List(Of Integer).Enumerator"" IL_002a: callvirt ""Sub System.IDisposable.Dispose()"" IL_002f: nop IL_0030: endfinally } IL_0031: nop .try { IL_0032: ldloc.0 IL_0033: callvirt ""Function System.Collections.Generic.List(Of Integer).GetEnumerator() As System.Collections.Generic.List(Of Integer).Enumerator"" IL_0038: stloc.s V_4 IL_003a: br.s IL_0045 IL_003c: ldloca.s V_4 IL_003e: call ""Function System.Collections.Generic.List(Of Integer).Enumerator.get_Current() As Integer"" IL_0043: stloc.1 IL_0044: nop IL_0045: ldloca.s V_4 IL_0047: call ""Function System.Collections.Generic.List(Of Integer).Enumerator.MoveNext() As Boolean"" IL_004c: stloc.s V_5 IL_004e: ldloc.s V_5 IL_0050: brtrue.s IL_003c IL_0052: leave.s IL_0063 } finally { IL_0054: ldloca.s V_4 IL_0056: constrained. ""System.Collections.Generic.List(Of Integer).Enumerator"" IL_005c: callvirt ""Sub System.IDisposable.Dispose()"" IL_0061: nop IL_0062: endfinally } IL_0063: ret } ") End Sub ''' <summary> ''' Local slots must be preserved based on signature. ''' </summary> <Fact> Public Sub PreserveLocalSlotsFor001() Dim sources0 = <compilation> <file name="a.vb"><![CDATA[ Class A(Of T) End Class Class C Inherits A(Of C) Shared Function F() As C Return Nothing End Function Shared Sub M(o As object) for i as double = goo() to goo() step goo() for j as double = goo() to goo() step goo() next next End Sub shared function goo() as double return 1 end function End Class ]]></file> </compilation> Dim compilation0 = CreateCompilationWithMscorlib40(sources0, options:=TestOptions.DebugDll) Dim compilation1 = compilation0.Clone() Dim testData0 = New CompilationTestData() Dim bytes0 = compilation0.EmitToArray(testData:=testData0) testData0.GetMethodData("C.M").VerifyIL(" { // Code size 148 (0x94) .maxstack 2 .locals init (Double V_0, Double V_1, Double V_2, Boolean V_3, Double V_4, //i Double V_5, Double V_6, Double V_7, Boolean V_8, Double V_9) //j IL_0000: nop IL_0001: call ""Function C.goo() As Double"" IL_0006: stloc.0 IL_0007: call ""Function C.goo() As Double"" IL_000c: stloc.1 IL_000d: call ""Function C.goo() As Double"" IL_0012: stloc.2 IL_0013: ldloc.2 IL_0014: ldc.r8 0 IL_001d: clt.un IL_001f: ldc.i4.0 IL_0020: ceq IL_0022: stloc.3 IL_0023: ldloc.0 IL_0024: stloc.s V_4 IL_0026: br.s IL_007c IL_0028: call ""Function C.goo() As Double"" IL_002d: stloc.s V_5 IL_002f: call ""Function C.goo() As Double"" IL_0034: stloc.s V_6 IL_0036: call ""Function C.goo() As Double"" IL_003b: stloc.s V_7 IL_003d: ldloc.s V_7 IL_003f: ldc.r8 0 IL_0048: clt.un IL_004a: ldc.i4.0 IL_004b: ceq IL_004d: stloc.s V_8 IL_004f: ldloc.s V_5 IL_0051: stloc.s V_9 IL_0053: br.s IL_005c IL_0055: ldloc.s V_9 IL_0057: ldloc.s V_7 IL_0059: add IL_005a: stloc.s V_9 IL_005c: ldloc.s V_8 IL_005e: brtrue.s IL_006b IL_0060: ldloc.s V_9 IL_0062: ldloc.s V_6 IL_0064: clt.un IL_0066: ldc.i4.0 IL_0067: ceq IL_0069: br.s IL_0074 IL_006b: ldloc.s V_9 IL_006d: ldloc.s V_6 IL_006f: cgt.un IL_0071: ldc.i4.0 IL_0072: ceq IL_0074: brtrue.s IL_0055 IL_0076: ldloc.s V_4 IL_0078: ldloc.2 IL_0079: add IL_007a: stloc.s V_4 IL_007c: ldloc.3 IL_007d: brtrue.s IL_0089 IL_007f: ldloc.s V_4 IL_0081: ldloc.1 IL_0082: clt.un IL_0084: ldc.i4.0 IL_0085: ceq IL_0087: br.s IL_0091 IL_0089: ldloc.s V_4 IL_008b: ldloc.1 IL_008c: cgt.un IL_008e: ldc.i4.0 IL_008f: ceq IL_0091: brtrue.s IL_0028 IL_0093: ret } ") Dim method0 = compilation0.GetMember(Of MethodSymbol)("C.M") Dim method1 = compilation1.GetMember(Of MethodSymbol)("C.M") Dim generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), testData0.GetMethodData("C.M").EncDebugInfoProvider) Dim diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(New SemanticEdit(SemanticEditKind.Update, method0, method1, preserveLocalVariables:=True))) diff1.VerifyIL("C.M", " { // Code size 148 (0x94) .maxstack 2 .locals init (Double V_0, Double V_1, Double V_2, Boolean V_3, Double V_4, //i Double V_5, Double V_6, Double V_7, Boolean V_8, Double V_9) //j IL_0000: nop IL_0001: call ""Function C.goo() As Double"" IL_0006: stloc.0 IL_0007: call ""Function C.goo() As Double"" IL_000c: stloc.1 IL_000d: call ""Function C.goo() As Double"" IL_0012: stloc.2 IL_0013: ldloc.2 IL_0014: ldc.r8 0 IL_001d: clt.un IL_001f: ldc.i4.0 IL_0020: ceq IL_0022: stloc.3 IL_0023: ldloc.0 IL_0024: stloc.s V_4 IL_0026: br.s IL_007c IL_0028: call ""Function C.goo() As Double"" IL_002d: stloc.s V_5 IL_002f: call ""Function C.goo() As Double"" IL_0034: stloc.s V_6 IL_0036: call ""Function C.goo() As Double"" IL_003b: stloc.s V_7 IL_003d: ldloc.s V_7 IL_003f: ldc.r8 0 IL_0048: clt.un IL_004a: ldc.i4.0 IL_004b: ceq IL_004d: stloc.s V_8 IL_004f: ldloc.s V_5 IL_0051: stloc.s V_9 IL_0053: br.s IL_005c IL_0055: ldloc.s V_9 IL_0057: ldloc.s V_7 IL_0059: add IL_005a: stloc.s V_9 IL_005c: ldloc.s V_8 IL_005e: brtrue.s IL_006b IL_0060: ldloc.s V_9 IL_0062: ldloc.s V_6 IL_0064: clt.un IL_0066: ldc.i4.0 IL_0067: ceq IL_0069: br.s IL_0074 IL_006b: ldloc.s V_9 IL_006d: ldloc.s V_6 IL_006f: cgt.un IL_0071: ldc.i4.0 IL_0072: ceq IL_0074: brtrue.s IL_0055 IL_0076: ldloc.s V_4 IL_0078: ldloc.2 IL_0079: add IL_007a: stloc.s V_4 IL_007c: ldloc.3 IL_007d: brtrue.s IL_0089 IL_007f: ldloc.s V_4 IL_0081: ldloc.1 IL_0082: clt.un IL_0084: ldc.i4.0 IL_0085: ceq IL_0087: br.s IL_0091 IL_0089: ldloc.s V_4 IL_008b: ldloc.1 IL_008c: cgt.un IL_008e: ldc.i4.0 IL_008f: ceq IL_0091: brtrue.s IL_0028 IL_0093: ret } ") End Sub ''' <summary> ''' Local slots must be preserved based on signature. ''' </summary> <Fact> Public Sub PreserveLocalSlotsImplicit() Dim sources0 = <compilation> <file name="a.vb"><![CDATA[ option explicit off Class A(Of T) End Class Class C Inherits A(Of C) Shared Function F() As C Return Nothing End Function Shared Sub M(o As Object) dim x as System.Guid() = nothing With x Dim z = .ToString y = z end With End Sub End Class ]]></file> </compilation> Dim compilation0 = CreateCompilationWithMscorlib40(sources0, options:=TestOptions.DebugDll) Dim compilation1 = compilation0.Clone() Dim testData0 = New CompilationTestData() Dim bytes0 = compilation0.EmitToArray(testData:=testData0) testData0.GetMethodData("C.M").VerifyIL(" { // Code size 19 (0x13) .maxstack 1 .locals init (Object V_0, //y System.Guid() V_1, //x System.Guid() V_2, //$W0 String V_3) //z IL_0000: nop IL_0001: ldnull IL_0002: stloc.1 IL_0003: nop IL_0004: ldloc.1 IL_0005: stloc.2 IL_0006: ldloc.2 IL_0007: callvirt ""Function Object.ToString() As String"" IL_000c: stloc.3 IL_000d: ldloc.3 IL_000e: stloc.0 IL_000f: nop IL_0010: ldnull IL_0011: stloc.2 IL_0012: ret } ") Dim method0 = compilation0.GetMember(Of MethodSymbol)("C.M") Dim method1 = compilation1.GetMember(Of MethodSymbol)("C.M") Dim generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), testData0.GetMethodData("C.M").EncDebugInfoProvider) Dim edit = New SemanticEdit(SemanticEditKind.Update, method0, method1, preserveLocalVariables:=True) Dim diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(edit)) diff1.VerifyIL("C.M", " { // Code size 19 (0x13) .maxstack 1 .locals init (Object V_0, //y System.Guid() V_1, //x System.Guid() V_2, //$W0 String V_3) //z IL_0000: nop IL_0001: ldnull IL_0002: stloc.1 IL_0003: nop IL_0004: ldloc.1 IL_0005: stloc.2 IL_0006: ldloc.2 IL_0007: callvirt ""Function Object.ToString() As String"" IL_000c: stloc.3 IL_000d: ldloc.3 IL_000e: stloc.0 IL_000f: nop IL_0010: ldnull IL_0011: stloc.2 IL_0012: ret } ") End Sub ''' <summary> ''' Local slots must be preserved based on signature. ''' </summary> <Fact> Public Sub PreserveLocalSlotsImplicitQualified() Dim sources0 = <compilation> <file name="a.vb"><![CDATA[ option explicit off Class A(Of T) End Class Class C Inherits A(Of C) Shared Function F() As C Return Nothing End Function Shared Sub M(o As Object) dim x as System.Guid() = nothing goto Length ' this does not declare Length Length: ' this does not declare Length dim y = x.Length ' this does not declare Length Length = 5 ' this does End Sub End Class ]]></file> </compilation> Dim compilation0 = CreateCompilationWithMscorlib40(sources0, options:=TestOptions.DebugDll) Dim compilation1 = compilation0.Clone() Dim testData0 = New CompilationTestData() Dim bytes0 = compilation0.EmitToArray(testData:=testData0) Dim actualIL0 = testData0.GetMethodData("C.M").GetMethodIL() Dim expectedIL0 = " { // Code size 18 (0x12) .maxstack 1 .locals init (Object V_0, //Length System.Guid() V_1, //x Integer V_2) //y IL_0000: nop IL_0001: ldnull IL_0002: stloc.1 IL_0003: br.s IL_0005 IL_0005: nop IL_0006: ldloc.1 IL_0007: ldlen IL_0008: conv.i4 IL_0009: stloc.2 IL_000a: ldc.i4.5 IL_000b: box ""Integer"" IL_0010: stloc.0 IL_0011: ret } " AssertEx.AssertEqualToleratingWhitespaceDifferences(expectedIL0, actualIL0) Dim method0 = compilation0.GetMember(Of MethodSymbol)("C.M") Dim method1 = compilation1.GetMember(Of MethodSymbol)("C.M") Dim generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), testData0.GetMethodData("C.M").EncDebugInfoProvider) Dim edit = New SemanticEdit(SemanticEditKind.Update, method0, method1, preserveLocalVariables:=True) Dim diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(edit)) diff1.VerifyIL("C.M", " { // Code size 18 (0x12) .maxstack 1 .locals init (Object V_0, //Length System.Guid() V_1, //x Integer V_2) //y IL_0000: nop IL_0001: ldnull IL_0002: stloc.1 IL_0003: br.s IL_0005 IL_0005: nop IL_0006: ldloc.1 IL_0007: ldlen IL_0008: conv.i4 IL_0009: stloc.2 IL_000a: ldc.i4.5 IL_000b: box ""Integer"" IL_0010: stloc.0 IL_0011: ret } ") End Sub ''' <summary> ''' Local slots must be preserved based on signature. ''' </summary> <Fact> Public Sub PreserveLocalSlotsImplicitXmlNs() Dim sources0 = <compilation> <file name="a.vb"><![CDATA[ option explicit off Imports <xmlns:Length="http: //roslyn/F"> Class A(Of T) End Class Class C Inherits A(Of C) Shared Function F() As C Return Nothing End Function Shared Sub M(o As Object) dim x as System.Guid() = nothing GetXmlNamespace(Length).ToString() ' this does not declare Length dim z as object = GetXmlNamespace(Length) ' this does not declare Length Length = 5 ' this does Dim aa = Length End Sub End Class ]]></file> </compilation> Dim compilation0 = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(sources0, XmlReferences, TestOptions.DebugDll) Dim compilation1 = compilation0.Clone() Dim testData0 = New CompilationTestData() Dim bytes0 = compilation0.EmitToArray(testData:=testData0) testData0.GetMethodData("C.M").VerifyIL(" { // Code size 45 (0x2d) .maxstack 1 .locals init (Object V_0, //Length System.Guid() V_1, //x Object V_2, //z Object V_3) //aa IL_0000: nop IL_0001: ldnull IL_0002: stloc.1 IL_0003: ldstr ""http: //roslyn/F"" IL_0008: call ""Function System.Xml.Linq.XNamespace.Get(String) As System.Xml.Linq.XNamespace"" IL_000d: callvirt ""Function System.Xml.Linq.XNamespace.ToString() As String"" IL_0012: pop IL_0013: ldstr ""http: //roslyn/F"" IL_0018: call ""Function System.Xml.Linq.XNamespace.Get(String) As System.Xml.Linq.XNamespace"" IL_001d: stloc.2 IL_001e: ldc.i4.5 IL_001f: box ""Integer"" IL_0024: stloc.0 IL_0025: ldloc.0 IL_0026: call ""Function System.Runtime.CompilerServices.RuntimeHelpers.GetObjectValue(Object) As Object"" IL_002b: stloc.3 IL_002c: ret } ") Dim method0 = compilation0.GetMember(Of MethodSymbol)("C.M") Dim method1 = compilation1.GetMember(Of MethodSymbol)("C.M") Dim generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), testData0.GetMethodData("C.M").EncDebugInfoProvider) Dim edit = New SemanticEdit(SemanticEditKind.Update, method0, method1, preserveLocalVariables:=True) Dim diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(edit)) diff1.VerifyIL("C.M", " { // Code size 45 (0x2d) .maxstack 1 .locals init (Object V_0, //Length System.Guid() V_1, //x Object V_2, //z Object V_3) //aa IL_0000: nop IL_0001: ldnull IL_0002: stloc.1 IL_0003: ldstr ""http: //roslyn/F"" IL_0008: call ""Function System.Xml.Linq.XNamespace.Get(String) As System.Xml.Linq.XNamespace"" IL_000d: callvirt ""Function System.Xml.Linq.XNamespace.ToString() As String"" IL_0012: pop IL_0013: ldstr ""http: //roslyn/F"" IL_0018: call ""Function System.Xml.Linq.XNamespace.Get(String) As System.Xml.Linq.XNamespace"" IL_001d: stloc.2 IL_001e: ldc.i4.5 IL_001f: box ""Integer"" IL_0024: stloc.0 IL_0025: ldloc.0 IL_0026: call ""Function System.Runtime.CompilerServices.RuntimeHelpers.GetObjectValue(Object) As Object"" IL_002b: stloc.3 IL_002c: ret } ") End Sub ''' <summary> ''' Local slots must be preserved based on signature. ''' </summary> <Fact> Public Sub PreserveLocalSlotsImplicitNamedArgXml() Dim sources0 = <compilation> <file name="a.vb"><![CDATA[ Option Explicit Off Class A(Of T) End Class Class C Inherits A(Of C) Shared Function F() As C Return Nothing End Function Shared Sub F(qq As Object) End Sub Shared Sub M(o As Object) F(qq:=<qq a="qq"></>) 'does not declare qq qq = 5 Dim aa = qq End Sub End Class ]]></file> </compilation> Dim compilation0 = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(sources0, XmlReferences, TestOptions.DebugDll) Dim compilation1 = compilation0.Clone() Dim testData0 = New CompilationTestData() Dim bytes0 = compilation0.EmitToArray(testData:=testData0) Dim actualIL0 = testData0.GetMethodData("C.M").GetMethodIL() Dim expectedIL0 = <![CDATA[ { // Code size 88 (0x58) .maxstack 3 .locals init (Object V_0, //qq Object V_1, //aa System.Xml.Linq.XElement V_2) IL_0000: nop IL_0001: ldstr "qq" IL_0006: ldstr "" IL_000b: call "Function System.Xml.Linq.XName.Get(String, String) As System.Xml.Linq.XName" IL_0010: newobj "Sub System.Xml.Linq.XElement..ctor(System.Xml.Linq.XName)" IL_0015: stloc.2 IL_0016: ldloc.2 IL_0017: ldstr "a" IL_001c: ldstr "" IL_0021: call "Function System.Xml.Linq.XName.Get(String, String) As System.Xml.Linq.XName" IL_0026: ldstr "qq" IL_002b: newobj "Sub System.Xml.Linq.XAttribute..ctor(System.Xml.Linq.XName, Object)" IL_0030: callvirt "Sub System.Xml.Linq.XContainer.Add(Object)" IL_0035: nop IL_0036: ldloc.2 IL_0037: ldstr "" IL_003c: callvirt "Sub System.Xml.Linq.XContainer.Add(Object)" IL_0041: nop IL_0042: ldloc.2 IL_0043: call "Sub C.F(Object)" IL_0048: nop IL_0049: ldc.i4.5 IL_004a: box "Integer" IL_004f: stloc.0 IL_0050: ldloc.0 IL_0051: call "Function System.Runtime.CompilerServices.RuntimeHelpers.GetObjectValue(Object) As Object" IL_0056: stloc.1 IL_0057: ret } ]]>.Value AssertEx.AssertEqualToleratingWhitespaceDifferences(expectedIL0, actualIL0) Dim method0 = compilation0.GetMember(Of MethodSymbol)("C.M") Dim method1 = compilation1.GetMember(Of MethodSymbol)("C.M") Dim generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), testData0.GetMethodData("C.M").EncDebugInfoProvider) Dim edit = New SemanticEdit(SemanticEditKind.Update, method0, method1, preserveLocalVariables:=True) Dim diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(edit)) diff1.VerifyIL("C.M", <![CDATA[ { // Code size 88 (0x58) .maxstack 3 .locals init (Object V_0, //qq Object V_1, //aa [unchanged] V_2, System.Xml.Linq.XElement V_3) IL_0000: nop IL_0001: ldstr "qq" IL_0006: ldstr "" IL_000b: call "Function System.Xml.Linq.XName.Get(String, String) As System.Xml.Linq.XName" IL_0010: newobj "Sub System.Xml.Linq.XElement..ctor(System.Xml.Linq.XName)" IL_0015: stloc.3 IL_0016: ldloc.3 IL_0017: ldstr "a" IL_001c: ldstr "" IL_0021: call "Function System.Xml.Linq.XName.Get(String, String) As System.Xml.Linq.XName" IL_0026: ldstr "qq" IL_002b: newobj "Sub System.Xml.Linq.XAttribute..ctor(System.Xml.Linq.XName, Object)" IL_0030: callvirt "Sub System.Xml.Linq.XContainer.Add(Object)" IL_0035: nop IL_0036: ldloc.3 IL_0037: ldstr "" IL_003c: callvirt "Sub System.Xml.Linq.XContainer.Add(Object)" IL_0041: nop IL_0042: ldloc.3 IL_0043: call "Sub C.F(Object)" IL_0048: nop IL_0049: ldc.i4.5 IL_004a: box "Integer" IL_004f: stloc.0 IL_0050: ldloc.0 IL_0051: call "Function System.Runtime.CompilerServices.RuntimeHelpers.GetObjectValue(Object) As Object" IL_0056: stloc.1 IL_0057: ret } ]]>.Value) End Sub <Fact> Public Sub AnonymousTypes_Update() Dim source0 = MarkedSource(" Class C Shared Sub F() Dim <N:0>x</N:0> = New With { .A = 1 } End Sub End Class ") Dim source1 = MarkedSource(" Class C Shared Sub F() Dim <N:0>x</N:0> = New With { .A = 2 } End Sub End Class ") Dim source2 = MarkedSource(" Class C Shared Sub F() Dim <N:0>x</N:0> = New With { .A = 3 } End Sub End Class ") Dim compilation0 = CreateCompilationWithMscorlib40(source0.Tree, options:=ComSafeDebugDll.WithMetadataImportOptions(MetadataImportOptions.All)) Dim compilation1 = compilation0.WithSource(source1.Tree) Dim compilation2 = compilation1.WithSource(source2.Tree) Dim v0 = CompileAndVerify(compilation0) Dim md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData) Dim f0 = compilation0.GetMember(Of MethodSymbol)("C.F") Dim f1 = compilation1.GetMember(Of MethodSymbol)("C.F") Dim f2 = compilation2.GetMember(Of MethodSymbol)("C.F") Dim generation0 = EmitBaseline.CreateInitialBaseline(md0, AddressOf v0.CreateSymReader().GetEncMethodDebugInfo) v0.VerifyIL("C.F", " { // Code size 9 (0x9) .maxstack 1 .locals init (VB$AnonymousType_0(Of Integer) V_0) //x IL_0000: nop IL_0001: ldc.i4.1 IL_0002: newobj ""Sub VB$AnonymousType_0(Of Integer)..ctor(Integer)"" IL_0007: stloc.0 IL_0008: ret } ") Dim diff1 = compilation1.EmitDifference(generation0, ImmutableArray.Create( New SemanticEdit(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables:=True))) diff1.VerifyIL("C.F", " { // Code size 9 (0x9) .maxstack 1 .locals init (VB$AnonymousType_0(Of Integer) V_0) //x IL_0000: nop IL_0001: ldc.i4.2 IL_0002: newobj ""Sub VB$AnonymousType_0(Of Integer)..ctor(Integer)"" IL_0007: stloc.0 IL_0008: ret } ") ' expect a single TypeRef for System.Object Dim md1 = diff1.GetMetadata() AssertEx.Equal({"[0x23000002] 0x0000020d.0x0000021a"}, DumpTypeRefs(md1.Reader)) Dim diff2 = compilation2.EmitDifference(diff1.NextGeneration, ImmutableArray.Create( New SemanticEdit(SemanticEditKind.Update, f1, f2, GetSyntaxMapFromMarkers(source1, source2), preserveLocalVariables:=True))) diff2.VerifyIL("C.F", " { // Code size 9 (0x9) .maxstack 1 .locals init (VB$AnonymousType_0(Of Integer) V_0) //x IL_0000: nop IL_0001: ldc.i4.3 IL_0002: newobj ""Sub VB$AnonymousType_0(Of Integer)..ctor(Integer)"" IL_0007: stloc.0 IL_0008: ret } ") ' expect a single TypeRef for System.Object Dim md2 = diff2.GetMetadata() AssertEx.Equal({"[0x23000003] 0x00000256.0x00000263"}, DumpTypeRefs(md2.Reader)) End Sub <Fact> Public Sub AnonymousTypes_UpdateAfterAdd() Dim source0 = MarkedSource(" Class C Shared Sub F() End Sub End Class ") Dim source1 = MarkedSource(" Class C Shared Sub F() Dim <N:0>x</N:0> = New With { .A = 2 } End Sub End Class ") Dim source2 = MarkedSource(" Class C Shared Sub F() Dim <N:0>x</N:0> = New With { .A = 3 } End Sub End Class ") Dim compilation0 = CreateCompilationWithMscorlib40(source0.Tree, options:=ComSafeDebugDll.WithMetadataImportOptions(MetadataImportOptions.All)) Dim compilation1 = compilation0.WithSource(source1.Tree) Dim compilation2 = compilation1.WithSource(source2.Tree) Dim v0 = CompileAndVerify(compilation0) Dim md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData) Dim f0 = compilation0.GetMember(Of MethodSymbol)("C.F") Dim f1 = compilation1.GetMember(Of MethodSymbol)("C.F") Dim f2 = compilation2.GetMember(Of MethodSymbol)("C.F") Dim generation0 = EmitBaseline.CreateInitialBaseline(md0, AddressOf v0.CreateSymReader().GetEncMethodDebugInfo) Dim diff1 = compilation1.EmitDifference(generation0, ImmutableArray.Create( New SemanticEdit(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables:=True))) diff1.VerifyIL("C.F", " { // Code size 9 (0x9) .maxstack 1 .locals init (VB$AnonymousType_0(Of Integer) V_0) //x IL_0000: nop IL_0001: ldc.i4.2 IL_0002: newobj ""Sub VB$AnonymousType_0(Of Integer)..ctor(Integer)"" IL_0007: stloc.0 IL_0008: ret } ") Dim diff2 = compilation2.EmitDifference(diff1.NextGeneration, ImmutableArray.Create( New SemanticEdit(SemanticEditKind.Update, f1, f2, GetSyntaxMapFromMarkers(source1, source2), preserveLocalVariables:=True))) diff2.VerifyIL("C.F", " { // Code size 9 (0x9) .maxstack 1 .locals init (VB$AnonymousType_0(Of Integer) V_0) //x IL_0000: nop IL_0001: ldc.i4.3 IL_0002: newobj ""Sub VB$AnonymousType_0(Of Integer)..ctor(Integer)"" IL_0007: stloc.0 IL_0008: ret } ") ' expect a single TypeRef for System.Object Dim md2 = diff2.GetMetadata() AssertEx.Equal({"[0x23000003] 0x00000289.0x00000296"}, DumpTypeRefs(md2.Reader)) End Sub Private Shared Iterator Function DumpTypeRefs(reader As MetadataReader) As IEnumerable(Of String) For Each typeRefHandle In reader.TypeReferences Dim typeRef = reader.GetTypeReference(typeRefHandle) Yield $"[0x{MetadataTokens.GetToken(typeRef.ResolutionScope):x8}] 0x{MetadataTokens.GetHeapOffset(typeRef.Namespace):x8}.0x{MetadataTokens.GetHeapOffset(typeRef.Name):x8}" Next End Function <Fact> Public Sub AnonymousTypes() Dim sources0 = <compilation> <file name="a.vb"><![CDATA[ Namespace N Class A Shared F As Object = New With {.A = 1, .B = 2} End Class End Namespace Namespace M Class B Shared Sub M() Dim x As New With {.B = 3, .A = 4} Dim y = x.A Dim z As New With {.C = 5} End Sub End Class End Namespace ]]></file> </compilation> Dim sources1 = <compilation> <file name="a.vb"><![CDATA[ Namespace N Class A Shared F As Object = New With {.A = 1, .B = 2} End Class End Namespace Namespace M Class B Shared Sub M() Dim x As New With {.B = 3, .A = 4} Dim y As New With {.A = x.A} Dim z As New With {.C = 5} End Sub End Class End Namespace ]]></file> </compilation> Dim compilation0 = CreateCompilationWithMscorlib40(sources0, options:=TestOptions.DebugDll) Dim compilation1 = compilation0.WithSource(sources1) Dim testData0 = New CompilationTestData() Dim bytes0 = compilation0.EmitToArray(testData:=testData0) Using md0 = ModuleMetadata.CreateFromImage(bytes0) Dim generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), testData0.GetMethodData("M.B.M").EncDebugInfoProvider) Dim method0 = compilation0.GetMember(Of MethodSymbol)("M.B.M") Dim reader0 = md0.MetadataReader CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "VB$AnonymousType_0`2", "VB$AnonymousType_1`2", "VB$AnonymousType_2`1", "A", "B") Dim method1 = compilation1.GetMember(Of MethodSymbol)("M.B.M") Dim diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(New SemanticEdit(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables:=True))) Using md1 = diff1.GetMetadata() Dim reader1 = md1.Reader CheckNames({reader0, reader1}, reader1.GetTypeDefNames(), "VB$AnonymousType_3`1") diff1.VerifyIL("M.B.M", " { // Code size 29 (0x1d) .maxstack 2 .locals init (VB$AnonymousType_1(Of Integer, Integer) V_0, //x [int] V_1, VB$AnonymousType_2(Of Integer) V_2, //z VB$AnonymousType_3(Of Integer) V_3) //y IL_0000: nop IL_0001: ldc.i4.3 IL_0002: ldc.i4.4 IL_0003: newobj ""Sub VB$AnonymousType_1(Of Integer, Integer)..ctor(Integer, Integer)"" IL_0008: stloc.0 IL_0009: ldloc.0 IL_000a: callvirt ""Function VB$AnonymousType_1(Of Integer, Integer).get_A() As Integer"" IL_000f: newobj ""Sub VB$AnonymousType_3(Of Integer)..ctor(Integer)"" IL_0014: stloc.3 IL_0015: ldc.i4.5 IL_0016: newobj ""Sub VB$AnonymousType_2(Of Integer)..ctor(Integer)"" IL_001b: stloc.2 IL_001c: ret } ") End Using End Using End Sub ''' <summary> ''' Update method with anonymous type that was ''' not directly referenced in previous generation. ''' </summary> <Fact> Public Sub AnonymousTypes_SkipGeneration() Dim source0 = MarkedSource(" Class A End Class Class B <N:3>Shared Function F() As Object</N:3> Dim <N:0>x</N:0> As New With {.A = 1} Return x.A End Function <N:4>Shared Function G() As Object</N:4> Dim <N:1>x</N:1> As Integer = 1 Return x End Function End Class ") Dim source1 = MarkedSource(" Class A End Class Class B <N:3>Shared Function F() As Object</N:3> Dim <N:0>x</N:0> As New With {.A = 1} Return x.A End Function <N:4>Shared Function G() As Object</N:4> Dim <N:1>x</N:1> As Integer = 1 Return x + 1 End Function End Class ") Dim source2 = MarkedSource(" Class A End Class Class B <N:3>Shared Function F() As Object</N:3> Dim <N:0>x</N:0> As New With {.A = 1} Return x.A End Function <N:4>Shared Function G() As Object</N:4> Dim <N:1>x</N:1> As New With {.A = New A()} Dim <N:2>y</N:2> As New With {.B = 2} Return x.A End Function End Class ") Dim source3 = MarkedSource(" Class A End Class Class B <N:3>Shared Function F() As Object</N:3> Dim <N:0>x</N:0> As New With {.A = 1} Return x.A End Function <N:4>Shared Function G() As Object</N:4> Dim <N:1>x</N:1> As New With {.A = New A()} Dim <N:2>y</N:2> As New With {.B = 3} Return y.B End Function End Class ") Dim compilation0 = CreateCompilationWithMscorlib40(source0.Tree, options:=ComSafeDebugDll) Dim compilation1 = compilation0.WithSource(source1.Tree) Dim compilation2 = compilation1.WithSource(source2.Tree) Dim compilation3 = compilation2.WithSource(source3.Tree) Dim v0 = CompileAndVerify(compilation0) Dim md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData) Dim generation0 = EmitBaseline.CreateInitialBaseline(md0, AddressOf v0.CreateSymReader().GetEncMethodDebugInfo) Dim method0 = compilation0.GetMember(Of MethodSymbol)("B.G") Dim method1 = compilation1.GetMember(Of MethodSymbol)("B.G") Dim method2 = compilation2.GetMember(Of MethodSymbol)("B.G") Dim method3 = compilation3.GetMember(Of MethodSymbol)("B.G") Dim reader0 = md0.MetadataReader CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "VB$AnonymousType_0`1", "A", "B") Dim diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(New SemanticEdit(SemanticEditKind.Update, method0, method1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables:=True))) Dim md1 = diff1.GetMetadata() Dim reader1 = md1.Reader CheckNames({reader0, reader1}, reader1.GetTypeDefNames()) ' no additional types diff1.VerifyIL("B.G", " { // Code size 16 (0x10) .maxstack 2 .locals init (Object V_0, //G Integer V_1) //x IL_0000: nop IL_0001: ldc.i4.1 IL_0002: stloc.1 IL_0003: ldloc.1 IL_0004: ldc.i4.1 IL_0005: add.ovf IL_0006: box ""Integer"" IL_000b: stloc.0 IL_000c: br.s IL_000e IL_000e: ldloc.0 IL_000f: ret } ") Dim diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create(New SemanticEdit(SemanticEditKind.Update, method1, method2, GetSyntaxMapFromMarkers(source1, source2), preserveLocalVariables:=True))) Dim md2 = diff2.GetMetadata() Dim reader2 = md2.Reader CheckNames({reader0, reader1, reader2}, reader2.GetTypeDefNames(), "VB$AnonymousType_1`1") ' one additional type diff2.VerifyIL("B.G", " { // Code size 30 (0x1e) .maxstack 1 .locals init (Object V_0, //G [int] V_1, VB$AnonymousType_0(Of A) V_2, //x VB$AnonymousType_1(Of Integer) V_3) //y IL_0000: nop IL_0001: newobj ""Sub A..ctor()"" IL_0006: newobj ""Sub VB$AnonymousType_0(Of A)..ctor(A)"" IL_000b: stloc.2 IL_000c: ldc.i4.2 IL_000d: newobj ""Sub VB$AnonymousType_1(Of Integer)..ctor(Integer)"" IL_0012: stloc.3 IL_0013: ldloc.2 IL_0014: callvirt ""Function VB$AnonymousType_0(Of A).get_A() As A"" IL_0019: stloc.0 IL_001a: br.s IL_001c IL_001c: ldloc.0 IL_001d: ret } ") Dim diff3 = compilation3.EmitDifference( diff2.NextGeneration, ImmutableArray.Create(New SemanticEdit(SemanticEditKind.Update, method2, method3, GetSyntaxMapFromMarkers(source2, source3), preserveLocalVariables:=True))) Dim md3 = diff3.GetMetadata() Dim reader3 = md3.Reader CheckNames({reader0, reader1, reader2, reader3}, reader3.GetTypeDefNames()) ' no additional types diff3.VerifyIL("B.G", " { // Code size 35 (0x23) .maxstack 1 .locals init (Object V_0, //G [int] V_1, VB$AnonymousType_0(Of A) V_2, //x VB$AnonymousType_1(Of Integer) V_3) //y IL_0000: nop IL_0001: newobj ""Sub A..ctor()"" IL_0006: newobj ""Sub VB$AnonymousType_0(Of A)..ctor(A)"" IL_000b: stloc.2 IL_000c: ldc.i4.3 IL_000d: newobj ""Sub VB$AnonymousType_1(Of Integer)..ctor(Integer)"" IL_0012: stloc.3 IL_0013: ldloc.3 IL_0014: callvirt ""Function VB$AnonymousType_1(Of Integer).get_B() As Integer"" IL_0019: box ""Integer"" IL_001e: stloc.0 IL_001f: br.s IL_0021 IL_0021: ldloc.0 IL_0022: ret } ") End Sub ''' <summary> ''' Update another method (without directly referencing ''' anonymous type) after updating method with anonymous type. ''' </summary> <Fact> Public Sub AnonymousTypes_SkipGeneration_2() Dim sources0 = <compilation> <file name="a.vb"><![CDATA[ Class C Shared Function F() As Object Dim x As New With {.A = 1} Return x.A End Function Shared Function G() As Object Dim x As Integer = 1 Return x End Function End Class ]]></file> </compilation> Dim sources1 = <compilation> <file name="a.vb"><![CDATA[ Class C Shared Function F() As Object Dim x As New With {.A = 2, .B = 3} Return x.A End Function Shared Function G() As Object Dim x As Integer = 1 Return x End Function End Class ]]></file> </compilation> Dim sources2 = <compilation> <file name="a.vb"><![CDATA[ Class C Shared Function F() As Object Dim x As New With {.A = 2, .B = 3} Return x.A End Function Shared Function G() As Object Dim x As Integer = 1 Return x + 1 End Function End Class ]]></file> </compilation> Dim sources3 = <compilation> <file name="a.vb"><![CDATA[ Class C Shared Function F() As Object Dim x As New With {.A = 2, .B = 3} Return x.A End Function Shared Function G() As Object Dim x As New With {.A = DirectCast(Nothing, Object)} Dim y As New With {.A = "a"c, .B = "b"c} Return x End Function End Class ]]></file> </compilation> Dim compilation0 = CreateCompilationWithMscorlib40(sources0, options:=TestOptions.DebugDll) Dim compilation1 = compilation0.WithSource(sources1) Dim compilation2 = compilation1.WithSource(sources2) Dim compilation3 = compilation2.WithSource(sources3) Dim testData0 = New CompilationTestData() Dim bytes0 = compilation0.EmitToArray(testData:=testData0) Using md0 = ModuleMetadata.CreateFromImage(bytes0) Dim generation0 = EmitBaseline.CreateInitialBaseline( ModuleMetadata.CreateFromImage(bytes0), Function(m) Select Case md0.MetadataReader.GetString(md0.MetadataReader.GetMethodDefinition(m).Name) Case "F" : Return testData0.GetMethodData("C.F").GetEncDebugInfo() Case "G" : Return testData0.GetMethodData("C.G").GetEncDebugInfo() End Select Return Nothing End Function) Dim method0F = compilation0.GetMember(Of MethodSymbol)("C.F") Dim reader0 = md0.MetadataReader CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "VB$AnonymousType_0`1", "C") Dim method1F = compilation1.GetMember(Of MethodSymbol)("C.F") Dim method1G = compilation1.GetMember(Of MethodSymbol)("C.G") Dim diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(New SemanticEdit(SemanticEditKind.Update, method0F, method1F, GetEquivalentNodesMap(method1F, method0F), preserveLocalVariables:=True))) Using md1 = diff1.GetMetadata() Dim reader1 = md1.Reader CheckNames({reader0, reader1}, reader1.GetTypeDefNames(), "VB$AnonymousType_1`2") ' one additional type Dim method2G = compilation2.GetMember(Of MethodSymbol)("C.G") Dim diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create(New SemanticEdit(SemanticEditKind.Update, method1G, method2G, GetEquivalentNodesMap(method2G, method1G), preserveLocalVariables:=True))) Using md2 = diff2.GetMetadata() Dim reader2 = md2.Reader CheckNames({reader0, reader1, reader2}, reader2.GetTypeDefNames()) ' no additional types Dim method3G = compilation3.GetMember(Of MethodSymbol)("C.G") Dim diff3 = compilation3.EmitDifference( diff2.NextGeneration, ImmutableArray.Create(New SemanticEdit(SemanticEditKind.Update, method2G, method3G, GetEquivalentNodesMap(method3G, method2G), preserveLocalVariables:=True))) Using md3 = diff3.GetMetadata() Dim reader3 = md3.Reader CheckNames({reader0, reader1, reader2, reader3}, reader3.GetTypeDefNames()) ' no additional types End Using End Using End Using End Using End Sub <WorkItem(1292, "https://github.com/dotnet/roslyn/issues/1292")> <Fact> Public Sub AnonymousTypes_Key() Dim sources0 = <compilation> <file name="a.vb"><![CDATA[ Class C Shared Sub M() Dim x As New With {.A = 1, .B = 2} Dim y As New With {Key .A = 3, .B = 4} Dim z As New With {.A = 5, Key .B = 6} End Sub End Class ]]></file> </compilation> Dim sources1 = <compilation> <file name="a.vb"><![CDATA[ Class C Shared Sub M() Dim x As New With {.A = 1, .B = 2} Dim y As New With {Key .A = 3, Key .B = 4} Dim z As New With {Key .A = 5, .B = 6} End Sub End Class ]]></file> </compilation> Dim compilation0 = CreateCompilationWithMscorlib40(sources0, options:=TestOptions.DebugDll) Dim compilation1 = compilation0.WithSource(sources1) Dim testData0 = New CompilationTestData() Dim bytes0 = compilation0.EmitToArray(testData:=testData0) Using md0 = ModuleMetadata.CreateFromImage(bytes0) Dim generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), testData0.GetMethodData("C.M").EncDebugInfoProvider) Dim method0 = compilation0.GetMember(Of MethodSymbol)("C.M") Dim reader0 = md0.MetadataReader CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "VB$AnonymousType_0`2", "VB$AnonymousType_1`2", "VB$AnonymousType_2`2", "C") Dim method1 = compilation1.GetMember(Of MethodSymbol)("C.M") Dim diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(New SemanticEdit(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables:=True))) Using md1 = diff1.GetMetadata() Dim reader1 = md1.Reader CheckNames({reader0, reader1}, reader1.GetTypeDefNames(), "VB$AnonymousType_3`2") diff1.VerifyIL("C.M", "{ // Code size 27 (0x1b) .maxstack 2 .locals init (VB$AnonymousType_0(Of Integer, Integer) V_0, //x [unchanged] V_1, [unchanged] V_2, VB$AnonymousType_3(Of Integer, Integer) V_3, //y VB$AnonymousType_1(Of Integer, Integer) V_4) //z IL_0000: nop IL_0001: ldc.i4.1 IL_0002: ldc.i4.2 IL_0003: newobj ""Sub VB$AnonymousType_0(Of Integer, Integer)..ctor(Integer, Integer)"" IL_0008: stloc.0 IL_0009: ldc.i4.3 IL_000a: ldc.i4.4 IL_000b: newobj ""Sub VB$AnonymousType_3(Of Integer, Integer)..ctor(Integer, Integer)"" IL_0010: stloc.3 IL_0011: ldc.i4.5 IL_0012: ldc.i4.6 IL_0013: newobj ""Sub VB$AnonymousType_1(Of Integer, Integer)..ctor(Integer, Integer)"" IL_0018: stloc.s V_4 IL_001a: ret }") End Using End Using End Sub <Fact> Public Sub AnonymousTypes_DifferentCase() Dim sources0 = <compilation> <file name="a.vb"><![CDATA[ Class C Shared Sub M() Dim x As New With {.A = 1, .B = 2} Dim y As New With {.a = 3, .b = 4} End Sub End Class ]]></file> </compilation> Dim sources1 = <compilation> <file name="a.vb"><![CDATA[ Class C Shared Sub M() Dim x As New With {.a = 1, .B = 2} Dim y As New With {.AB = 3} Dim z As New With {.ab = 4} End Sub End Class ]]></file> </compilation> Dim sources2 = <compilation> <file name="a.vb"><![CDATA[ Class C Shared Sub M() Dim x As New With {.a = 1, .B = 2} Dim z As New With {.Ab = 5} End Sub End Class ]]></file> </compilation> Dim compilation0 = CreateCompilationWithMscorlib40(sources0, options:=TestOptions.DebugDll) Dim compilation1 = compilation0.WithSource(sources1) Dim compilation2 = compilation1.WithSource(sources2) Dim testData0 = New CompilationTestData() Dim bytes0 = compilation0.EmitToArray(testData:=testData0) Using md0 = ModuleMetadata.CreateFromImage(bytes0) Dim generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), testData0.GetMethodData("C.M").EncDebugInfoProvider) Dim method0 = compilation0.GetMember(Of MethodSymbol)("C.M") Dim reader0 = md0.MetadataReader CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "VB$AnonymousType_0`2", "C") Dim method1 = compilation1.GetMember(Of MethodSymbol)("C.M") Dim diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(New SemanticEdit(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables:=True))) Using md1 = diff1.GetMetadata() Dim reader1 = md1.Reader CheckNames({reader0, reader1}, reader1.GetTypeDefNames(), "VB$AnonymousType_1`1") diff1.VerifyIL("C.M", "{ // Code size 25 (0x19) .maxstack 2 .locals init ([unchanged] V_0, [unchanged] V_1, VB$AnonymousType_0(Of Integer, Integer) V_2, //x VB$AnonymousType_1(Of Integer) V_3, //y VB$AnonymousType_1(Of Integer) V_4) //z IL_0000: nop IL_0001: ldc.i4.1 IL_0002: ldc.i4.2 IL_0003: newobj ""Sub VB$AnonymousType_0(Of Integer, Integer)..ctor(Integer, Integer)"" IL_0008: stloc.2 IL_0009: ldc.i4.3 IL_000a: newobj ""Sub VB$AnonymousType_1(Of Integer)..ctor(Integer)"" IL_000f: stloc.3 IL_0010: ldc.i4.4 IL_0011: newobj ""Sub VB$AnonymousType_1(Of Integer)..ctor(Integer)"" IL_0016: stloc.s V_4 IL_0018: ret }") Dim method2 = compilation2.GetMember(Of MethodSymbol)("C.M") Dim diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create(New SemanticEdit(SemanticEditKind.Update, method1, method2, GetEquivalentNodesMap(method2, method1), preserveLocalVariables:=True))) Using md2 = diff2.GetMetadata() Dim reader2 = md2.Reader CheckNames({reader0, reader1, reader2}, reader2.GetTypeDefNames()) diff2.VerifyIL("C.M", "{ // Code size 18 (0x12) .maxstack 2 .locals init ([unchanged] V_0, [unchanged] V_1, VB$AnonymousType_0(Of Integer, Integer) V_2, //x [unchanged] V_3, [unchanged] V_4, VB$AnonymousType_1(Of Integer) V_5) //z IL_0000: nop IL_0001: ldc.i4.1 IL_0002: ldc.i4.2 IL_0003: newobj ""Sub VB$AnonymousType_0(Of Integer, Integer)..ctor(Integer, Integer)"" IL_0008: stloc.2 IL_0009: ldc.i4.5 IL_000a: newobj ""Sub VB$AnonymousType_1(Of Integer)..ctor(Integer)"" IL_000f: stloc.s V_5 IL_0011: ret }") End Using End Using End Using End Sub <Fact> Public Sub AnonymousTypes_Nested() Dim template = " Imports System Imports System.Linq Class C Sub F(args As String()) Dim <N:4>result</N:4> = From a in args Let <N:0>x = a.Reverse()</N:0> Let <N:1>y = x.Reverse()</N:1> <N:2>Where x.SequenceEqual(y)</N:2> Select <N:3>Value = a</N:3>, Length = a.Length Console.WriteLine(<<VALUE>>) End Sub End Class " Dim source0 = MarkedSource(template.Replace("<<VALUE>>", "0")) Dim source1 = MarkedSource(template.Replace("<<VALUE>>", "1")) Dim source2 = MarkedSource(template.Replace("<<VALUE>>", "2")) Dim compilation0 = CreateCompilationWithMscorlib45({source0.Tree}, {SystemCoreRef}, options:=ComSafeDebugDll) Dim compilation1 = compilation0.WithSource(source1.Tree) Dim compilation2 = compilation0.WithSource(source2.Tree) Dim v0 = CompileAndVerify(compilation0) Dim md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData) Dim f0 = compilation0.GetMember(Of MethodSymbol)("C.F") Dim f1 = compilation1.GetMember(Of MethodSymbol)("C.F") Dim f2 = compilation2.GetMember(Of MethodSymbol)("C.F") Dim generation0 = EmitBaseline.CreateInitialBaseline(md0, AddressOf v0.CreateSymReader().GetEncMethodDebugInfo) Dim expectedIL = " { // Code size 175 (0xaf) .maxstack 3 .locals init (System.Collections.Generic.IEnumerable(Of <anonymous type: Key Value As String, Key Length As Integer>) V_0) //result IL_0000: nop IL_0001: ldarg.1 IL_0002: ldsfld ""C._Closure$__.$I1-0 As System.Func(Of String, <anonymous type: Key a As String, Key x As System.Collections.Generic.IEnumerable(Of Char)>)"" IL_0007: brfalse.s IL_0010 IL_0009: ldsfld ""C._Closure$__.$I1-0 As System.Func(Of String, <anonymous type: Key a As String, Key x As System.Collections.Generic.IEnumerable(Of Char)>)"" IL_000e: br.s IL_0026 IL_0010: ldsfld ""C._Closure$__.$I As C._Closure$__"" IL_0015: ldftn ""Function C._Closure$__._Lambda$__1-0(String) As <anonymous type: Key a As String, Key x As System.Collections.Generic.IEnumerable(Of Char)>"" IL_001b: newobj ""Sub System.Func(Of String, <anonymous type: Key a As String, Key x As System.Collections.Generic.IEnumerable(Of Char)>)..ctor(Object, System.IntPtr)"" IL_0020: dup IL_0021: stsfld ""C._Closure$__.$I1-0 As System.Func(Of String, <anonymous type: Key a As String, Key x As System.Collections.Generic.IEnumerable(Of Char)>)"" IL_0026: call ""Function System.Linq.Enumerable.Select(Of String, <anonymous type: Key a As String, Key x As System.Collections.Generic.IEnumerable(Of Char)>)(System.Collections.Generic.IEnumerable(Of String), System.Func(Of String, <anonymous type: Key a As String, Key x As System.Collections.Generic.IEnumerable(Of Char)>)) As System.Collections.Generic.IEnumerable(Of <anonymous type: Key a As String, Key x As System.Collections.Generic.IEnumerable(Of Char)>)"" IL_002b: ldsfld ""C._Closure$__.$I1-1 As System.Func(Of <anonymous type: Key a As String, Key x As System.Collections.Generic.IEnumerable(Of Char)>, <anonymous type: Key $VB$It As <anonymous type: Key a As String, Key x As System.Collections.Generic.IEnumerable(Of Char)>, Key y As System.Collections.Generic.IEnumerable(Of Char)>)"" IL_0030: brfalse.s IL_0039 IL_0032: ldsfld ""C._Closure$__.$I1-1 As System.Func(Of <anonymous type: Key a As String, Key x As System.Collections.Generic.IEnumerable(Of Char)>, <anonymous type: Key $VB$It As <anonymous type: Key a As String, Key x As System.Collections.Generic.IEnumerable(Of Char)>, Key y As System.Collections.Generic.IEnumerable(Of Char)>)"" IL_0037: br.s IL_004f IL_0039: ldsfld ""C._Closure$__.$I As C._Closure$__"" IL_003e: ldftn ""Function C._Closure$__._Lambda$__1-1(<anonymous type: Key a As String, Key x As System.Collections.Generic.IEnumerable(Of Char)>) As <anonymous type: Key $VB$It As <anonymous type: Key a As String, Key x As System.Collections.Generic.IEnumerable(Of Char)>, Key y As System.Collections.Generic.IEnumerable(Of Char)>"" IL_0044: newobj ""Sub System.Func(Of <anonymous type: Key a As String, Key x As System.Collections.Generic.IEnumerable(Of Char)>, <anonymous type: Key $VB$It As <anonymous type: Key a As String, Key x As System.Collections.Generic.IEnumerable(Of Char)>, Key y As System.Collections.Generic.IEnumerable(Of Char)>)..ctor(Object, System.IntPtr)"" IL_0049: dup IL_004a: stsfld ""C._Closure$__.$I1-1 As System.Func(Of <anonymous type: Key a As String, Key x As System.Collections.Generic.IEnumerable(Of Char)>, <anonymous type: Key $VB$It As <anonymous type: Key a As String, Key x As System.Collections.Generic.IEnumerable(Of Char)>, Key y As System.Collections.Generic.IEnumerable(Of Char)>)"" IL_004f: call ""Function System.Linq.Enumerable.Select(Of <anonymous type: Key a As String, Key x As System.Collections.Generic.IEnumerable(Of Char)>, <anonymous type: Key $VB$It As <anonymous type: Key a As String, Key x As System.Collections.Generic.IEnumerable(Of Char)>, Key y As System.Collections.Generic.IEnumerable(Of Char)>)(System.Collections.Generic.IEnumerable(Of <anonymous type: Key a As String, Key x As System.Collections.Generic.IEnumerable(Of Char)>), System.Func(Of <anonymous type: Key a As String, Key x As System.Collections.Generic.IEnumerable(Of Char)>, <anonymous type: Key $VB$It As <anonymous type: Key a As String, Key x As System.Collections.Generic.IEnumerable(Of Char)>, Key y As System.Collections.Generic.IEnumerable(Of Char)>)) As System.Collections.Generic.IEnumerable(Of <anonymous type: Key $VB$It As <anonymous type: Key a As String, Key x As System.Collections.Generic.IEnumerable(Of Char)>, Key y As System.Collections.Generic.IEnumerable(Of Char)>)"" IL_0054: ldsfld ""C._Closure$__.$I1-2 As System.Func(Of <anonymous type: Key $VB$It As <anonymous type: Key a As String, Key x As System.Collections.Generic.IEnumerable(Of Char)>, Key y As System.Collections.Generic.IEnumerable(Of Char)>, Boolean)"" IL_0059: brfalse.s IL_0062 IL_005b: ldsfld ""C._Closure$__.$I1-2 As System.Func(Of <anonymous type: Key $VB$It As <anonymous type: Key a As String, Key x As System.Collections.Generic.IEnumerable(Of Char)>, Key y As System.Collections.Generic.IEnumerable(Of Char)>, Boolean)"" IL_0060: br.s IL_0078 IL_0062: ldsfld ""C._Closure$__.$I As C._Closure$__"" IL_0067: ldftn ""Function C._Closure$__._Lambda$__1-2(<anonymous type: Key $VB$It As <anonymous type: Key a As String, Key x As System.Collections.Generic.IEnumerable(Of Char)>, Key y As System.Collections.Generic.IEnumerable(Of Char)>) As Boolean"" IL_006d: newobj ""Sub System.Func(Of <anonymous type: Key $VB$It As <anonymous type: Key a As String, Key x As System.Collections.Generic.IEnumerable(Of Char)>, Key y As System.Collections.Generic.IEnumerable(Of Char)>, Boolean)..ctor(Object, System.IntPtr)"" IL_0072: dup IL_0073: stsfld ""C._Closure$__.$I1-2 As System.Func(Of <anonymous type: Key $VB$It As <anonymous type: Key a As String, Key x As System.Collections.Generic.IEnumerable(Of Char)>, Key y As System.Collections.Generic.IEnumerable(Of Char)>, Boolean)"" IL_0078: call ""Function System.Linq.Enumerable.Where(Of <anonymous type: Key $VB$It As <anonymous type: Key a As String, Key x As System.Collections.Generic.IEnumerable(Of Char)>, Key y As System.Collections.Generic.IEnumerable(Of Char)>)(System.Collections.Generic.IEnumerable(Of <anonymous type: Key $VB$It As <anonymous type: Key a As String, Key x As System.Collections.Generic.IEnumerable(Of Char)>, Key y As System.Collections.Generic.IEnumerable(Of Char)>), System.Func(Of <anonymous type: Key $VB$It As <anonymous type: Key a As String, Key x As System.Collections.Generic.IEnumerable(Of Char)>, Key y As System.Collections.Generic.IEnumerable(Of Char)>, Boolean)) As System.Collections.Generic.IEnumerable(Of <anonymous type: Key $VB$It As <anonymous type: Key a As String, Key x As System.Collections.Generic.IEnumerable(Of Char)>, Key y As System.Collections.Generic.IEnumerable(Of Char)>)"" IL_007d: ldsfld ""C._Closure$__.$I1-3 As System.Func(Of <anonymous type: Key $VB$It As <anonymous type: Key a As String, Key x As System.Collections.Generic.IEnumerable(Of Char)>, Key y As System.Collections.Generic.IEnumerable(Of Char)>, <anonymous type: Key Value As String, Key Length As Integer>)"" IL_0082: brfalse.s IL_008b IL_0084: ldsfld ""C._Closure$__.$I1-3 As System.Func(Of <anonymous type: Key $VB$It As <anonymous type: Key a As String, Key x As System.Collections.Generic.IEnumerable(Of Char)>, Key y As System.Collections.Generic.IEnumerable(Of Char)>, <anonymous type: Key Value As String, Key Length As Integer>)"" IL_0089: br.s IL_00a1 IL_008b: ldsfld ""C._Closure$__.$I As C._Closure$__"" IL_0090: ldftn ""Function C._Closure$__._Lambda$__1-3(<anonymous type: Key $VB$It As <anonymous type: Key a As String, Key x As System.Collections.Generic.IEnumerable(Of Char)>, Key y As System.Collections.Generic.IEnumerable(Of Char)>) As <anonymous type: Key Value As String, Key Length As Integer>"" IL_0096: newobj ""Sub System.Func(Of <anonymous type: Key $VB$It As <anonymous type: Key a As String, Key x As System.Collections.Generic.IEnumerable(Of Char)>, Key y As System.Collections.Generic.IEnumerable(Of Char)>, <anonymous type: Key Value As String, Key Length As Integer>)..ctor(Object, System.IntPtr)"" IL_009b: dup IL_009c: stsfld ""C._Closure$__.$I1-3 As System.Func(Of <anonymous type: Key $VB$It As <anonymous type: Key a As String, Key x As System.Collections.Generic.IEnumerable(Of Char)>, Key y As System.Collections.Generic.IEnumerable(Of Char)>, <anonymous type: Key Value As String, Key Length As Integer>)"" IL_00a1: call ""Function System.Linq.Enumerable.Select(Of <anonymous type: Key $VB$It As <anonymous type: Key a As String, Key x As System.Collections.Generic.IEnumerable(Of Char)>, Key y As System.Collections.Generic.IEnumerable(Of Char)>, <anonymous type: Key Value As String, Key Length As Integer>)(System.Collections.Generic.IEnumerable(Of <anonymous type: Key $VB$It As <anonymous type: Key a As String, Key x As System.Collections.Generic.IEnumerable(Of Char)>, Key y As System.Collections.Generic.IEnumerable(Of Char)>), System.Func(Of <anonymous type: Key $VB$It As <anonymous type: Key a As String, Key x As System.Collections.Generic.IEnumerable(Of Char)>, Key y As System.Collections.Generic.IEnumerable(Of Char)>, <anonymous type: Key Value As String, Key Length As Integer>)) As System.Collections.Generic.IEnumerable(Of <anonymous type: Key Value As String, Key Length As Integer>)"" IL_00a6: stloc.0 IL_00a7: ldc.i4.<<VALUE>> IL_00a8: call ""Sub System.Console.WriteLine(Integer)"" IL_00ad: nop IL_00ae: ret }" v0.VerifyIL("C.F", expectedIL.Replace("<<VALUE>>", "0")) Dim diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( New SemanticEdit(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables:=True))) diff1.VerifySynthesizedMembers( "C: {_Closure$__}", "C._Closure$__: {$I1-0, $I1-1, $I1-2, $I1-3, _Lambda$__1-0, _Lambda$__1-1, _Lambda$__1-2, _Lambda$__1-3}") diff1.VerifyIL("C.F", expectedIL.Replace("<<VALUE>>", "1")) Dim diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create( New SemanticEdit(SemanticEditKind.Update, f1, f2, GetSyntaxMapFromMarkers(source1, source2), preserveLocalVariables:=True))) diff2.VerifySynthesizedMembers( "C: {_Closure$__}", "C._Closure$__: {$I1-0, $I1-1, $I1-2, $I1-3, _Lambda$__1-0, _Lambda$__1-1, _Lambda$__1-2, _Lambda$__1-3}") diff2.VerifyIL("C.F", expectedIL.Replace("<<VALUE>>", "2")) End Sub <Fact> Public Sub AnonymousDelegates1() Dim source0 = MarkedSource(" Class C Private Sub F() Dim <N:0>g</N:0> = <N:1>Function(ByRef arg As String) arg</N:1> System.Console.WriteLine(1) End Sub End Class ") Dim source1 = MarkedSource(" Class C Private Sub F() Dim <N:0>g</N:0> = <N:1>Function(ByRef arg As String) arg</N:1> System.Console.WriteLine(2) End Sub End Class ") Dim source2 = MarkedSource(" Class C Private Sub F() Dim <N:0>g</N:0> = <N:1>Function(ByRef arg As String) arg</N:1> System.Console.WriteLine(3) End Sub End Class ") Dim compilation0 = CreateCompilationWithMscorlib40({source0.Tree}, options:=ComSafeDebugDll) Dim compilation1 = compilation0.WithSource(source1.Tree) Dim compilation2 = compilation1.WithSource(source2.Tree) Dim v0 = CompileAndVerify(compilation0) v0.VerifyIL("C.F", " { // Code size 46 (0x2e) .maxstack 2 .locals init (VB$AnonymousDelegate_0(Of String, String) V_0) //g IL_0000: nop IL_0001: ldsfld ""C._Closure$__.$I1-0 As <generated method>"" IL_0006: brfalse.s IL_000f IL_0008: ldsfld ""C._Closure$__.$I1-0 As <generated method>"" IL_000d: br.s IL_0025 IL_000f: ldsfld ""C._Closure$__.$I As C._Closure$__"" IL_0014: ldftn ""Function C._Closure$__._Lambda$__1-0(ByRef String) As String"" IL_001a: newobj ""Sub VB$AnonymousDelegate_0(Of String, String)..ctor(Object, System.IntPtr)"" IL_001f: dup IL_0020: stsfld ""C._Closure$__.$I1-0 As <generated method>"" IL_0025: stloc.0 IL_0026: ldc.i4.1 IL_0027: call ""Sub System.Console.WriteLine(Integer)"" IL_002c: nop IL_002d: ret } ") Dim md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData) Dim generation0 = EmitBaseline.CreateInitialBaseline(md0, AddressOf v0.CreateSymReader().GetEncMethodDebugInfo) Dim f0 = compilation0.GetMember(Of MethodSymbol)("C.F") Dim f1 = compilation1.GetMember(Of MethodSymbol)("C.F") Dim f2 = compilation2.GetMember(Of MethodSymbol)("C.F") Dim diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(New SemanticEdit(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables:=True))) diff1.VerifyIL("C.F", " { // Code size 46 (0x2e) .maxstack 2 .locals init (VB$AnonymousDelegate_0(Of String, String) V_0) //g IL_0000: nop IL_0001: ldsfld ""C._Closure$__.$I1-0 As <generated method>"" IL_0006: brfalse.s IL_000f IL_0008: ldsfld ""C._Closure$__.$I1-0 As <generated method>"" IL_000d: br.s IL_0025 IL_000f: ldsfld ""C._Closure$__.$I As C._Closure$__"" IL_0014: ldftn ""Function C._Closure$__._Lambda$__1-0(ByRef String) As String"" IL_001a: newobj ""Sub VB$AnonymousDelegate_0(Of String, String)..ctor(Object, System.IntPtr)"" IL_001f: dup IL_0020: stsfld ""C._Closure$__.$I1-0 As <generated method>"" IL_0025: stloc.0 IL_0026: ldc.i4.2 IL_0027: call ""Sub System.Console.WriteLine(Integer)"" IL_002c: nop IL_002d: ret } ") Dim diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create(New SemanticEdit(SemanticEditKind.Update, f1, f2, GetSyntaxMapFromMarkers(source1, source2), preserveLocalVariables:=True))) diff2.VerifyIL("C.F", " { // Code size 46 (0x2e) .maxstack 2 .locals init (VB$AnonymousDelegate_0(Of String, String) V_0) //g IL_0000: nop IL_0001: ldsfld ""C._Closure$__.$I1-0 As <generated method>"" IL_0006: brfalse.s IL_000f IL_0008: ldsfld ""C._Closure$__.$I1-0 As <generated method>"" IL_000d: br.s IL_0025 IL_000f: ldsfld ""C._Closure$__.$I As C._Closure$__"" IL_0014: ldftn ""Function C._Closure$__._Lambda$__1-0(ByRef String) As String"" IL_001a: newobj ""Sub VB$AnonymousDelegate_0(Of String, String)..ctor(Object, System.IntPtr)"" IL_001f: dup IL_0020: stsfld ""C._Closure$__.$I1-0 As <generated method>"" IL_0025: stloc.0 IL_0026: ldc.i4.3 IL_0027: call ""Sub System.Console.WriteLine(Integer)"" IL_002c: nop IL_002d: ret } ") End Sub ''' <summary> ''' Should not re-use locals with custom modifiers. ''' </summary> <Fact(Skip:="9854")> <WorkItem(9854, "https://github.com/dotnet/roslyn/issues/9854")> Public Sub LocalType_CustomModifiers() ' Equivalent method signature to VB, but ' with optional modifiers on locals. Dim ilSource = <![CDATA[ .assembly extern mscorlib { .ver 4:0:0:0 .publickeytoken = (B7 7A 5C 56 19 34 E0 89) } .assembly '<<GeneratedFileName>>' { } .class public C { .method public specialname rtspecialname instance void .ctor() { ret } .method public static object F(class [mscorlib]System.IDisposable d) { .locals init ([0] object F, [1] class C modopt(int32) c, [2] class [mscorlib]System.IDisposable modopt(object) VB$Using, [3] bool V_3) ldnull ret } } ]]>.Value Dim source = <compilation> <file name="c.vb"><![CDATA[ Class C Shared Function F(d As System.IDisposable) As Object Dim c As C Using d c = DirectCast(d, C) End Using Return c End Function End Class ]]> </file> </compilation> Dim metadata0 = DirectCast(CompileIL(ilSource, prependDefaultHeader:=False), MetadataImageReference) ' Still need a compilation with source for the initial ' generation - to get a MethodSymbol and syntax map. Dim compilation0 = CreateCompilationWithMscorlib40(source, options:=TestOptions.DebugDll) Dim compilation1 = compilation0.Clone() Dim moduleMetadata0 = DirectCast(metadata0.GetMetadataNoCopy(), AssemblyMetadata).GetModules(0) Dim method0 = compilation0.GetMember(Of MethodSymbol)("C.F") Dim generation0 = EmitBaseline.CreateInitialBaseline( moduleMetadata0, Function(m) Nothing) Dim testData1 = New CompilationTestData() Dim method1 = compilation1.GetMember(Of MethodSymbol)("C.F") Dim edit = New SemanticEdit(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables:=True) Dim diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(edit)) diff1.VerifyIL("C.F", " { // Code size 45 (0x2d) .maxstack 2 .locals init ([object] V_0, [unchanged] V_1, [unchanged] V_2, [bool] V_3, Object V_4, //F C V_5, //c System.IDisposable V_6, //VB$Using Boolean V_7) IL_0000: nop IL_0001: nop IL_0002: ldarg.0 IL_0003: stloc.s V_6 .try { IL_0005: ldarg.0 IL_0006: castclass ""C"" IL_000b: stloc.s V_5 IL_000d: leave.s IL_0024 } finally { IL_000f: nop IL_0010: ldloc.s V_6 IL_0012: ldnull IL_0013: ceq IL_0015: stloc.s V_7 IL_0017: ldloc.s V_7 IL_0019: brtrue.s IL_0023 IL_001b: ldloc.s V_6 IL_001d: callvirt ""Sub System.IDisposable.Dispose()"" IL_0022: nop IL_0023: endfinally } IL_0024: ldloc.s V_5 IL_0026: stloc.s V_4 IL_0028: br.s IL_002a IL_002a: ldloc.s V_4 IL_002c: ret } ") End Sub <WorkItem(839414, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/839414")> <Fact> Public Sub Bug839414() Dim source0 = <compilation> <file name="a.vb"> Module M Function F() As Object Static x = 1 Return x End Function End Module </file> </compilation> Dim source1 = <compilation> <file name="a.vb"> Module M Function F() As Object Static x = "2" Return x End Function End Module </file> </compilation> Dim compilation0 = CreateCompilationWithMscorlib40AndVBRuntime(source0, TestOptions.DebugDll) Dim compilation1 = compilation0.WithSource(source1) Dim bytes0 = compilation0.EmitToArray() Dim method0 = compilation0.GetMember(Of MethodSymbol)("M.F") Dim method1 = compilation1.GetMember(Of MethodSymbol)("M.F") Dim generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), EmptyLocalsProvider) compilation1.EmitDifference( generation0, ImmutableArray.Create(New SemanticEdit(SemanticEditKind.Update, method0, method1))) End Sub <WorkItem(849649, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/849649")> <Fact> Public Sub Bug849649() Dim source0 = <compilation> <file name="a.vb"> Module M Sub F() Dim x(5) As Integer x(3) = 2 End Sub End Module </file> </compilation> Dim source1 = <compilation> <file name="a.vb"> Module M Sub F() Dim x(5) As Integer x(3) = 3 End Sub End Module </file> </compilation> Dim compilation0 = CreateCompilationWithMscorlib40AndVBRuntime(source0, TestOptions.DebugDll) Dim compilation1 = compilation0.WithSource(source1) Dim bytes0 = compilation0.EmitToArray() Dim method0 = compilation0.GetMember(Of MethodSymbol)("M.F") Dim method1 = compilation1.GetMember(Of MethodSymbol)("M.F") Dim generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), EmptyLocalsProvider) Dim diff0 = compilation1.EmitDifference( generation0, ImmutableArray.Create(New SemanticEdit(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables:=True))) diff0.VerifyIL(" { // Code size 13 (0xd) .maxstack 3 IL_0000: nop IL_0001: ldc.i4.6 IL_0002: newarr 0x0100000A IL_0007: stloc.1 IL_0008: ldloc.1 IL_0009: ldc.i4.3 IL_000a: ldc.i4.3 IL_000b: stelem.i4 IL_000c: ret } ") End Sub #End Region <ConditionalFact(GetType(WindowsOnly), Reason:=ConditionalSkipReason.NativePdbRequiresDesktop)> Public Sub SymWriterErrors() Dim source0 = <compilation> <file name="a.vb"><![CDATA[ Class C End Class ]]></file> </compilation> Dim source1 = <compilation> <file name="a.vb"><![CDATA[ Class C Sub Main() End Sub End Class ]]></file> </compilation> Dim compilation0 = CreateCompilationWithMscorlib40(source0, options:=TestOptions.DebugDll) Dim compilation1 = compilation0.WithSource(source1) ' Verify full metadata contains expected rows. Dim bytes0 = compilation0.EmitToArray() Using md0 = ModuleMetadata.CreateFromImage(bytes0) Dim diff1 = compilation1.EmitDifference( EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider), ImmutableArray.Create(New SemanticEdit(SemanticEditKind.Insert, Nothing, compilation1.GetMember(Of MethodSymbol)("C.Main"))), testData:=New CompilationTestData With {.SymWriterFactory = Function() New MockSymUnmanagedWriter()}) diff1.EmitResult.Diagnostics.Verify( Diagnostic(ERRID.ERR_PDBWritingFailed).WithArguments("MockSymUnmanagedWriter error message")) Assert.False(diff1.EmitResult.Success) End Using End Sub <WorkItem(1003274, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1003274")> <Fact> Public Sub ConditionalAttribute() Const source0 = " Imports System.Diagnostics Class C Sub M() ' Body End Sub <Conditional(""Defined"")> Sub N1() End Sub <Conditional(""Undefined"")> Sub N2() End Sub End Class " Dim parseOptions As New VisualBasicParseOptions(preprocessorSymbols:={New KeyValuePair(Of String, Object)("Defined", True)}) Dim tree0 = VisualBasicSyntaxTree.ParseText(source0, parseOptions) Dim tree1 = VisualBasicSyntaxTree.ParseText(source0.Replace("' Body", "N1(): N2()"), parseOptions) Dim compilation0 = CreateCompilationWithMscorlib40({tree0}, options:=TestOptions.DebugDll) Dim compilation1 = compilation0.ReplaceSyntaxTree(tree0, tree1) Dim bytes0 = compilation0.EmitToArray() Using md0 = ModuleMetadata.CreateFromImage(bytes0) Dim reader0 = md0.MetadataReader Dim method0 = compilation0.GetMember(Of MethodSymbol)("C.M") Dim method1 = compilation1.GetMember(Of MethodSymbol)("C.M") Dim generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), EmptyLocalsProvider) Dim diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(New SemanticEdit(SemanticEditKind.Update, method0, method1))) diff1.EmitResult.Diagnostics.AssertNoErrors() diff1.VerifyIL("C.M", " { // Code size 9 (0x9) .maxstack 1 IL_0000: nop IL_0001: ldarg.0 IL_0002: call ""Sub C.N1()"" IL_0007: nop IL_0008: ret } ") End Using End Sub <Fact> Public Sub ReferenceToMemberAddedToAnotherAssembly1() Dim sourceA0 = " Public Class A End Class " Dim sourceA1 = " Public Class A Public Sub M() System.Console.WriteLine(1) End Sub End Class Public Class X End Class " Dim sourceB0 = " Public Class B Public Shared Sub F() End Sub End Class" Dim sourceB1 = " Public Class B Public Shared Sub F() Dim a = New A() a.M() End Sub End Class Public Class Y Inherits X End Class " Dim compilationA0 = CreateCompilationWithMscorlib40({sourceA0}, options:=TestOptions.DebugDll, assemblyName:="LibA") Dim compilationA1 = compilationA0.WithSource(sourceA1) Dim compilationB0 = CreateCompilationWithMscorlib40({sourceB0}, {compilationA0.ToMetadataReference()}, options:=TestOptions.DebugDll, assemblyName:="LibB") Dim compilationB1 = CreateCompilationWithMscorlib40({sourceB1}, {compilationA1.ToMetadataReference()}, options:=TestOptions.DebugDll, assemblyName:="LibB") Dim bytesA0 = compilationA0.EmitToArray() Dim bytesB0 = compilationB0.EmitToArray() Dim mdA0 = ModuleMetadata.CreateFromImage(bytesA0) Dim mdB0 = ModuleMetadata.CreateFromImage(bytesB0) Dim generationA0 = EmitBaseline.CreateInitialBaseline(mdA0, EmptyLocalsProvider) Dim generationB0 = EmitBaseline.CreateInitialBaseline(mdB0, EmptyLocalsProvider) Dim mA1 = compilationA1.GetMember(Of MethodSymbol)("A.M") Dim mX1 = compilationA1.GetMember(Of TypeSymbol)("X") Dim allAddedSymbols = New ISymbol() {mA1, mX1} Dim diffA1 = compilationA1.EmitDifference( generationA0, ImmutableArray.Create( New SemanticEdit(SemanticEditKind.Insert, Nothing, mA1), New SemanticEdit(SemanticEditKind.Insert, Nothing, mX1)), allAddedSymbols) diffA1.EmitResult.Diagnostics.Verify() Dim diffB1 = compilationB1.EmitDifference( generationB0, ImmutableArray.Create( New SemanticEdit(SemanticEditKind.Update, compilationB0.GetMember(Of MethodSymbol)("B.F"), compilationB1.GetMember(Of MethodSymbol)("B.F")), New SemanticEdit(SemanticEditKind.Insert, Nothing, compilationB1.GetMember(Of TypeSymbol)("Y"))), allAddedSymbols) diffB1.EmitResult.Diagnostics.Verify( Diagnostic(ERRID.ERR_EncReferenceToAddedMember, "X").WithArguments("X", "LibA").WithLocation(8, 14), Diagnostic(ERRID.ERR_EncReferenceToAddedMember, "M").WithArguments("M", "LibA").WithLocation(3, 16)) End Sub <Fact> Public Sub ReferenceToMemberAddedToAnotherAssembly2() Dim sourceA = " Public Class A Public Sub M() End Sub End Class" Dim sourceB0 = " Public Class B Public Shared Sub F() Dim a = New A() End Sub End Class" Dim sourceB1 = " Public Class B Public Shared Sub F() Dim a = New A() a.M() End Sub End Class" Dim sourceB2 = " Public Class B Public Shared Sub F() Dim a = New A() End Sub End Class" Dim compilationA = CreateCompilationWithMscorlib40({sourceA}, options:=TestOptions.DebugDll, assemblyName:="AssemblyA") Dim aRef = compilationA.ToMetadataReference() Dim compilationB0 = CreateCompilationWithMscorlib40({sourceB0}, {aRef}, options:=TestOptions.DebugDll, assemblyName:="AssemblyB") Dim compilationB1 = compilationB0.WithSource(sourceB1) Dim compilationB2 = compilationB1.WithSource(sourceB2) Dim testDataB0 = New CompilationTestData() Dim bytesB0 = compilationB0.EmitToArray(testData:=testDataB0) Dim mdB0 = ModuleMetadata.CreateFromImage(bytesB0) Dim generationB0 = EmitBaseline.CreateInitialBaseline(mdB0, testDataB0.GetMethodData("B.F").EncDebugInfoProvider()) Dim f0 = compilationB0.GetMember(Of MethodSymbol)("B.F") Dim f1 = compilationB1.GetMember(Of MethodSymbol)("B.F") Dim f2 = compilationB2.GetMember(Of MethodSymbol)("B.F") Dim diffB1 = compilationB1.EmitDifference( generationB0, ImmutableArray.Create(New SemanticEdit(SemanticEditKind.Update, f0, f1, GetEquivalentNodesMap(f1, f0), preserveLocalVariables:=True))) diffB1.VerifyIL("B.F", " { // Code size 15 (0xf) .maxstack 1 .locals init (A V_0) //a IL_0000: nop IL_0001: newobj ""Sub A..ctor()"" IL_0006: stloc.0 IL_0007: ldloc.0 IL_0008: callvirt ""Sub A.M()"" IL_000d: nop IL_000e: ret } ") Dim diffB2 = compilationB2.EmitDifference( diffB1.NextGeneration, ImmutableArray.Create(New SemanticEdit(SemanticEditKind.Update, f1, f2, GetEquivalentNodesMap(f2, f1), preserveLocalVariables:=True))) diffB2.VerifyIL("B.F", " { // Code size 8 (0x8) .maxstack 1 .locals init (A V_0) //a IL_0000: nop IL_0001: newobj ""Sub A..ctor()"" IL_0006: stloc.0 IL_0007: ret } ") End Sub <Fact> Public Sub ForStatement() Dim source0 = MarkedSource(" Imports System Class C Sub F() <N:0><N:1>For a = G(0) To G(1) Step G(2)</N:1> Console.WriteLine(1) Next</N:0> End Sub Function G(a As Integer) As Integer Return 10 End Function End Class ") Dim source1 = MarkedSource(" Imports System Class C Sub F() <N:0><N:1>For a = G(0) To G(1) Step G(2)</N:1> Console.WriteLine(2) Next</N:0> End Sub Function G(a As Integer) As Integer Return 10 End Function End Class ") Dim compilation0 = CreateCompilationWithMscorlib40(source0.Tree, {MsvbRef}, ComSafeDebugDll) Dim compilation1 = compilation0.WithSource(source1.Tree) Dim v0 = CompileAndVerify(compilation0) Dim md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData) Dim generation0 = EmitBaseline.CreateInitialBaseline(md0, AddressOf v0.CreateSymReader().GetEncMethodDebugInfo) Dim f0 = compilation0.GetMember(Of MethodSymbol)("C.F") Dim f1 = compilation1.GetMember(Of MethodSymbol)("C.F") Dim diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(New SemanticEdit(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables:=True))) Dim md1 = diff1.GetMetadata() Dim reader1 = md1.Reader v0.VerifyIL("C.F", " { // Code size 55 (0x37) .maxstack 3 .locals init (Integer V_0, Integer V_1, Integer V_2, Integer V_3) //a IL_0000: nop IL_0001: ldarg.0 IL_0002: ldc.i4.0 IL_0003: call ""Function C.G(Integer) As Integer"" IL_0008: stloc.0 IL_0009: ldarg.0 IL_000a: ldc.i4.1 IL_000b: call ""Function C.G(Integer) As Integer"" IL_0010: stloc.1 IL_0011: ldarg.0 IL_0012: ldc.i4.2 IL_0013: call ""Function C.G(Integer) As Integer"" IL_0018: stloc.2 IL_0019: ldloc.0 IL_001a: stloc.3 IL_001b: br.s IL_0028 IL_001d: ldc.i4.1 IL_001e: call ""Sub System.Console.WriteLine(Integer)"" IL_0023: nop IL_0024: ldloc.3 IL_0025: ldloc.2 IL_0026: add.ovf IL_0027: stloc.3 IL_0028: ldloc.2 IL_0029: ldc.i4.s 31 IL_002b: shr IL_002c: ldloc.3 IL_002d: xor IL_002e: ldloc.2 IL_002f: ldc.i4.s 31 IL_0031: shr IL_0032: ldloc.1 IL_0033: xor IL_0034: ble.s IL_001d IL_0036: ret } ") ' Note that all variables are mapped to their previous slots diff1.VerifyIL("C.F", " { // Code size 55 (0x37) .maxstack 3 .locals init (Integer V_0, Integer V_1, Integer V_2, Integer V_3) //a IL_0000: nop IL_0001: ldarg.0 IL_0002: ldc.i4.0 IL_0003: call ""Function C.G(Integer) As Integer"" IL_0008: stloc.0 IL_0009: ldarg.0 IL_000a: ldc.i4.1 IL_000b: call ""Function C.G(Integer) As Integer"" IL_0010: stloc.1 IL_0011: ldarg.0 IL_0012: ldc.i4.2 IL_0013: call ""Function C.G(Integer) As Integer"" IL_0018: stloc.2 IL_0019: ldloc.0 IL_001a: stloc.3 IL_001b: br.s IL_0028 IL_001d: ldc.i4.2 IL_001e: call ""Sub System.Console.WriteLine(Integer)"" IL_0023: nop IL_0024: ldloc.3 IL_0025: ldloc.2 IL_0026: add.ovf IL_0027: stloc.3 IL_0028: ldloc.2 IL_0029: ldc.i4.s 31 IL_002b: shr IL_002c: ldloc.3 IL_002d: xor IL_002e: ldloc.2 IL_002f: ldc.i4.s 31 IL_0031: shr IL_0032: ldloc.1 IL_0033: xor IL_0034: ble.s IL_001d IL_0036: ret } ") End Sub <Fact> Public Sub ForStatement_LateBound() Dim source0 = MarkedSource(" Option Strict On Public Class C Public Shared Sub F() Dim <N:0>a</N:0> As Object = 0 Dim <N:1>b</N:1> As Object = 0 Dim <N:2>c</N:2> As Object = 0 Dim <N:3>d</N:3> As Object = 0 <N:4>For a = b To c Step d System.Console.Write(a) Next</N:4> End Sub End Class") Dim source1 = MarkedSource(" Option Strict On Public Class C Public Shared Sub F() Dim <N:0>a</N:0> As Object = 0 Dim <N:1>b</N:1> As Object = 0 Dim <N:2>c</N:2> As Object = 0 Dim <N:3>d</N:3> As Object = 0 <N:4>For a = b To c Step d System.Console.WriteLine(a) Next</N:4> End Sub End Class") Dim compilation0 = CreateCompilationWithMscorlib40(source0.Tree, {MsvbRef}, ComSafeDebugDll) Dim compilation1 = compilation0.WithSource(source1.Tree) Dim v0 = CompileAndVerify(compilation0) Dim md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData) Dim generation0 = EmitBaseline.CreateInitialBaseline(md0, AddressOf v0.CreateSymReader().GetEncMethodDebugInfo) Dim f0 = compilation0.GetMember(Of MethodSymbol)("C.F") Dim f1 = compilation1.GetMember(Of MethodSymbol)("C.F") Dim diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(New SemanticEdit(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables:=True))) Dim md1 = diff1.GetMetadata() Dim reader1 = md1.Reader v0.VerifyIL("C.F", " { // Code size 77 (0x4d) .maxstack 6 .locals init (Object V_0, //a Object V_1, //b Object V_2, //c Object V_3, //d Object V_4, Boolean V_5, Boolean V_6) IL_0000: nop IL_0001: ldc.i4.0 IL_0002: box ""Integer"" IL_0007: stloc.0 IL_0008: ldc.i4.0 IL_0009: box ""Integer"" IL_000e: stloc.1 IL_000f: ldc.i4.0 IL_0010: box ""Integer"" IL_0015: stloc.2 IL_0016: ldc.i4.0 IL_0017: box ""Integer"" IL_001c: stloc.3 IL_001d: ldloc.0 IL_001e: ldloc.1 IL_001f: ldloc.2 IL_0020: ldloc.3 IL_0021: ldloca.s V_4 IL_0023: ldloca.s V_0 IL_0025: call ""Function Microsoft.VisualBasic.CompilerServices.ObjectFlowControl.ForLoopControl.ForLoopInitObj(Object, Object, Object, Object, ByRef Object, ByRef Object) As Boolean"" IL_002a: stloc.s V_5 IL_002c: ldloc.s V_5 IL_002e: brfalse.s IL_004c IL_0030: ldloc.0 IL_0031: call ""Function System.Runtime.CompilerServices.RuntimeHelpers.GetObjectValue(Object) As Object"" IL_0036: call ""Sub System.Console.Write(Object)"" IL_003b: nop IL_003c: ldloc.0 IL_003d: ldloc.s V_4 IL_003f: ldloca.s V_0 IL_0041: call ""Function Microsoft.VisualBasic.CompilerServices.ObjectFlowControl.ForLoopControl.ForNextCheckObj(Object, Object, ByRef Object) As Boolean"" IL_0046: stloc.s V_6 IL_0048: ldloc.s V_6 IL_004a: brtrue.s IL_0030 IL_004c: ret } ") ' Note that all variables are mapped to their previous slots diff1.VerifyIL("C.F", " { // Code size 77 (0x4d) .maxstack 6 .locals init (Object V_0, //a Object V_1, //b Object V_2, //c Object V_3, //d Object V_4, Boolean V_5, Boolean V_6) IL_0000: nop IL_0001: ldc.i4.0 IL_0002: box ""Integer"" IL_0007: stloc.0 IL_0008: ldc.i4.0 IL_0009: box ""Integer"" IL_000e: stloc.1 IL_000f: ldc.i4.0 IL_0010: box ""Integer"" IL_0015: stloc.2 IL_0016: ldc.i4.0 IL_0017: box ""Integer"" IL_001c: stloc.3 IL_001d: ldloc.0 IL_001e: ldloc.1 IL_001f: ldloc.2 IL_0020: ldloc.3 IL_0021: ldloca.s V_4 IL_0023: ldloca.s V_0 IL_0025: call ""Function Microsoft.VisualBasic.CompilerServices.ObjectFlowControl.ForLoopControl.ForLoopInitObj(Object, Object, Object, Object, ByRef Object, ByRef Object) As Boolean"" IL_002a: stloc.s V_5 IL_002c: ldloc.s V_5 IL_002e: brfalse.s IL_004c IL_0030: ldloc.0 IL_0031: call ""Function System.Runtime.CompilerServices.RuntimeHelpers.GetObjectValue(Object) As Object"" IL_0036: call ""Sub System.Console.WriteLine(Object)"" IL_003b: nop IL_003c: ldloc.0 IL_003d: ldloc.s V_4 IL_003f: ldloca.s V_0 IL_0041: call ""Function Microsoft.VisualBasic.CompilerServices.ObjectFlowControl.ForLoopControl.ForNextCheckObj(Object, Object, ByRef Object) As Boolean"" IL_0046: stloc.s V_6 IL_0048: ldloc.s V_6 IL_004a: brtrue.s IL_0030 IL_004c: ret } ") End Sub <Fact> Public Sub AddImports_AmbiguousCode() Dim source0 = MarkedSource(" Imports System.Threading Class C Shared Sub E() Dim t = New Timer(Sub(s) System.Console.WriteLine(s)) End Sub End Class ") Dim source1 = MarkedSource(" Imports System.Threading Imports System.Timers Class C Shared Sub E() Dim t = New Timer(Sub(s) System.Console.WriteLine(s)) End Sub Shared Sub G() System.Console.WriteLine(new TimersDescriptionAttribute("""")) End Sub End Class ") Dim compilation0 = CreateCompilation(source0.Tree, targetFramework:=TargetFramework.NetStandard20, options:=ComSafeDebugDll) Dim compilation1 = compilation0.WithSource(source1.Tree) Dim e0 = compilation0.GetMember(Of MethodSymbol)("C.E") Dim e1 = compilation1.GetMember(Of MethodSymbol)("C.E") Dim g1 = compilation1.GetMember(Of MethodSymbol)("C.G") Dim v0 = CompileAndVerify(compilation0) Dim md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData) Dim generation0 = EmitBaseline.CreateInitialBaseline(md0, AddressOf v0.CreateSymReader().GetEncMethodDebugInfo) ' Pretend there was an update to C.E to ensure we haven't invalidated the test Dim diffError = compilation1.EmitDifference( generation0, ImmutableArray.Create(New SemanticEdit(SemanticEditKind.Update, e0, e1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables:=True))) diffError.EmitResult.Diagnostics.Verify( Diagnostic(ERRID.ERR_AmbiguousInImports2, "Timer").WithArguments("Timer", "System.Threading, System.Timers").WithLocation(7, 21)) Dim diff = compilation1.EmitDifference( generation0, ImmutableArray.Create(New SemanticEdit(SemanticEditKind.Insert, Nothing, g1))) diff.EmitResult.Diagnostics.Verify() diff.VerifyIL("C.G", " { // Code size 18 (0x12) .maxstack 1 IL_0000: nop IL_0001: ldstr """" IL_0006: newobj ""Sub System.Timers.TimersDescriptionAttribute..ctor(String)"" IL_000b: call ""Sub System.Console.WriteLine(Object)"" IL_0010: nop IL_0011: ret }") End Sub End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable Imports System.IO Imports System.Reflection.Metadata Imports System.Reflection.Metadata.Ecma335 Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.CodeGen Imports Microsoft.CodeAnalysis.Emit Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.CodeAnalysis.VisualBasic.Emit Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Roslyn.Test.MetadataUtilities Imports Roslyn.Test.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests Public Class EditAndContinueTests Inherits EditAndContinueTestBase <Fact> Public Sub SemanticErrors_MethodBody() Dim source0 = MarkedSource(" Class C Shared Sub E() Dim x As Integer = 1 System.Console.WriteLine(x) End Sub Shared Sub G() System.Console.WriteLine(1) End Sub End Class ") Dim source1 = MarkedSource(" Class C Shared Sub E() Dim x = Unknown(2) System.Console.WriteLine(x) End Sub Shared Sub G() System.Console.WriteLine(2) End Sub End Class ") Dim compilation0 = CreateCompilationWithMscorlib40(source0.Tree, options:=ComSafeDebugDll) Dim compilation1 = compilation0.WithSource(source1.Tree) Dim e0 = compilation0.GetMember(Of MethodSymbol)("C.E") Dim e1 = compilation1.GetMember(Of MethodSymbol)("C.E") Dim g0 = compilation0.GetMember(Of MethodSymbol)("C.G") Dim g1 = compilation1.GetMember(Of MethodSymbol)("C.G") Dim v0 = CompileAndVerify(compilation0) Dim md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData) Dim generation0 = EmitBaseline.CreateInitialBaseline(md0, AddressOf v0.CreateSymReader().GetEncMethodDebugInfo) ' Semantic errors are reported only for the bodies of members being emitted. Dim diffError = compilation1.EmitDifference( generation0, ImmutableArray.Create(New SemanticEdit(SemanticEditKind.Update, e0, e1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables:=True))) diffError.EmitResult.Diagnostics.Verify( Diagnostic(ERRID.ERR_NameNotDeclared1, "Unknown").WithArguments("Unknown").WithLocation(4, 17)) Dim diffGood = compilation1.EmitDifference( generation0, ImmutableArray.Create(New SemanticEdit(SemanticEditKind.Update, g0, g1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables:=True))) diffGood.EmitResult.Diagnostics.Verify() diffGood.VerifyIL("C.G", " { // Code size 9 (0x9) .maxstack 1 IL_0000: nop IL_0001: ldc.i4.2 IL_0002: call ""Sub System.Console.WriteLine(Integer)"" IL_0007: nop IL_0008: ret }") End Sub <Fact> Public Sub SemanticErrors_Declaration() Dim source0 = MarkedSource(" Class C Sub G() System.Console.WriteLine(1) End Sub End Class ") Dim source1 = MarkedSource(" Class C Sub G() System.Console.WriteLine(1) End Sub End Class Class Bad Inherits Bad End Class ") Dim compilation0 = CreateCompilationWithMscorlib40(source0.Tree, options:=ComSafeDebugDll) Dim compilation1 = compilation0.WithSource(source1.Tree) Dim g0 = compilation0.GetMember(Of MethodSymbol)("C.G") Dim g1 = compilation1.GetMember(Of MethodSymbol)("C.G") Dim v0 = CompileAndVerify(compilation0) Dim md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData) Dim generation0 = EmitBaseline.CreateInitialBaseline(md0, AddressOf v0.CreateSymReader().GetEncMethodDebugInfo) Dim diff = compilation1.EmitDifference( generation0, ImmutableArray.Create(New SemanticEdit(SemanticEditKind.Update, g0, g1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables:=True))) diff.EmitResult.Diagnostics.Verify( Diagnostic(ERRID.ERR_TypeInItsInheritsClause1, "Bad").WithArguments("Bad").WithLocation(9, 12)) End Sub <Fact> Public Sub ModifyMethod_WithTuples() Dim source0 = " Class C Shared Sub Main End Sub Shared Function F() As (Integer, Integer) Return (1, 2) End Function End Class " Dim source1 = " Class C Shared Sub Main End Sub Shared Function F() As (Integer, Integer) Return (2, 3) End Function End Class " Dim compilation0 = CreateCompilationWithMscorlib40({source0}, options:=TestOptions.DebugExe, references:={ValueTupleRef, SystemRuntimeFacadeRef}) Dim compilation1 = compilation0.WithSource(source1) Dim bytes0 = compilation0.EmitToArray() Using md0 = ModuleMetadata.CreateFromImage(bytes0) Dim reader0 = md0.MetadataReader Dim method0 = compilation0.GetMember(Of MethodSymbol)("C.F") Dim generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider) Dim method1 = compilation1.GetMember(Of MethodSymbol)("C.F") Dim diff1 = compilation1.EmitDifference(generation0, ImmutableArray.Create(New SemanticEdit(SemanticEditKind.Update, method0, method1))) ' Verify delta metadata contains expected rows. Using md1 = diff1.GetMetadata() Dim reader1 = md1.Reader Dim readers = {reader0, reader1} EncValidation.VerifyModuleMvid(1, reader0, reader1) CheckNames(readers, reader1.GetTypeDefNames()) CheckNames(readers, reader1.GetMethodDefNames(), "F") CheckNames(readers, reader1.GetMemberRefNames(), ".ctor") ' System.ValueTuple ctor CheckEncLog(reader1, Row(3, TableIndex.AssemblyRef, EditAndContinueOperation.Default), Row(4, TableIndex.AssemblyRef, EditAndContinueOperation.Default), Row(7, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(8, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(9, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(2, TableIndex.TypeSpec, EditAndContinueOperation.Default), Row(2, TableIndex.StandAloneSig, EditAndContinueOperation.Default), Row(3, TableIndex.MethodDef, EditAndContinueOperation.Default)) ' C.F CheckEncMap(reader1, Handle(8, TableIndex.TypeRef), Handle(9, TableIndex.TypeRef), Handle(3, TableIndex.MethodDef), Handle(7, TableIndex.MemberRef), Handle(2, TableIndex.StandAloneSig), Handle(2, TableIndex.TypeSpec), Handle(3, TableIndex.AssemblyRef), Handle(4, TableIndex.AssemblyRef)) End Using End Using End Sub <Fact> Public Sub ModifyMethod_RenameParameter() Dim source0 = " Class C Shared Function F(i As Integer) As Integer Return i End Function End Class " Dim source1 = " Class C Shared Function F(x As Integer) As Integer Return x End Function End Class " Dim compilation0 = CreateCompilationWithMscorlib40({source0}, options:=TestOptions.DebugDll, references:={ValueTupleRef, SystemRuntimeFacadeRef}) Dim compilation1 = compilation0.WithSource(source1) Dim bytes0 = compilation0.EmitToArray() Using md0 = ModuleMetadata.CreateFromImage(bytes0) Dim reader0 = md0.MetadataReader Dim method0 = compilation0.GetMember(Of MethodSymbol)("C.F") Dim generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider) CheckNames(reader0, reader0.GetParameterDefNames(), "i") Dim method1 = compilation1.GetMember(Of MethodSymbol)("C.F") Dim diff1 = compilation1.EmitDifference(generation0, ImmutableArray.Create(New SemanticEdit(SemanticEditKind.Update, method0, method1))) ' Verify delta metadata contains expected rows. Using md1 = diff1.GetMetadata() Dim reader1 = md1.Reader Dim readers = {reader0, reader1} EncValidation.VerifyModuleMvid(1, reader0, reader1) CheckNames(readers, reader1.GetTypeDefNames()) CheckNames(readers, reader1.GetMethodDefNames(), "F") CheckNames(readers, reader1.GetParameterDefNames(), "x") CheckEncLogDefinitions(reader1, Row(2, TableIndex.StandAloneSig, EditAndContinueOperation.Default), Row(2, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(1, TableIndex.Param, EditAndContinueOperation.Default)) CheckEncMapDefinitions(reader1, Handle(2, TableIndex.MethodDef), Handle(1, TableIndex.Param), Handle(2, TableIndex.StandAloneSig)) End Using End Using End Sub <WorkItem(962219, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/962219")> <Fact> Public Sub PartialMethod() Dim source = <compilation> <file name="a.vb"> Partial Class C Private Shared Partial Sub M1() End Sub Private Shared Partial Sub M2() End Sub Private Shared Partial Sub M3() End Sub Private Shared Sub M1() End Sub Private Shared Sub M2() End Sub End Class </file> </compilation> Dim compilation0 = CreateCompilationWithMscorlib40AndVBRuntime(source, TestOptions.DebugDll) Dim compilation1 = compilation0.Clone() Dim bytes0 = compilation0.EmitToArray() Using md0 = ModuleMetadata.CreateFromImage(bytes0) Dim reader0 = md0.MetadataReader CheckNames(reader0, reader0.GetMethodDefNames(), ".ctor", "M1", "M2") Dim method0 = compilation0.GetMember(Of MethodSymbol)("C.M2").PartialImplementationPart Dim method1 = compilation1.GetMember(Of MethodSymbol)("C.M2").PartialImplementationPart Dim generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), EmptyLocalsProvider) Dim diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(New SemanticEdit(SemanticEditKind.Update, method0, method1))) Dim methods = diff1.TestData.GetMethodsByName() Assert.Equal(methods.Count, 1) Assert.True(methods.ContainsKey("C.M2()")) Using md1 = diff1.GetMetadata() Dim reader1 = md1.Reader Dim readers = {reader0, reader1} CheckNames(readers, reader1.GetMethodDefNames(), "M2") CheckEncLog(reader1, Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default), Row(6, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(3, TableIndex.MethodDef, EditAndContinueOperation.Default)) CheckEncMap(reader1, Handle(6, TableIndex.TypeRef), Handle(3, TableIndex.MethodDef), Handle(2, TableIndex.AssemblyRef)) End Using End Using End Sub <Fact> Public Sub AddThenModifyExplicitImplementation() Dim source0 = <compilation> <file name="a.vb"> Interface I(Of T) Sub M() End Interface </file> </compilation> Dim source1 = <compilation> <file name="a.vb"> Interface I(Of T) Sub M() End Interface Class A Implements I(Of Integer), I(Of Object) Public Sub New() End Sub Sub M() Implements I(Of Integer).M, I(Of Object).M End Sub End Class </file> </compilation> Dim source2 = source1 Dim source3 = <compilation> <file name="a.vb"> Interface I(Of T) Sub M() End Interface Class A Implements I(Of Integer), I(Of Object) Public Sub New() End Sub Sub M() Implements I(Of Integer).M, I(Of Object).M End Sub End Class Class B Implements I(Of Object) Public Sub New() End Sub Sub M() Implements I(Of Object).M End Sub End Class </file> </compilation> Dim compilation0 = CreateCompilationWithMscorlib40AndVBRuntime(source0, TestOptions.DebugDll) Dim compilation1 = compilation0.WithSource(source1) Dim compilation2 = compilation1.WithSource(source2) Dim compilation3 = compilation2.WithSource(source3) Dim bytes0 = compilation0.EmitToArray() Using md0 = ModuleMetadata.CreateFromImage(bytes0) Dim reader0 = md0.MetadataReader Dim type1 = compilation1.GetMember(Of NamedTypeSymbol)("A") Dim method1 = compilation1.GetMember(Of MethodSymbol)("A.M") Dim generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), EmptyLocalsProvider) Dim diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(New SemanticEdit(SemanticEditKind.Insert, Nothing, type1))) Using md1 = diff1.GetMetadata() Dim reader1 = md1.Reader Dim readers = {reader0, reader1} CheckNames(readers, reader1.GetMethodDefNames(), ".ctor", "M") CheckEncLog(reader1, Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default), Row(4, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(5, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(6, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(5, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(1, TableIndex.TypeSpec, EditAndContinueOperation.Default), Row(2, TableIndex.TypeSpec, EditAndContinueOperation.Default), Row(3, TableIndex.TypeDef, EditAndContinueOperation.Default), Row(3, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(2, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(3, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(3, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(1, TableIndex.MethodImpl, EditAndContinueOperation.Default), Row(2, TableIndex.MethodImpl, EditAndContinueOperation.Default), Row(1, TableIndex.InterfaceImpl, EditAndContinueOperation.Default), Row(2, TableIndex.InterfaceImpl, EditAndContinueOperation.Default)) CheckEncMap(reader1, Handle(5, TableIndex.TypeRef), Handle(3, TableIndex.TypeDef), Handle(2, TableIndex.MethodDef), Handle(3, TableIndex.MethodDef), Handle(1, TableIndex.InterfaceImpl), Handle(2, TableIndex.InterfaceImpl), Handle(4, TableIndex.MemberRef), Handle(5, TableIndex.MemberRef), Handle(6, TableIndex.MemberRef), Handle(1, TableIndex.MethodImpl), Handle(2, TableIndex.MethodImpl), Handle(1, TableIndex.TypeSpec), Handle(2, TableIndex.TypeSpec), Handle(2, TableIndex.AssemblyRef)) Dim generation1 = diff1.NextGeneration Dim method2 = compilation2.GetMember(Of MethodSymbol)("A.M") Dim diff2 = compilation2.EmitDifference( generation1, ImmutableArray.Create(New SemanticEdit(SemanticEditKind.Update, method1, method2))) Using md2 = diff2.GetMetadata() Dim reader2 = md2.Reader readers = {reader0, reader1, reader2} CheckNames(readers, reader2.GetMethodDefNames(), "M") CheckEncLog(reader2, Row(3, TableIndex.AssemblyRef, EditAndContinueOperation.Default), Row(6, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(3, TableIndex.TypeSpec, EditAndContinueOperation.Default), Row(4, TableIndex.TypeSpec, EditAndContinueOperation.Default), Row(3, TableIndex.MethodDef, EditAndContinueOperation.Default)) CheckEncMap(reader2, Handle(6, TableIndex.TypeRef), Handle(3, TableIndex.MethodDef), Handle(3, TableIndex.TypeSpec), Handle(4, TableIndex.TypeSpec), Handle(3, TableIndex.AssemblyRef)) Dim generation2 = diff2.NextGeneration Dim type3 = compilation3.GetMember(Of NamedTypeSymbol)("B") Dim diff3 = compilation3.EmitDifference( generation1, ImmutableArray.Create(New SemanticEdit(SemanticEditKind.Insert, Nothing, type3))) Using md3 = diff3.GetMetadata() Dim reader3 = md3.Reader readers = {reader0, reader1, reader3} CheckNames(readers, reader3.GetMethodDefNames(), ".ctor", "M") CheckEncLog(reader3, Row(3, TableIndex.AssemblyRef, EditAndContinueOperation.Default), Row(7, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(8, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(6, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(3, TableIndex.TypeSpec, EditAndContinueOperation.Default), Row(4, TableIndex.TypeDef, EditAndContinueOperation.Default), Row(4, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(4, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(4, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(5, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(3, TableIndex.MethodImpl, EditAndContinueOperation.Default), Row(3, TableIndex.InterfaceImpl, EditAndContinueOperation.Default)) CheckEncMap(reader3, Handle(6, TableIndex.TypeRef), Handle(4, TableIndex.TypeDef), Handle(4, TableIndex.MethodDef), Handle(5, TableIndex.MethodDef), Handle(3, TableIndex.InterfaceImpl), Handle(7, TableIndex.MemberRef), Handle(8, TableIndex.MemberRef), Handle(3, TableIndex.MethodImpl), Handle(3, TableIndex.TypeSpec), Handle(3, TableIndex.AssemblyRef)) End Using End Using End Using End Using End Sub <Fact, WorkItem(930065, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/930065")> Public Sub ModifyConstructorBodyInPresenceOfExplicitInterfaceImplementation() Dim source = <compilation> <file name="a.vb"> Interface I Sub M1() Sub M2() End Interface Class C Implements I Public Sub New() End Sub Sub M() Implements I.M1, I.M2 End Sub End Class </file> </compilation> Dim compilation0 = CreateCompilationWithMscorlib40AndVBRuntime(source, TestOptions.DebugDll) Dim compilation1 = compilation0.Clone() Dim bytes0 = compilation0.EmitToArray() Using md0 = ModuleMetadata.CreateFromImage(bytes0) Dim reader0 = md0.MetadataReader Dim method0 = compilation0.GetMember(Of NamedTypeSymbol)("C").InstanceConstructors.Single() Dim method1 = compilation1.GetMember(Of NamedTypeSymbol)("C").InstanceConstructors.Single() Dim generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), EmptyLocalsProvider) Dim diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(New SemanticEdit(SemanticEditKind.Update, method0, method1))) Using md1 = diff1.GetMetadata() Dim reader1 = md1.Reader Dim readers = {reader0, reader1} CheckNames(readers, reader1.GetTypeDefNames()) CheckNames(readers, reader1.GetMethodDefNames(), ".ctor") CheckEncLog(reader1, Row(2, TableIndex.AssemblyRef, EditAndContinueOperation.Default), Row(5, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(6, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(3, TableIndex.MethodDef, EditAndContinueOperation.Default)) CheckEncMap(reader1, Handle(6, TableIndex.TypeRef), Handle(3, TableIndex.MethodDef), Handle(5, TableIndex.MemberRef), Handle(2, TableIndex.AssemblyRef)) End Using End Using End Sub <Fact> Public Sub NamespacesAndOverloads() Dim compilation0 = CreateCompilationWithMscorlib40AndVBRuntime(options:=TestOptions.DebugDll, source:= <compilation> <file name="a.vb"><![CDATA[ Class C End Class Namespace N Class C End Class End Namespace Namespace M Class C Sub M1(o As N.C) End Sub Sub M1(o As M.C) End Sub Sub M2(a As N.C, b As M.C, c As Global.C) M1(a) End Sub End Class End Namespace ]]></file> </compilation>) Dim bytes = compilation0.EmitToArray() Dim generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes), EmptyLocalsProvider) Dim compilation1 = compilation0.WithSource( <compilation> <file name="a.vb"><![CDATA[ Class C End Class Namespace N Class C End Class End Namespace Namespace M Class C Sub M1(o As N.C) End Sub Sub M1(o As M.C) End Sub Sub M1(o As Global.C) End Sub Sub M2(a As N.C, b As M.C, c As Global.C) M1(a) M1(b) End Sub End Class End Namespace ]]></file> </compilation>) Dim diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(New SemanticEdit(SemanticEditKind.Insert, Nothing, compilation1.GetMembers("M.C.M1")(2)), New SemanticEdit(SemanticEditKind.Update, compilation0.GetMembers("M.C.M2")(0), compilation1.GetMembers("M.C.M2")(0)))) diff1.VerifyIL(" { // Code size 18 (0x12) .maxstack 8 IL_0000: nop IL_0001: ldarg.0 IL_0002: ldarg.1 IL_0003: call 0x06000004 IL_0008: nop IL_0009: ldarg.0 IL_000a: ldarg.2 IL_000b: call 0x06000005 IL_0010: nop IL_0011: ret } { // Code size 2 (0x2) .maxstack 8 IL_0000: nop IL_0001: ret } ") Dim compilation2 = compilation1.WithSource( <compilation> <file name="a.vb"><![CDATA[ Class C End Class Namespace N Class C End Class End Namespace Namespace M Class C Sub M1(o As N.C) End Sub Sub M1(o As M.C) End Sub Sub M1(o As Global.C) End Sub Sub M2(a As N.C, b As M.C, c As Global.C) M1(a) M1(b) M1(c) End Sub End Class End Namespace ]]></file> </compilation>) Dim diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create(New SemanticEdit(SemanticEditKind.Update, compilation1.GetMembers("M.C.M2")(0), compilation2.GetMembers("M.C.M2")(0)))) diff2.VerifyIL(" { // Code size 26 (0x1a) .maxstack 8 IL_0000: nop IL_0001: ldarg.0 IL_0002: ldarg.1 IL_0003: call 0x06000004 IL_0008: nop IL_0009: ldarg.0 IL_000a: ldarg.2 IL_000b: call 0x06000005 IL_0010: nop IL_0011: ldarg.0 IL_0012: ldarg.3 IL_0013: call 0x06000007 IL_0018: nop IL_0019: ret } ") End Sub <WorkItem(829353, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/829353")> <Fact()> Public Sub PrivateImplementationDetails_ArrayInitializer_FromMetadata() Dim sources0 = <compilation> <file name="a.vb"><![CDATA[ Class C Shared Sub M() Dim a As Integer() = {1, 2, 3} System.Console.Write(a(0)) End Sub End Class ]]></file> </compilation> Dim sources1 = <compilation> <file name="a.vb"><![CDATA[ Class C Shared Sub M() Dim a As Integer() = {1, 2, 3} System.Console.Write(a(1)) End Sub End Class ]]></file> </compilation> Dim compilation0 = CreateCompilationWithMscorlib40AndVBRuntime(sources0, TestOptions.DebugDll.WithModuleName("MODULE")) Dim compilation1 = compilation0.WithSource(sources1) Dim testData0 = New CompilationTestData() Dim bytes0 = compilation0.EmitToArray(testData:=testData0) Dim methodData0 = testData0.GetMethodData("C.M") methodData0.VerifyIL(" { // Code size 29 (0x1d) .maxstack 3 .locals init (Integer() V_0) //a IL_0000: nop IL_0001: ldc.i4.3 IL_0002: newarr ""Integer"" IL_0007: dup IL_0008: ldtoken ""<PrivateImplementationDetails>.__StaticArrayInitTypeSize=12 <PrivateImplementationDetails>.4636993D3E1DA4E9D6B8F87B79E8F7C6D018580D52661950EABC3845C5897A4D"" IL_000d: call ""Sub System.Runtime.CompilerServices.RuntimeHelpers.InitializeArray(System.Array, System.RuntimeFieldHandle)"" IL_0012: stloc.0 IL_0013: ldloc.0 IL_0014: ldc.i4.0 IL_0015: ldelem.i4 IL_0016: call ""Sub System.Console.Write(Integer)"" IL_001b: nop IL_001c: ret } ") Dim method0 = compilation0.GetMember(Of MethodSymbol)("C.M") Dim generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), methodData0.EncDebugInfoProvider) Dim testData1 = New CompilationTestData() Dim method1 = compilation1.GetMember(Of MethodSymbol)("C.M") Dim edit = New SemanticEdit(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables:=True) Dim diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(edit)) diff1.VerifyIL("C.M", " { // Code size 30 (0x1e) .maxstack 4 .locals init (Integer() V_0) //a IL_0000: nop IL_0001: ldc.i4.3 IL_0002: newarr ""Integer"" IL_0007: dup IL_0008: ldc.i4.0 IL_0009: ldc.i4.1 IL_000a: stelem.i4 IL_000b: dup IL_000c: ldc.i4.1 IL_000d: ldc.i4.2 IL_000e: stelem.i4 IL_000f: dup IL_0010: ldc.i4.2 IL_0011: ldc.i4.3 IL_0012: stelem.i4 IL_0013: stloc.0 IL_0014: ldloc.0 IL_0015: ldc.i4.1 IL_0016: ldelem.i4 IL_0017: call ""Sub System.Console.Write(Integer)"" IL_001c: nop IL_001d: ret } ") End Sub ''' <summary> ''' Should not generate method for string switch since ''' the CLR only allows adding private members. ''' </summary> <WorkItem(834086, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/834086")> <Fact()> Public Sub PrivateImplementationDetails_ComputeStringHash() Dim sources = <compilation> <file name="a.vb"><![CDATA[ Class C Shared Function F(s As String) Select Case s Case "1" Return 1 Case "2" Return 2 Case "3" Return 3 Case "4" Return 4 Case "5" Return 5 Case "6" Return 6 Case "7" Return 7 Case Else Return 0 End Select End Function End Class ]]></file> </compilation> Const ComputeStringHashName As String = "ComputeStringHash" Dim compilation0 = CreateCompilationWithMscorlib40AndVBRuntime(sources, TestOptions.DebugDll) Dim compilation1 = compilation0.WithSource(sources) Dim testData0 = New CompilationTestData() Dim bytes0 = compilation0.EmitToArray(testData:=testData0) Dim methodData0 = testData0.GetMethodData("C.F") Dim method0 = compilation0.GetMember(Of MethodSymbol)("C.F") Dim generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), methodData0.EncDebugInfoProvider) ' Should have generated call to ComputeStringHash and ' added the method to <PrivateImplementationDetails>. Dim actualIL0 = methodData0.GetMethodIL() Assert.True(actualIL0.Contains(ComputeStringHashName)) Using md0 = ModuleMetadata.CreateFromImage(bytes0) Dim reader0 = md0.MetadataReader CheckNames(reader0, reader0.GetMethodDefNames(), ".ctor", "F", ComputeStringHashName) Dim testData1 = New CompilationTestData() Dim method1 = compilation1.GetMember(Of MethodSymbol)("C.F") Dim edit = New SemanticEdit(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables:=True) Dim diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(edit)) ' Should not have generated call to ComputeStringHash nor ' added the method to <PrivateImplementationDetails>. Dim actualIL1 = diff1.GetMethodIL("C.F") Assert.False(actualIL1.Contains(ComputeStringHashName)) Using md1 = diff1.GetMetadata() Dim reader1 = md1.Reader Dim readers = {reader0, reader1} CheckNames(readers, reader1.GetMethodDefNames(), "F") End Using End Using End Sub ''' <summary> ''' Avoid adding references from method bodies ''' other than the changed methods. ''' </summary> <Fact> Public Sub ReferencesInIL() Dim sources0 = <compilation> <file name="a.vb"><![CDATA[ Module M Sub F() System.Console.WriteLine(1) End Sub Sub G() System.Console.WriteLine(2) End Sub End Module ]]></file> </compilation> Dim sources1 = <compilation> <file name="a.vb"><![CDATA[ Module M Sub F() System.Console.WriteLine(1) End Sub Sub G() System.Console.Write(2) End Sub End Module ]]></file> </compilation> Dim compilation0 = CreateCompilationWithMscorlib40AndVBRuntime(sources0, TestOptions.DebugDll) Dim compilation1 = compilation0.WithSource(sources1) ' Verify full metadata contains expected rows. Dim bytes0 = compilation0.EmitToArray() Using md0 = ModuleMetadata.CreateFromImage(bytes0) Dim reader0 = md0.MetadataReader CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "M") CheckNames(reader0, reader0.GetMethodDefNames(), "F", "G") CheckNames(reader0, reader0.GetMemberRefNames(), ".ctor", ".ctor", ".ctor", ".ctor", "WriteLine") Dim generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider) Dim diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(New SemanticEdit(SemanticEditKind.Insert, Nothing, compilation1.GetMember("M.G")))) ' "Write" should be included in string table, but "WriteLine" should not. Assert.True(diff1.MetadataDelta.IsIncluded("Write")) Assert.False(diff1.MetadataDelta.IsIncluded("WriteLine")) End Using End Sub <Fact> Public Sub ExceptionFilters() Dim source0 = MarkedSource(" Imports System Imports System.IO Class C Shared Function filter(e As Exception) Return True End Function Shared Sub F() Try Throw New InvalidOperationException() <N:0>Catch e As IOException <N:1>When filter(e)</N:1></N:0> Console.WriteLine() <N:2>Catch e As Exception <N:3>When filter(e)</N:3></N:2> Console.WriteLine() End Try End Sub End Class ") Dim source1 = MarkedSource(" Imports System Imports System.IO Class C Shared Function filter(e As Exception) Return True End Function Shared Sub F() Try Throw New InvalidOperationException() <N:0>Catch e As IOException <N:1>When filter(e)</N:1></N:0> Console.WriteLine() <N:2>Catch e As Exception <N:3>When filter(e)</N:3></N:2> Console.WriteLine() End Try Console.WriteLine() End Sub End Class ") Dim compilation0 = CreateCompilationWithMscorlib45AndVBRuntime({source0.Tree}, options:=ComSafeDebugDll) Dim compilation1 = compilation0.WithSource(source1.Tree) Dim v0 = CompileAndVerify(compilation0) Dim md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData) Dim f0 = compilation0.GetMember(Of MethodSymbol)("C.F") Dim f1 = compilation1.GetMember(Of MethodSymbol)("C.F") Dim generation0 = EmitBaseline.CreateInitialBaseline(md0, AddressOf v0.CreateSymReader().GetEncMethodDebugInfo) Dim diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( New SemanticEdit(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables:=True))) diff1.VerifyIL("C.F", " { // Code size 118 (0x76) .maxstack 2 .locals init (System.IO.IOException V_0, //e Boolean V_1, System.Exception V_2, //e Boolean V_3) IL_0000: nop .try { IL_0001: nop IL_0002: newobj ""Sub System.InvalidOperationException..ctor()"" IL_0007: throw } filter { IL_0008: isinst ""System.IO.IOException"" IL_000d: dup IL_000e: brtrue.s IL_0014 IL_0010: pop IL_0011: ldc.i4.0 IL_0012: br.s IL_002b IL_0014: dup IL_0015: call ""Sub Microsoft.VisualBasic.CompilerServices.ProjectData.SetProjectError(System.Exception)"" IL_001a: stloc.0 IL_001b: ldloc.0 IL_001c: call ""Function C.filter(System.Exception) As Object"" IL_0021: call ""Function Microsoft.VisualBasic.CompilerServices.Conversions.ToBoolean(Object) As Boolean"" IL_0026: stloc.1 IL_0027: ldloc.1 IL_0028: ldc.i4.0 IL_0029: cgt.un IL_002b: endfilter } // end filter { // handler IL_002d: pop IL_002e: call ""Sub System.Console.WriteLine()"" IL_0033: nop IL_0034: call ""Sub Microsoft.VisualBasic.CompilerServices.ProjectData.ClearProjectError()"" IL_0039: leave.s IL_006e } filter { IL_003b: isinst ""System.Exception"" IL_0040: dup IL_0041: brtrue.s IL_0047 IL_0043: pop IL_0044: ldc.i4.0 IL_0045: br.s IL_005e IL_0047: dup IL_0048: call ""Sub Microsoft.VisualBasic.CompilerServices.ProjectData.SetProjectError(System.Exception)"" IL_004d: stloc.2 IL_004e: ldloc.2 IL_004f: call ""Function C.filter(System.Exception) As Object"" IL_0054: call ""Function Microsoft.VisualBasic.CompilerServices.Conversions.ToBoolean(Object) As Boolean"" IL_0059: stloc.3 IL_005a: ldloc.3 IL_005b: ldc.i4.0 IL_005c: cgt.un IL_005e: endfilter } // end filter { // handler IL_0060: pop IL_0061: call ""Sub System.Console.WriteLine()"" IL_0066: nop IL_0067: call ""Sub Microsoft.VisualBasic.CompilerServices.ProjectData.ClearProjectError()"" IL_006c: leave.s IL_006e } IL_006e: nop IL_006f: call ""Sub System.Console.WriteLine()"" IL_0074: nop IL_0075: ret } ") End Sub <Fact> Public Sub SymbolMatcher_TypeArguments() Dim source = <compilation> <file name="c.vb"><![CDATA[ Class A(Of T) Class B(Of U) Shared Function M(Of V)(x As A(Of U).B(Of T), y As A(Of Object).S) As A(Of V) Return Nothing End Function Shared Function M(Of V)(x As A(Of U).B(Of T), y As A(Of V).S) As A(Of V) Return Nothing End Function End Class Structure S End Structure End Class ]]> </file> </compilation> Dim compilation0 = CreateCompilationWithMscorlib40AndVBRuntime(source, TestOptions.DebugDll) Dim compilation1 = compilation0.Clone() Dim matcher = CreateMatcher(compilation1, compilation0) Dim members = compilation1.GetMember(Of NamedTypeSymbol)("A.B").GetMembers("M") Assert.Equal(members.Length, 2) For Each member In members Dim other = DirectCast(matcher.MapDefinition(DirectCast(member.GetCciAdapter(), Cci.IMethodDefinition)).GetInternalSymbol(), MethodSymbol) Assert.NotNull(other) Next End Sub <Fact> Public Sub SymbolMatcher_Constraints() Dim source = <compilation> <file name="c.vb"><![CDATA[ Interface I(Of T As I(Of T)) End Interface Class C Shared Sub M(Of T As I(Of T))(o As I(Of T)) End Sub End Class ]]> </file> </compilation> Dim compilation0 = CreateCompilationWithMscorlib40AndVBRuntime(source, TestOptions.DebugDll) Dim compilation1 = compilation0.Clone() Dim matcher = CreateMatcher(compilation1, compilation0) Dim member = compilation1.GetMember(Of MethodSymbol)("C.M") Dim other = DirectCast(matcher.MapDefinition(DirectCast(member.GetCciAdapter(), Cci.IMethodDefinition)).GetInternalSymbol(), MethodSymbol) Assert.NotNull(other) End Sub <Fact> Public Sub SymbolMatcher_CustomModifiers() Dim ilSource = <![CDATA[ .class public abstract A { .method public hidebysig specialname rtspecialname instance void .ctor() { ret } .method public abstract virtual instance object modopt(A) [] F() { } } ]]>.Value Dim source = <compilation> <file name="c.vb"><![CDATA[ Class B Inherits A Public Overrides Function F() As Object() Return Nothing End Function End Class ]]> </file> </compilation> Dim metadata = CompileIL(ilSource) Dim compilation0 = CreateCompilationWithMscorlib40AndVBRuntime(source, {metadata}, TestOptions.DebugDll) Dim compilation1 = compilation0.Clone() Dim member1 = compilation1.GetMember(Of MethodSymbol)("B.F") Const nModifiers As Integer = 1 Assert.Equal(nModifiers, DirectCast(member1.ReturnType, ArrayTypeSymbol).CustomModifiers.Length) Dim matcher = CreateMatcher(compilation1, compilation0) Dim other = DirectCast(matcher.MapDefinition(DirectCast(member1.GetCciAdapter(), Cci.IMethodDefinition)).GetInternalSymbol(), MethodSymbol) Assert.NotNull(other) Assert.Equal(nModifiers, DirectCast(other.ReturnType, ArrayTypeSymbol).CustomModifiers.Length) End Sub <Fact> <WorkItem(54939, "https://github.com/dotnet/roslyn/issues/54939")> Sub AddNamespace() Dim source0 = " Class C Shared Sub Main() End Sub End Class" Dim source1 = " Namespace N1.N2 Class D Public Shared Sub F() End Sub End Class End Namespace Class C Shared Sub Main() N1.N2.D.F() End Sub End Class " Dim source2 = " Namespace N1.N2 Class D Public Shared Sub F() End Sub End Class Namespace M1.M2 Class E Public Shared Sub G() End Sub End Class End Namespace End Namespace Class C Shared Sub Main() N1.N2.M1.M2.E.G() End Sub End Class " Dim compilation0 = CreateCompilation(source0, options:=ComSafeDebugDll) Dim compilation1 = compilation0.WithSource(source1) Dim compilation2 = compilation1.WithSource(source2) Dim main0 = compilation0.GetMember(Of MethodSymbol)("C.Main") Dim main1 = compilation1.GetMember(Of MethodSymbol)("C.Main") Dim main2 = compilation2.GetMember(Of MethodSymbol)("C.Main") Dim d1 = compilation1.GetMember(Of NamedTypeSymbol)("N1.N2.D") Dim e2 = compilation2.GetMember(Of NamedTypeSymbol)("N1.N2.M1.M2.E") Using md0 = ModuleMetadata.CreateFromImage(compilation0.EmitToArray()) Dim generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider) Dim diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, main0, main1), SemanticEdit.Create(SemanticEditKind.Insert, Nothing, d1))) diff1.VerifyIL("C.Main", " { // Code size 8 (0x8) .maxstack 0 IL_0000: nop IL_0001: call ""Sub N1.N2.D.F()"" IL_0006: nop IL_0007: ret }") Dim diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, main1, main2), SemanticEdit.Create(SemanticEditKind.Insert, Nothing, e2))) diff2.VerifyIL("C.Main", " { // Code size 8 (0x8) .maxstack 0 IL_0000: nop IL_0001: call ""Sub N1.N2.M1.M2.E.G()"" IL_0006: nop IL_0007: ret }") End Using End Sub <WorkItem(844472, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/844472")> <Fact()> Public Sub MethodSignatureWithNoPIAType() Dim sourcesPIA = <compilation> <file name="a.vb"><![CDATA[ Imports System Imports System.Runtime.InteropServices <Assembly: ImportedFromTypeLib("_.dll")> <Assembly: Guid("35DB1A6B-D635-4320-A062-28D42920F2A3")> <ComImport()> <Guid("35DB1A6B-D635-4320-A062-28D42920F2A4")> Public Interface I End Interface ]]></file> </compilation> Dim sources0 = <compilation> <file name="a.vb"><![CDATA[ Class C Shared Sub M(x As I) Dim y As I = Nothing M(Nothing) End Sub End Class ]]></file> </compilation> Dim sources1 = <compilation> <file name="a.vb"><![CDATA[ Class C Shared Sub M(x As I) Dim y As I = Nothing M(x) End Sub End Class ]]></file> </compilation> Dim compilationPIA = CreateCompilationWithMscorlib40AndVBRuntime(sourcesPIA) compilationPIA.AssertTheseDiagnostics() Dim referencePIA = compilationPIA.EmitToImageReference(embedInteropTypes:=True) Dim compilation0 = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(sources0, options:=TestOptions.DebugDll, references:={referencePIA}) Dim compilation1 = compilation0.WithSource(sources1) Dim testData0 = New CompilationTestData() Dim bytes0 = compilation0.EmitToArray(testData:=testData0) Dim methodData0 = testData0.GetMethodData("C.M") Using md0 = ModuleMetadata.CreateFromImage(bytes0) Dim generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider) Dim method0 = compilation0.GetMember(Of MethodSymbol)("C.M") Dim method1 = compilation1.GetMember(Of MethodSymbol)("C.M") Dim diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(New SemanticEdit(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables:=True))) diff1.VerifyIL("C.M", <![CDATA[ { // Code size 11 (0xb) .maxstack 1 .locals init ([unchanged] V_0, I V_1) //y IL_0000: nop IL_0001: ldnull IL_0002: stloc.1 IL_0003: ldarg.0 IL_0004: call "Sub C.M(I)" IL_0009: nop IL_000a: ret } ]]>.Value) End Using End Sub ''' <summary> ''' Disallow edits that require NoPIA references. ''' </summary> <Fact()> Public Sub NoPIAReferences() Dim sourcesPIA = <compilation> <file name="a.vb"><![CDATA[ Imports System Imports System.Runtime.InteropServices <Assembly: ImportedFromTypeLib("_.dll")> <Assembly: Guid("35DB1A6B-D635-4320-A062-28D42920F2B3")> <ComImport()> <Guid("35DB1A6B-D635-4320-A062-28D42920F2B4")> Public Interface IA Sub M() ReadOnly Property P As Integer Event E As Action End Interface <ComImport()> <Guid("35DB1A6B-D635-4320-A062-28D42920F2B5")> Public Interface IB End Interface <ComImport()> <Guid("35DB1A6B-D635-4320-A062-28D42920F2B6")> Public Interface IC End Interface Public Structure S Public F As Object End Structure ]]></file> </compilation> Dim sources0 = <compilation> <file name="a.vb"><![CDATA[ Class C(Of T) Shared Private F As Object = GetType(IC) Shared Sub M1() Dim o As IA = Nothing o.M() M2(o.P) AddHandler o.E, AddressOf M1 M2(C(Of IA).F) M2(New S()) End Sub Shared Sub M2(o As Object) End Sub End Class ]]></file> </compilation> Dim sources1A = sources0 Dim sources1B = <compilation> <file name="a.vb"><![CDATA[ Class C(Of T) Shared Private F As Object = GetType(IC) Shared Sub M1() M2(Nothing) End Sub Shared Sub M2(o As Object) End Sub End Class ]]></file> </compilation> Dim compilationPIA = CreateCompilationWithMscorlib40AndVBRuntime(sourcesPIA) compilationPIA.AssertTheseDiagnostics() Dim referencePIA = compilationPIA.EmitToImageReference(embedInteropTypes:=True) Dim compilation0 = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(sources0, options:=TestOptions.DebugDll, references:={referencePIA}) Dim compilation1A = compilation0.WithSource(sources1A) Dim compilation1B = compilation0.WithSource(sources1B) Dim testData0 = New CompilationTestData() Dim bytes0 = compilation0.EmitToArray(testData:=testData0) Dim methodData0 = testData0.GetMethodData("C(Of T).M1") Using md0 = ModuleMetadata.CreateFromImage(bytes0) Dim reader0 = md0.MetadataReader CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "C`1", "IA", "IC", "S") Dim generation0 = EmitBaseline.CreateInitialBaseline(md0, methodData0.EncDebugInfoProvider) Dim method0 = compilation0.GetMember(Of MethodSymbol)("C.M1") ' Disallow edits that require NoPIA references. Dim method1A = compilation1A.GetMember(Of MethodSymbol)("C.M1") Dim diff1A = compilation1A.EmitDifference( generation0, ImmutableArray.Create(New SemanticEdit(SemanticEditKind.Update, method0, method1A, GetEquivalentNodesMap(method1A, method0), preserveLocalVariables:=True))) diff1A.EmitResult.Diagnostics.AssertTheseDiagnostics(<errors><![CDATA[ BC37230: Cannot continue since the edit includes a reference to an embedded type: 'IA'. BC37230: Cannot continue since the edit includes a reference to an embedded type: 'S'. ]]></errors>) ' Allow edits that do not require NoPIA references, Dim method1B = compilation1B.GetMember(Of MethodSymbol)("C.M1") Dim diff1B = compilation1B.EmitDifference( generation0, ImmutableArray.Create(New SemanticEdit(SemanticEditKind.Update, method0, method1B, GetEquivalentNodesMap(method1B, method0), preserveLocalVariables:=True))) diff1B.VerifyIL("C(Of T).M1", <![CDATA[ { // Code size 9 (0x9) .maxstack 1 .locals init ([unchanged] V_0, [unchanged] V_1) IL_0000: nop IL_0001: ldnull IL_0002: call "Sub C(Of T).M2(Object)" IL_0007: nop IL_0008: ret } ]]>.Value) Using md1 = diff1B.GetMetadata() Dim reader1 = md1.Reader CheckNames({reader0, reader1}, reader1.GetTypeDefNames()) End Using End Using End Sub <WorkItem(844536, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/844536")> <Fact()> Public Sub NoPIATypeInNamespace() Dim sourcesPIA = <compilation> <file name="a.vb"><![CDATA[ Imports System Imports System.Runtime.InteropServices <Assembly: ImportedFromTypeLib("_.dll")> <Assembly: Guid("35DB1A6B-D635-4320-A062-28D42920F2A5")> Namespace N <ComImport()> <Guid("35DB1A6B-D635-4320-A062-28D42920F2A6")> Public Interface IA End Interface End Namespace <ComImport()> <Guid("35DB1A6B-D635-4320-A062-28D42920F2A6")> Public Interface IB End Interface ]]></file> </compilation> Dim sources = <compilation> <file name="a.vb"><![CDATA[ Class C(Of T) Shared Sub M(o As Object) M(C(Of N.IA).E.X) M(C(Of IB).E.X) End Sub Enum E X End Enum End Class ]]></file> </compilation> Dim compilationPIA = CreateCompilationWithMscorlib40AndVBRuntime(sourcesPIA) compilationPIA.AssertTheseDiagnostics() Dim referencePIA = AssemblyMetadata.CreateFromImage(compilationPIA.EmitToArray()).GetReference(embedInteropTypes:=True) Dim compilation0 = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(sources, options:=TestOptions.DebugDll, references:={referencePIA}) Dim compilation1 = compilation0.WithSource(sources) Dim bytes0 = compilation0.EmitToArray() Using md0 = ModuleMetadata.CreateFromImage(bytes0) Dim generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider) Dim method0 = compilation0.GetMember(Of MethodSymbol)("C.M") Dim method1 = compilation1.GetMember(Of MethodSymbol)("C.M") Dim diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(New SemanticEdit(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables:=True))) diff1.EmitResult.Diagnostics.AssertTheseDiagnostics(<errors><![CDATA[ BC37230: Cannot continue since the edit includes a reference to an embedded type: 'IA'. BC37230: Cannot continue since the edit includes a reference to an embedded type: 'IB'. ]]></errors>) diff1.VerifyIL("C(Of T).M", <![CDATA[ { // Code size 26 (0x1a) .maxstack 1 IL_0000: nop IL_0001: ldc.i4.0 IL_0002: box "C(Of N.IA).E" IL_0007: call "Sub C(Of T).M(Object)" IL_000c: nop IL_000d: ldc.i4.0 IL_000e: box "C(Of IB).E" IL_0013: call "Sub C(Of T).M(Object)" IL_0018: nop IL_0019: ret } ]]>.Value) End Using End Sub <Fact, WorkItem(1175704, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1175704")> Public Sub EventFields() Dim source0 = MarkedSource(" Imports System Class C Shared Event handler As EventHandler Shared Function F() As Integer RaiseEvent handler(Nothing, Nothing) Return 1 End Function End Class ") Dim source1 = MarkedSource(" Imports System Class C Shared Event handler As EventHandler Shared Function F() As Integer RaiseEvent handler(Nothing, Nothing) Return 10 End Function End Class ") Dim compilation0 = CreateCompilationWithMscorlib40(source0.Tree, options:=ComSafeDebugDll) compilation0.AssertNoDiagnostics() Dim compilation1 = compilation0.WithSource(source1.Tree) Dim f0 = compilation0.GetMember(Of MethodSymbol)("C.F") Dim f1 = compilation1.GetMember(Of MethodSymbol)("C.F") Dim v0 = CompileAndVerify(compilation0) Dim md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData) Dim generation0 = EmitBaseline.CreateInitialBaseline(md0, AddressOf v0.CreateSymReader().GetEncMethodDebugInfo) Dim diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( New SemanticEdit(SemanticEditKind.Update, f0, f1, preserveLocalVariables:=True))) diff1.VerifyIL("C.F", " { // Code size 26 (0x1a) .maxstack 3 .locals init (Integer V_0, //F [unchanged] V_1, System.EventHandler V_2) IL_0000: nop IL_0001: ldsfld ""C.handlerEvent As System.EventHandler"" IL_0006: stloc.2 IL_0007: ldloc.2 IL_0008: brfalse.s IL_0013 IL_000a: ldloc.2 IL_000b: ldnull IL_000c: ldnull IL_000d: callvirt ""Sub System.EventHandler.Invoke(Object, System.EventArgs)"" IL_0012: nop IL_0013: ldc.i4.s 10 IL_0015: stloc.0 IL_0016: br.s IL_0018 IL_0018: ldloc.0 IL_0019: ret } ") End Sub ''' <summary> ''' Should use TypeDef rather than TypeRef for unrecognized ''' local of a type defined in the original assembly. ''' </summary> <WorkItem(910777, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/910777")> <Fact()> Public Sub UnrecognizedLocalOfTypeFromAssembly() Dim source = <compilation> <file name="a.vb"><![CDATA[ Class E Inherits System.Exception End Class Class C Shared Sub M() Try Catch e As E End Try End Sub End Class ]]></file> </compilation> Dim compilation0 = CreateCompilationWithMscorlib40AndVBRuntime(source, options:=TestOptions.DebugDll) Dim compilation1 = compilation0.Clone() Dim bytes0 = compilation0.EmitToArray() Using md0 = ModuleMetadata.CreateFromImage(bytes0) Dim reader0 = md0.MetadataReader CheckNames(reader0, reader0.GetAssemblyRefNames(), "mscorlib", "Microsoft.VisualBasic") Dim method0 = compilation0.GetMember(Of MethodSymbol)("C.M") ' Use empty LocalVariableNameProvider for original locals and ' use preserveLocalVariables: true for the edit so that existing ' locals are retained even though all are unrecognized. Dim generation0 = EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider) Dim method1 = compilation1.GetMember(Of MethodSymbol)("C.M") Dim diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(New SemanticEdit(SemanticEditKind.Update, method0, method1, syntaxMap:=Function(s) Nothing, preserveLocalVariables:=True))) Using md1 = diff1.GetMetadata() Dim reader1 = md1.Reader Dim readers = {reader0, reader1} CheckNames(readers, reader1.GetAssemblyRefNames(), "mscorlib", "Microsoft.VisualBasic") CheckNames(readers, reader1.GetTypeRefNames(), "Object", "ProjectData", "Exception") CheckEncLog(reader1, Row(3, TableIndex.AssemblyRef, EditAndContinueOperation.Default), Row(4, TableIndex.AssemblyRef, EditAndContinueOperation.Default), Row(8, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(9, TableIndex.MemberRef, EditAndContinueOperation.Default), Row(8, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(9, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(10, TableIndex.TypeRef, EditAndContinueOperation.Default), Row(2, TableIndex.StandAloneSig, EditAndContinueOperation.Default), Row(3, TableIndex.MethodDef, EditAndContinueOperation.Default)) CheckEncMap(reader1, Handle(8, TableIndex.TypeRef), Handle(9, TableIndex.TypeRef), Handle(10, TableIndex.TypeRef), Handle(3, TableIndex.MethodDef), Handle(8, TableIndex.MemberRef), Handle(9, TableIndex.MemberRef), Handle(2, TableIndex.StandAloneSig), Handle(3, TableIndex.AssemblyRef), Handle(4, TableIndex.AssemblyRef)) End Using End Using End Sub <Fact, WorkItem(837315, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/837315")> Public Sub AddingSetAccessor() Dim source0 = <compilation> <file name="a.vb"> Module Module1 Sub Main() System.Console.WriteLine("hello") End Sub Friend name As String Readonly Property GetName Get Return name End Get End Property End Module </file> </compilation> Dim source1 = <compilation> <file name="a.vb"> Module Module1 Sub Main() System.Console.WriteLine("hello") End Sub Friend name As String Property GetName Get Return name End Get Private Set(value) End Set End Property End Module</file> </compilation> Dim compilation0 = CreateCompilationWithMscorlib40AndVBRuntime(source0, TestOptions.DebugDll) Dim compilation1 = compilation0.WithSource(source1) Dim testData0 = New CompilationTestData() Dim bytes0 = compilation0.EmitToArray(testData:=testData0) Using md0 = ModuleMetadata.CreateFromImage(bytes0) Dim reader0 = md0.MetadataReader Dim prop0 = compilation0.GetMember(Of PropertySymbol)("Module1.GetName") Dim prop1 = compilation1.GetMember(Of PropertySymbol)("Module1.GetName") Dim method1 = prop1.SetMethod Dim generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), EmptyLocalsProvider) Dim diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(New SemanticEdit(SemanticEditKind.Insert, Nothing, method1, preserveLocalVariables:=True))) Using md1 = diff1.GetMetadata() Dim reader1 = md1.Reader CheckNames({reader0, reader1}, reader1.GetMethodDefNames(), "set_GetName") End Using diff1.VerifyIL("Module1.set_GetName", " { // Code size 2 (0x2) .maxstack 0 IL_0000: nop IL_0001: ret } ") End Using End Sub <Fact> Public Sub PropertyGetterReturnValueVariable() Dim source0 = <compilation> <file name="a.vb"> Module Module1 ReadOnly Property P Get P = 1 End Get End Property End Module </file> </compilation> Dim source1 = <compilation> <file name="a.vb"> Module Module1 ReadOnly Property P Get P = 2 End Get End Property End Module</file> </compilation> Dim compilation0 = CreateCompilationWithMscorlib40AndVBRuntime(source0, TestOptions.DebugDll) Dim compilation1 = compilation0.WithSource(source1) Dim testData0 = New CompilationTestData() Dim bytes0 = compilation0.EmitToArray(testData:=testData0) Using md0 = ModuleMetadata.CreateFromImage(bytes0) Dim getter0 = compilation0.GetMember(Of PropertySymbol)("Module1.P").GetMethod Dim getter1 = compilation1.GetMember(Of PropertySymbol)("Module1.P").GetMethod Dim generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), testData0.GetMethodData("Module1.get_P").EncDebugInfoProvider) Dim diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(New SemanticEdit(SemanticEditKind.Update, getter0, getter1, preserveLocalVariables:=True))) diff1.VerifyIL("Module1.get_P", " { // Code size 10 (0xa) .maxstack 1 .locals init (Object V_0) //P IL_0000: nop IL_0001: ldc.i4.2 IL_0002: box ""Integer"" IL_0007: stloc.0 IL_0008: ldloc.0 IL_0009: ret }") End Using End Sub #Region "Local Slots" <Fact, WorkItem(828389, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/828389")> Public Sub CatchClause() Dim source0 = <compilation> <file name="a.vb"> Class C Shared Sub M() Try System.Console.WriteLine(1) Catch ex As System.Exception End Try End Sub End Class </file> </compilation> Dim source1 = <compilation> <file name="a.vb"> Class C Shared Sub M() Try System.Console.WriteLine(2) Catch ex As System.Exception End Try End Sub End Class </file> </compilation> Dim compilation0 = CreateCompilationWithMscorlib40AndVBRuntime(source0, TestOptions.DebugDll) Dim compilation1 = compilation0.WithSource(source1) Dim testData0 = New CompilationTestData() Dim bytes0 = compilation0.EmitToArray(testData:=testData0) Dim method0 = compilation0.GetMember(Of MethodSymbol)("C.M") Dim method1 = compilation1.GetMember(Of MethodSymbol)("C.M") Dim generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), testData0.GetMethodData("C.M").EncDebugInfoProvider) Dim diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(New SemanticEdit(SemanticEditKind.Update, method0, method1, preserveLocalVariables:=True))) diff1.VerifyIL("C.M", " { // Code size 28 (0x1c) .maxstack 2 .locals init (System.Exception V_0) //ex IL_0000: nop .try { IL_0001: nop IL_0002: ldc.i4.2 IL_0003: call ""Sub System.Console.WriteLine(Integer)"" IL_0008: nop IL_0009: leave.s IL_001a } catch System.Exception { IL_000b: dup IL_000c: call ""Sub Microsoft.VisualBasic.CompilerServices.ProjectData.SetProjectError(System.Exception)"" IL_0011: stloc.0 IL_0012: nop IL_0013: call ""Sub Microsoft.VisualBasic.CompilerServices.ProjectData.ClearProjectError()"" IL_0018: leave.s IL_001a } IL_001a: nop IL_001b: ret } ") End Sub ''' <summary> ''' Local slots must be preserved based on signature. ''' </summary> <ConditionalFact(GetType(WindowsOnly), Reason:=ConditionalSkipReason.NativePdbRequiresDesktop)> Public Sub PreserveLocalSlots() Dim sources0 = <compilation> <file><![CDATA[ Class A(Of T) End Class Class B Inherits A(Of B) Shared Function F() As B Return Nothing End Function Shared Sub M(o As Object) Dim x As Object = F() Dim y As A(Of B) = F() Dim z As Object = F() M(x) M(y) M(z) End Sub Shared Sub N() Dim a As Object = F() Dim b As Object = F() M(a) M(b) End Sub End Class ]]></file> </compilation> Dim sources1 = <compilation> <file><![CDATA[ Class A(Of T) End Class Class B Inherits A(Of B) Shared Function F() As B Return Nothing End Function Shared Sub M(o As Object) Dim z As B = F() Dim y As A(Of B) = F() Dim w As Object = F() M(w) M(y) End Sub Shared Sub N() Dim a As Object = F() Dim b As Object = F() M(a) M(b) End Sub End Class ]]></file> </compilation> Dim sources2 = <compilation> <file><![CDATA[ Class A(Of T) End Class Class B Inherits A(Of B) Shared Function F() As B Return Nothing End Function Shared Sub M(o As Object) Dim x As Object = F() Dim z As B = F() M(x) M(z) End Sub Shared Sub N() Dim a As Object = F() Dim b As Object = F() M(a) M(b) End Sub End Class ]]></file> </compilation> Dim sources3 = <compilation> <file><![CDATA[ Class A(Of T) End Class Class B Inherits A(Of B) Shared Function F() As B Return Nothing End Function Shared Sub M(o As Object) Dim x As Object = F() Dim z As B = F() M(x) M(z) End Sub Shared Sub N() Dim c As Object = F() Dim b As Object = F() M(c) M(b) End Sub End Class ]]></file> </compilation> Dim compilation0 = CreateCompilationWithMscorlib40(sources0, options:=TestOptions.DebugDll) Dim compilation1 = compilation0.WithSource(sources1) Dim compilation2 = compilation1.WithSource(sources2) Dim compilation3 = compilation2.WithSource(sources3) ' Verify full metadata contains expected rows. Dim testData0 = New CompilationTestData() Dim bytes0 = compilation0.EmitToArray(testData:=testData0) Dim method0 = compilation0.GetMember(Of MethodSymbol)("B.M") Dim method1 = compilation1.GetMember(Of MethodSymbol)("B.M") Dim methodN = compilation0.GetMember(Of MethodSymbol)("B.N") Dim generation0 = EmitBaseline.CreateInitialBaseline( ModuleMetadata.CreateFromImage(bytes0), Function(m) Select Case MetadataTokens.GetRowNumber(m) Case 4 Return testData0.GetMethodData("B.M").GetEncDebugInfo() Case 5 Return testData0.GetMethodData("B.N").GetEncDebugInfo() Case Else Return Nothing End Select End Function) Dim diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(New SemanticEdit(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables:=True))) diff1.VerifyIL(" { // Code size 41 (0x29) .maxstack 1 IL_0000: nop IL_0001: call 0x06000003 IL_0006: stloc.3 IL_0007: call 0x06000003 IL_000c: stloc.1 IL_000d: call 0x06000003 IL_0012: stloc.s V_4 IL_0014: ldloc.s V_4 IL_0016: call 0x0A000007 IL_001b: call 0x06000004 IL_0020: nop IL_0021: ldloc.1 IL_0022: call 0x06000004 IL_0027: nop IL_0028: ret } ") diff1.VerifyPdb({&H06000001UI, &H06000002UI, &H06000003UI, &H06000004UI, &H06000005UI}, <symbols> <files> <file id="1" name="" language="VB"/> </files> <methods> <method token="0x6000004"> <sequencePoints> <entry offset="0x0" startLine="8" startColumn="5" endLine="8" endColumn="30" document="1"/> <entry offset="0x1" startLine="9" startColumn="13" endLine="9" endColumn="25" document="1"/> <entry offset="0x7" startLine="10" startColumn="13" endLine="10" endColumn="31" document="1"/> <entry offset="0xd" startLine="11" startColumn="13" endLine="11" endColumn="30" document="1"/> <entry offset="0x14" startLine="12" startColumn="9" endLine="12" endColumn="13" document="1"/> <entry offset="0x21" startLine="13" startColumn="9" endLine="13" endColumn="13" document="1"/> <entry offset="0x28" startLine="14" startColumn="5" endLine="14" endColumn="12" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x29"> <currentnamespace name=""/> <local name="z" il_index="3" il_start="0x0" il_end="0x29" attributes="0"/> <local name="y" il_index="1" il_start="0x0" il_end="0x29" attributes="0"/> <local name="w" il_index="4" il_start="0x0" il_end="0x29" attributes="0"/> </scope> </method> </methods> </symbols>) Dim method2 = compilation2.GlobalNamespace.GetMember(Of NamedTypeSymbol)("B").GetMember(Of MethodSymbol)("M") Dim diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create(New SemanticEdit(SemanticEditKind.Update, method1, method2, GetEquivalentNodesMap(method2, method1), preserveLocalVariables:=True))) diff2.VerifyIL(" { // Code size 35 (0x23) .maxstack 1 IL_0000: nop IL_0001: call 0x06000003 IL_0006: stloc.s V_5 IL_0008: call 0x06000003 IL_000d: stloc.3 IL_000e: ldloc.s V_5 IL_0010: call 0x0A000008 IL_0015: call 0x06000004 IL_001a: nop IL_001b: ldloc.3 IL_001c: call 0x06000004 IL_0021: nop IL_0022: ret } ") diff2.VerifyPdb({&H06000001UI, &H06000002UI, &H06000003UI, &H06000004UI, &H06000005UI}, <symbols> <files> <file id="1" name="" language="VB"/> </files> <methods> <method token="0x6000004"> <sequencePoints> <entry offset="0x0" startLine="8" startColumn="5" endLine="8" endColumn="30" document="1"/> <entry offset="0x1" startLine="9" startColumn="13" endLine="9" endColumn="30" document="1"/> <entry offset="0x8" startLine="10" startColumn="13" endLine="10" endColumn="25" document="1"/> <entry offset="0xe" startLine="11" startColumn="9" endLine="11" endColumn="13" document="1"/> <entry offset="0x1b" startLine="12" startColumn="9" endLine="12" endColumn="13" document="1"/> <entry offset="0x22" startLine="13" startColumn="5" endLine="13" endColumn="12" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x23"> <currentnamespace name=""/> <local name="x" il_index="5" il_start="0x0" il_end="0x23" attributes="0"/> <local name="z" il_index="3" il_start="0x0" il_end="0x23" attributes="0"/> </scope> </method> </methods> </symbols>) ' Modify different method. (Previous generations ' have not referenced method.) method2 = compilation2.GlobalNamespace.GetMember(Of NamedTypeSymbol)("B").GetMember(Of MethodSymbol)("N") Dim method3 = compilation3.GlobalNamespace.GetMember(Of NamedTypeSymbol)("B").GetMember(Of MethodSymbol)("N") Dim metadata3 As ImmutableArray(Of Byte) = Nothing Dim il3 As ImmutableArray(Of Byte) = Nothing Dim pdb3 As Stream = Nothing Dim diff3 = compilation3.EmitDifference( diff2.NextGeneration, ImmutableArray.Create(New SemanticEdit(SemanticEditKind.Update, method2, method3, GetEquivalentNodesMap(method3, method2), preserveLocalVariables:=True))) diff3.VerifyIL(" { // Code size 38 (0x26) .maxstack 1 IL_0000: nop IL_0001: call 0x06000003 IL_0006: stloc.2 IL_0007: call 0x06000003 IL_000c: stloc.1 IL_000d: ldloc.2 IL_000e: call 0x0A000009 IL_0013: call 0x06000004 IL_0018: nop IL_0019: ldloc.1 IL_001a: call 0x0A000009 IL_001f: call 0x06000004 IL_0024: nop IL_0025: ret } ") diff3.VerifyPdb({&H06000001UI, &H06000002UI, &H06000003UI, &H06000004UI, &H06000005UI}, <symbols> <files> <file id="1" name="" language="VB"/> </files> <methods> <method token="0x6000005"> <sequencePoints> <entry offset="0x0" startLine="14" startColumn="5" endLine="14" endColumn="19" document="1"/> <entry offset="0x1" startLine="15" startColumn="13" endLine="15" endColumn="30" document="1"/> <entry offset="0x7" startLine="16" startColumn="13" endLine="16" endColumn="30" document="1"/> <entry offset="0xd" startLine="17" startColumn="9" endLine="17" endColumn="13" document="1"/> <entry offset="0x19" startLine="18" startColumn="9" endLine="18" endColumn="13" document="1"/> <entry offset="0x25" startLine="19" startColumn="5" endLine="19" endColumn="12" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x26"> <currentnamespace name=""/> <local name="c" il_index="2" il_start="0x0" il_end="0x26" attributes="0"/> <local name="b" il_index="1" il_start="0x0" il_end="0x26" attributes="0"/> </scope> </method> </methods> </symbols>) End Sub ''' <summary> ''' Preserve locals for method added after initial compilation. ''' </summary> <ConditionalFact(GetType(WindowsOnly), Reason:=ConditionalSkipReason.NativePdbRequiresDesktop)> Public Sub PreserveLocalSlots_NewMethod() Dim sources0 = <compilation> <file><![CDATA[ Class C End Class ]]></file> </compilation> Dim sources1 = <compilation> <file><![CDATA[ Class C Shared Sub M() Dim a = New Object() Dim b = String.Empty End Sub End Class ]]></file> </compilation> Dim sources2 = <compilation> <file><![CDATA[ Class C Shared Sub M() Dim a = 1 Dim b = String.Empty End Sub End Class ]]></file> </compilation> Dim compilation0 = CreateCompilationWithMscorlib40(sources0, options:=TestOptions.DebugDll) Dim compilation1 = compilation0.WithSource(sources1) Dim compilation2 = compilation1.WithSource(sources2) Dim bytes0 = compilation0.EmitToArray() Dim generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), EmptyLocalsProvider) Dim method1 = compilation1.GetMember(Of MethodSymbol)("C.M") Dim diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(New SemanticEdit(SemanticEditKind.Insert, Nothing, method1, Nothing, preserveLocalVariables:=True))) Dim method2 = compilation2.GetMember(Of MethodSymbol)("C.M") Dim diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create(New SemanticEdit(SemanticEditKind.Update, method1, method2, GetEquivalentNodesMap(method2, method1), preserveLocalVariables:=True))) diff2.VerifyIL("C.M", <![CDATA[ { // Code size 10 (0xa) .maxstack 1 .locals init ([object] V_0, String V_1, //b Integer V_2) //a IL_0000: nop IL_0001: ldc.i4.1 IL_0002: stloc.2 IL_0003: ldsfld "String.Empty As String" IL_0008: stloc.1 IL_0009: ret } ]]>.Value) diff2.VerifyPdb({&H06000002UI}, <symbols> <files> <file id="1" name="" language="VB"/> </files> <methods> <method token="0x6000002"> <sequencePoints> <entry offset="0x0" startLine="2" startColumn="5" endLine="2" endColumn="19" document="1"/> <entry offset="0x1" startLine="3" startColumn="13" endLine="3" endColumn="18" document="1"/> <entry offset="0x3" startLine="4" startColumn="13" endLine="4" endColumn="29" document="1"/> <entry offset="0x9" startLine="5" startColumn="5" endLine="5" endColumn="12" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0xa"> <currentnamespace name=""/> <local name="a" il_index="2" il_start="0x0" il_end="0xa" attributes="0"/> <local name="b" il_index="1" il_start="0x0" il_end="0xa" attributes="0"/> </scope> </method> </methods> </symbols>) End Sub ''' <summary> ''' Local types should be retained, even if the local is no longer ''' used by the method body, since there may be existing ''' references to that slot, in a Watch window for instance. ''' </summary> <WorkItem(843320, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/843320")> <Fact> Public Sub PreserveLocalTypes() Dim sources0 = <compilation> <file><![CDATA[ Class C Shared Sub Main() Dim x = True Dim y = x System.Console.WriteLine(y) End Sub End Class ]]></file> </compilation> Dim sources1 = <compilation> <file><![CDATA[ Class C Shared Sub Main() Dim x = "A" Dim y = x System.Console.WriteLine(y) End Sub End Class ]]></file> </compilation> Dim compilation0 = CreateCompilationWithMscorlib40(sources0, options:=TestOptions.DebugDll) Dim compilation1 = compilation0.WithSource(sources1) Dim testData0 = New CompilationTestData() Dim bytes0 = compilation0.EmitToArray(testData:=testData0) Dim method0 = compilation0.GetMember(Of MethodSymbol)("C.Main") Dim method1 = compilation1.GetMember(Of MethodSymbol)("C.Main") Dim generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), testData0.GetMethodData("C.Main").EncDebugInfoProvider) Dim diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(New SemanticEdit(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables:=True))) diff1.VerifyIL("C.Main", " { // Code size 17 (0x11) .maxstack 1 .locals init ([bool] V_0, [bool] V_1, String V_2, //x String V_3) //y IL_0000: nop IL_0001: ldstr ""A"" IL_0006: stloc.2 IL_0007: ldloc.2 IL_0008: stloc.3 IL_0009: ldloc.3 IL_000a: call ""Sub System.Console.WriteLine(String)"" IL_000f: nop IL_0010: ret }") End Sub ''' <summary> ''' Local slots must be preserved based on signature. ''' </summary> <Fact> Public Sub PreserveLocalSlotsReferences() Dim sources0 = <compilation> <file><![CDATA[ Class A(Of T) End Class Class C Inherits A(Of C) Shared Function F() As C Return Nothing End Function Shared Sub M(o As Object) dim x = new system.collections.generic.stack(of Integer) x.Push(1) End Sub End Class ]]></file> </compilation> Dim compilation0 = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(sources0, XmlReferences, TestOptions.DebugDll) Dim compilation1 = compilation0.Clone() Dim testData0 = New CompilationTestData() Dim bytes0 = compilation0.EmitToArray(testData:=testData0) testData0.GetMethodData("C.M").VerifyIL(" { // Code size 16 (0x10) .maxstack 2 .locals init (System.Collections.Generic.Stack(Of Integer) V_0) //x IL_0000: nop IL_0001: newobj ""Sub System.Collections.Generic.Stack(Of Integer)..ctor()"" IL_0006: stloc.0 IL_0007: ldloc.0 IL_0008: ldc.i4.1 IL_0009: callvirt ""Sub System.Collections.Generic.Stack(Of Integer).Push(Integer)"" IL_000e: nop IL_000f: ret } ") Dim method0 = compilation0.GetMember(Of MethodSymbol)("C.M") Dim method1 = compilation1.GetMember(Of MethodSymbol)("C.M") Dim modMeta = ModuleMetadata.CreateFromImage(bytes0) Dim generation0 = EmitBaseline.CreateInitialBaseline(modMeta, testData0.GetMethodData("C.M").EncDebugInfoProvider) Dim diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(New SemanticEdit(SemanticEditKind.Update, method0, method1, preserveLocalVariables:=True))) diff1.VerifyIL("C.M", <![CDATA[ { // Code size 16 (0x10) .maxstack 2 .locals init (System.Collections.Generic.Stack(Of Integer) V_0) //x IL_0000: nop IL_0001: newobj "Sub System.Collections.Generic.Stack(Of Integer)..ctor()" IL_0006: stloc.0 IL_0007: ldloc.0 IL_0008: ldc.i4.1 IL_0009: callvirt "Sub System.Collections.Generic.Stack(Of Integer).Push(Integer)" IL_000e: nop IL_000f: ret } ]]>.Value) End Sub ''' <summary> ''' Local slots must be preserved based on signature. ''' </summary> <Fact> Public Sub PreserveLocalSlotsUsing() Dim sources0 = <compilation> <file><![CDATA[ Class A(Of T) End Class Class C Inherits A(Of C) Shared Function F() As C Return Nothing End Function Shared Sub M(o As Object) dim x as System.IDisposable = nothing Using x end using End Sub End Class ]]></file> </compilation> Dim compilation0 = CreateCompilationWithMscorlib40(sources0, options:=TestOptions.DebugDll) Dim compilation1 = compilation0.Clone() Dim testData0 = New CompilationTestData() Dim bytes0 = compilation0.EmitToArray(testData:=testData0) testData0.GetMethodData("C.M").VerifyIL(" { // Code size 21 (0x15) .maxstack 1 .locals init (System.IDisposable V_0, //x System.IDisposable V_1) IL_0000: nop IL_0001: ldnull IL_0002: stloc.0 IL_0003: nop IL_0004: ldloc.0 IL_0005: stloc.1 .try { IL_0006: leave.s IL_0014 } finally { IL_0008: nop IL_0009: ldloc.1 IL_000a: brfalse.s IL_0013 IL_000c: ldloc.1 IL_000d: callvirt ""Sub System.IDisposable.Dispose()"" IL_0012: nop IL_0013: endfinally } IL_0014: ret } ") Dim method0 = compilation0.GetMember(Of MethodSymbol)("C.M") Dim method1 = compilation1.GetMember(Of MethodSymbol)("C.M") Dim generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), testData0.GetMethodData("C.M").EncDebugInfoProvider) Dim diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(New SemanticEdit(SemanticEditKind.Update, method0, method1, preserveLocalVariables:=True))) diff1.VerifyIL("C.M", " { // Code size 21 (0x15) .maxstack 1 .locals init (System.IDisposable V_0, //x System.IDisposable V_1) IL_0000: nop IL_0001: ldnull IL_0002: stloc.0 IL_0003: nop IL_0004: ldloc.0 IL_0005: stloc.1 .try { IL_0006: leave.s IL_0014 } finally { IL_0008: nop IL_0009: ldloc.1 IL_000a: brfalse.s IL_0013 IL_000c: ldloc.1 IL_000d: callvirt ""Sub System.IDisposable.Dispose()"" IL_0012: nop IL_0013: endfinally } IL_0014: ret } ") End Sub ''' <summary> ''' Local slots must be preserved based on signature. ''' </summary> <Fact> Public Sub PreserveLocalSlotsWithByRef() Dim sources0 = <compilation> <file><![CDATA[ Class A(Of T) End Class Class C Inherits A(Of C) Shared Function F() As C Return Nothing End Function Shared Sub M(o As Object) dim x as System.Guid() = nothing With x(3) .ToString() end With End Sub End Class ]]></file> </compilation> Dim compilation0 = CreateCompilationWithMscorlib40(sources0, options:=TestOptions.DebugDll) Dim compilation1 = compilation0.Clone() Dim testData0 = New CompilationTestData() Dim bytes0 = compilation0.EmitToArray(testData:=testData0) testData0.GetMethodData("C.M").VerifyIL(" { // Code size 27 (0x1b) .maxstack 2 .locals init (System.Guid() V_0, //x System.Guid& V_1) //$W0 IL_0000: nop IL_0001: ldnull IL_0002: stloc.0 IL_0003: nop IL_0004: ldloc.0 IL_0005: ldc.i4.3 IL_0006: ldelema ""System.Guid"" IL_000b: stloc.1 IL_000c: ldloc.1 IL_000d: constrained. ""System.Guid"" IL_0013: callvirt ""Function Object.ToString() As String"" IL_0018: pop IL_0019: nop IL_001a: ret } ") Dim method0 = compilation0.GetMember(Of MethodSymbol)("C.M") Dim method1 = compilation1.GetMember(Of MethodSymbol)("C.M") Dim generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), testData0.GetMethodData("C.M").EncDebugInfoProvider) Dim diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(New SemanticEdit(SemanticEditKind.Update, method0, method1, preserveLocalVariables:=True))) diff1.VerifyIL("C.M", " { // Code size 27 (0x1b) .maxstack 2 .locals init (System.Guid() V_0, //x System.Guid& V_1) //$W0 IL_0000: nop IL_0001: ldnull IL_0002: stloc.0 IL_0003: nop IL_0004: ldloc.0 IL_0005: ldc.i4.3 IL_0006: ldelema ""System.Guid"" IL_000b: stloc.1 IL_000c: ldloc.1 IL_000d: constrained. ""System.Guid"" IL_0013: callvirt ""Function Object.ToString() As String"" IL_0018: pop IL_0019: nop IL_001a: ret } ") End Sub ''' <summary> ''' Local slots must be preserved based on signature. ''' </summary> <Fact> Public Sub PreserveLocalSlotsWithByVal() Dim sources0 = <compilation> <file name="a.vb"><![CDATA[ Class A(Of T) End Class Class C Inherits A(Of C) Shared Function F() As C Return Nothing End Function Shared Sub M(o As Object) dim x as System.Guid() = nothing With x .ToString() end With End Sub End Class ]]></file> </compilation> Dim compilation0 = CreateCompilationWithMscorlib40(sources0, options:=TestOptions.DebugDll) Dim compilation1 = compilation0.Clone() Dim testData0 = New CompilationTestData() Dim bytes0 = compilation0.EmitToArray(testData:=testData0) testData0.GetMethodData("C.M").VerifyIL(" { // Code size 17 (0x11) .maxstack 1 .locals init (System.Guid() V_0, //x System.Guid() V_1) //$W0 IL_0000: nop IL_0001: ldnull IL_0002: stloc.0 IL_0003: nop IL_0004: ldloc.0 IL_0005: stloc.1 IL_0006: ldloc.1 IL_0007: callvirt ""Function Object.ToString() As String"" IL_000c: pop IL_000d: nop IL_000e: ldnull IL_000f: stloc.1 IL_0010: ret } ") Dim method0 = compilation0.GetMember(Of MethodSymbol)("C.M") Dim method1 = compilation1.GetMember(Of MethodSymbol)("C.M") Dim generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), testData0.GetMethodData("C.M").EncDebugInfoProvider) Dim diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(New SemanticEdit(SemanticEditKind.Update, method0, method1, preserveLocalVariables:=True))) diff1.VerifyIL("C.M", " { // Code size 17 (0x11) .maxstack 1 .locals init (System.Guid() V_0, //x System.Guid() V_1) //$W0 IL_0000: nop IL_0001: ldnull IL_0002: stloc.0 IL_0003: nop IL_0004: ldloc.0 IL_0005: stloc.1 IL_0006: ldloc.1 IL_0007: callvirt ""Function Object.ToString() As String"" IL_000c: pop IL_000d: nop IL_000e: ldnull IL_000f: stloc.1 IL_0010: ret } ") End Sub ''' <summary> ''' Local slots must be preserved based on signature. ''' </summary> <Fact> Public Sub PreserveLocalSlotsSyncLock() Dim sources0 = <compilation> <file name="a.vb"><![CDATA[ Class A(Of T) End Class Class C Inherits A(Of C) Shared Function F() As C Return Nothing End Function Shared Sub M(o As Object) dim x as System.Guid() = nothing SyncLock x dim y as System.Guid() = nothing SyncLock y x.ToString() end SyncLock end SyncLock End Sub End Class ]]></file> </compilation> Dim compilation0 = CreateCompilationWithMscorlib40(sources0, options:=TestOptions.DebugDll) Dim compilation1 = compilation0.Clone() Dim testData0 = New CompilationTestData() Dim bytes0 = compilation0.EmitToArray(testData:=testData0) testData0.GetMethodData("C.M").VerifyIL(" { // Code size 76 (0x4c) .maxstack 2 .locals init (System.Guid() V_0, //x Object V_1, Boolean V_2, System.Guid() V_3, //y Object V_4, Boolean V_5) IL_0000: nop IL_0001: ldnull IL_0002: stloc.0 IL_0003: nop IL_0004: ldloc.0 IL_0005: stloc.1 IL_0006: ldc.i4.0 IL_0007: stloc.2 .try { IL_0008: ldloc.1 IL_0009: ldloca.s V_2 IL_000b: call ""Sub System.Threading.Monitor.Enter(Object, ByRef Boolean)"" IL_0010: nop IL_0011: ldnull IL_0012: stloc.3 IL_0013: nop IL_0014: ldloc.3 IL_0015: stloc.s V_4 IL_0017: ldc.i4.0 IL_0018: stloc.s V_5 .try { IL_001a: ldloc.s V_4 IL_001c: ldloca.s V_5 IL_001e: call ""Sub System.Threading.Monitor.Enter(Object, ByRef Boolean)"" IL_0023: nop IL_0024: ldloc.0 IL_0025: callvirt ""Function Object.ToString() As String"" IL_002a: pop IL_002b: leave.s IL_003b } finally { IL_002d: ldloc.s V_5 IL_002f: brfalse.s IL_0039 IL_0031: ldloc.s V_4 IL_0033: call ""Sub System.Threading.Monitor.Exit(Object)"" IL_0038: nop IL_0039: nop IL_003a: endfinally } IL_003b: nop IL_003c: leave.s IL_004a } finally { IL_003e: ldloc.2 IL_003f: brfalse.s IL_0048 IL_0041: ldloc.1 IL_0042: call ""Sub System.Threading.Monitor.Exit(Object)"" IL_0047: nop IL_0048: nop IL_0049: endfinally } IL_004a: nop IL_004b: ret } ") Dim method0 = compilation0.GetMember(Of MethodSymbol)("C.M") Dim method1 = compilation1.GetMember(Of MethodSymbol)("C.M") Dim generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), testData0.GetMethodData("C.M").EncDebugInfoProvider) Dim diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(New SemanticEdit(SemanticEditKind.Update, method0, method1, preserveLocalVariables:=True))) diff1.VerifyIL("C.M", " { // Code size 76 (0x4c) .maxstack 2 .locals init (System.Guid() V_0, //x Object V_1, Boolean V_2, System.Guid() V_3, //y Object V_4, Boolean V_5) IL_0000: nop IL_0001: ldnull IL_0002: stloc.0 IL_0003: nop IL_0004: ldloc.0 IL_0005: stloc.1 IL_0006: ldc.i4.0 IL_0007: stloc.2 .try { IL_0008: ldloc.1 IL_0009: ldloca.s V_2 IL_000b: call ""Sub System.Threading.Monitor.Enter(Object, ByRef Boolean)"" IL_0010: nop IL_0011: ldnull IL_0012: stloc.3 IL_0013: nop IL_0014: ldloc.3 IL_0015: stloc.s V_4 IL_0017: ldc.i4.0 IL_0018: stloc.s V_5 .try { IL_001a: ldloc.s V_4 IL_001c: ldloca.s V_5 IL_001e: call ""Sub System.Threading.Monitor.Enter(Object, ByRef Boolean)"" IL_0023: nop IL_0024: ldloc.0 IL_0025: callvirt ""Function Object.ToString() As String"" IL_002a: pop IL_002b: leave.s IL_003b } finally { IL_002d: ldloc.s V_5 IL_002f: brfalse.s IL_0039 IL_0031: ldloc.s V_4 IL_0033: call ""Sub System.Threading.Monitor.Exit(Object)"" IL_0038: nop IL_0039: nop IL_003a: endfinally } IL_003b: nop IL_003c: leave.s IL_004a } finally { IL_003e: ldloc.2 IL_003f: brfalse.s IL_0048 IL_0041: ldloc.1 IL_0042: call ""Sub System.Threading.Monitor.Exit(Object)"" IL_0047: nop IL_0048: nop IL_0049: endfinally } IL_004a: nop IL_004b: ret } ") End Sub ''' <summary> ''' Local slots must be preserved based on signature. ''' </summary> <Fact> Public Sub PreserveLocalSlotsForEach() Dim sources0 = <compilation> <file name="a.vb"><![CDATA[ Class A(Of T) End Class Class C Inherits A(Of C) Shared Function F() As C Return Nothing End Function Shared Sub M(o As Object) dim x as System.Collections.Generic.List(of integer) = nothing for each [i] in [x] Next for each i as integer in x Next End Sub End Class ]]></file> </compilation> Dim compilation0 = CreateCompilationWithMscorlib40(sources0, options:=TestOptions.DebugDll) Dim compilation1 = compilation0.Clone() Dim testData0 = New CompilationTestData() Dim bytes0 = compilation0.EmitToArray(testData:=testData0) testData0.GetMethodData("C.M").VerifyIL(" { // Code size 101 (0x65) .maxstack 1 .locals init (System.Collections.Generic.List(Of Integer) V_0, //x System.Collections.Generic.List(Of Integer).Enumerator V_1, Integer V_2, //i Boolean V_3, System.Collections.Generic.List(Of Integer).Enumerator V_4, Integer V_5, //i Boolean V_6) IL_0000: nop IL_0001: ldnull IL_0002: stloc.0 .try { IL_0003: ldloc.0 IL_0004: callvirt ""Function System.Collections.Generic.List(Of Integer).GetEnumerator() As System.Collections.Generic.List(Of Integer).Enumerator"" IL_0009: stloc.1 IL_000a: br.s IL_0015 IL_000c: ldloca.s V_1 IL_000e: call ""Function System.Collections.Generic.List(Of Integer).Enumerator.get_Current() As Integer"" IL_0013: stloc.2 IL_0014: nop IL_0015: ldloca.s V_1 IL_0017: call ""Function System.Collections.Generic.List(Of Integer).Enumerator.MoveNext() As Boolean"" IL_001c: stloc.3 IL_001d: ldloc.3 IL_001e: brtrue.s IL_000c IL_0020: leave.s IL_0031 } finally { IL_0022: ldloca.s V_1 IL_0024: constrained. ""System.Collections.Generic.List(Of Integer).Enumerator"" IL_002a: callvirt ""Sub System.IDisposable.Dispose()"" IL_002f: nop IL_0030: endfinally } IL_0031: nop .try { IL_0032: ldloc.0 IL_0033: callvirt ""Function System.Collections.Generic.List(Of Integer).GetEnumerator() As System.Collections.Generic.List(Of Integer).Enumerator"" IL_0038: stloc.s V_4 IL_003a: br.s IL_0046 IL_003c: ldloca.s V_4 IL_003e: call ""Function System.Collections.Generic.List(Of Integer).Enumerator.get_Current() As Integer"" IL_0043: stloc.s V_5 IL_0045: nop IL_0046: ldloca.s V_4 IL_0048: call ""Function System.Collections.Generic.List(Of Integer).Enumerator.MoveNext() As Boolean"" IL_004d: stloc.s V_6 IL_004f: ldloc.s V_6 IL_0051: brtrue.s IL_003c IL_0053: leave.s IL_0064 } finally { IL_0055: ldloca.s V_4 IL_0057: constrained. ""System.Collections.Generic.List(Of Integer).Enumerator"" IL_005d: callvirt ""Sub System.IDisposable.Dispose()"" IL_0062: nop IL_0063: endfinally } IL_0064: ret } ") Dim method0 = compilation0.GetMember(Of MethodSymbol)("C.M") Dim method1 = compilation1.GetMember(Of MethodSymbol)("C.M") Dim generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), testData0.GetMethodData("C.M").EncDebugInfoProvider) Dim diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(New SemanticEdit(SemanticEditKind.Update, method0, method1, preserveLocalVariables:=True))) diff1.VerifyIL("C.M", " { // Code size 101 (0x65) .maxstack 1 .locals init (System.Collections.Generic.List(Of Integer) V_0, //x System.Collections.Generic.List(Of Integer).Enumerator V_1, Integer V_2, //i Boolean V_3, System.Collections.Generic.List(Of Integer).Enumerator V_4, Integer V_5, //i Boolean V_6) IL_0000: nop IL_0001: ldnull IL_0002: stloc.0 .try { IL_0003: ldloc.0 IL_0004: callvirt ""Function System.Collections.Generic.List(Of Integer).GetEnumerator() As System.Collections.Generic.List(Of Integer).Enumerator"" IL_0009: stloc.1 IL_000a: br.s IL_0015 IL_000c: ldloca.s V_1 IL_000e: call ""Function System.Collections.Generic.List(Of Integer).Enumerator.get_Current() As Integer"" IL_0013: stloc.2 IL_0014: nop IL_0015: ldloca.s V_1 IL_0017: call ""Function System.Collections.Generic.List(Of Integer).Enumerator.MoveNext() As Boolean"" IL_001c: stloc.3 IL_001d: ldloc.3 IL_001e: brtrue.s IL_000c IL_0020: leave.s IL_0031 } finally { IL_0022: ldloca.s V_1 IL_0024: constrained. ""System.Collections.Generic.List(Of Integer).Enumerator"" IL_002a: callvirt ""Sub System.IDisposable.Dispose()"" IL_002f: nop IL_0030: endfinally } IL_0031: nop .try { IL_0032: ldloc.0 IL_0033: callvirt ""Function System.Collections.Generic.List(Of Integer).GetEnumerator() As System.Collections.Generic.List(Of Integer).Enumerator"" IL_0038: stloc.s V_4 IL_003a: br.s IL_0046 IL_003c: ldloca.s V_4 IL_003e: call ""Function System.Collections.Generic.List(Of Integer).Enumerator.get_Current() As Integer"" IL_0043: stloc.s V_5 IL_0045: nop IL_0046: ldloca.s V_4 IL_0048: call ""Function System.Collections.Generic.List(Of Integer).Enumerator.MoveNext() As Boolean"" IL_004d: stloc.s V_6 IL_004f: ldloc.s V_6 IL_0051: brtrue.s IL_003c IL_0053: leave.s IL_0064 } finally { IL_0055: ldloca.s V_4 IL_0057: constrained. ""System.Collections.Generic.List(Of Integer).Enumerator"" IL_005d: callvirt ""Sub System.IDisposable.Dispose()"" IL_0062: nop IL_0063: endfinally } IL_0064: ret } ") End Sub ''' <summary> ''' Local slots must be preserved based on signature. ''' </summary> <Fact> Public Sub PreserveLocalSlotsForEach001() Dim sources0 = <compilation> <file name="a.vb"><![CDATA[ Class A(Of T) End Class Class C Inherits A(Of C) Shared Function F() As C Return Nothing End Function Shared Sub M(o As Object) dim x as System.Collections.Generic.List(of integer) = nothing Dim i as integer for each i in x Next for each i in x Next End Sub End Class ]]></file> </compilation> Dim compilation0 = CreateCompilationWithMscorlib40(sources0, options:=TestOptions.DebugDll) Dim compilation1 = compilation0.Clone() Dim testData0 = New CompilationTestData() Dim bytes0 = compilation0.EmitToArray(testData:=testData0) testData0.GetMethodData("C.M").VerifyIL(" { // Code size 100 (0x64) .maxstack 1 .locals init (System.Collections.Generic.List(Of Integer) V_0, //x Integer V_1, //i System.Collections.Generic.List(Of Integer).Enumerator V_2, Boolean V_3, System.Collections.Generic.List(Of Integer).Enumerator V_4, Boolean V_5) IL_0000: nop IL_0001: ldnull IL_0002: stloc.0 .try { IL_0003: ldloc.0 IL_0004: callvirt ""Function System.Collections.Generic.List(Of Integer).GetEnumerator() As System.Collections.Generic.List(Of Integer).Enumerator"" IL_0009: stloc.2 IL_000a: br.s IL_0015 IL_000c: ldloca.s V_2 IL_000e: call ""Function System.Collections.Generic.List(Of Integer).Enumerator.get_Current() As Integer"" IL_0013: stloc.1 IL_0014: nop IL_0015: ldloca.s V_2 IL_0017: call ""Function System.Collections.Generic.List(Of Integer).Enumerator.MoveNext() As Boolean"" IL_001c: stloc.3 IL_001d: ldloc.3 IL_001e: brtrue.s IL_000c IL_0020: leave.s IL_0031 } finally { IL_0022: ldloca.s V_2 IL_0024: constrained. ""System.Collections.Generic.List(Of Integer).Enumerator"" IL_002a: callvirt ""Sub System.IDisposable.Dispose()"" IL_002f: nop IL_0030: endfinally } IL_0031: nop .try { IL_0032: ldloc.0 IL_0033: callvirt ""Function System.Collections.Generic.List(Of Integer).GetEnumerator() As System.Collections.Generic.List(Of Integer).Enumerator"" IL_0038: stloc.s V_4 IL_003a: br.s IL_0045 IL_003c: ldloca.s V_4 IL_003e: call ""Function System.Collections.Generic.List(Of Integer).Enumerator.get_Current() As Integer"" IL_0043: stloc.1 IL_0044: nop IL_0045: ldloca.s V_4 IL_0047: call ""Function System.Collections.Generic.List(Of Integer).Enumerator.MoveNext() As Boolean"" IL_004c: stloc.s V_5 IL_004e: ldloc.s V_5 IL_0050: brtrue.s IL_003c IL_0052: leave.s IL_0063 } finally { IL_0054: ldloca.s V_4 IL_0056: constrained. ""System.Collections.Generic.List(Of Integer).Enumerator"" IL_005c: callvirt ""Sub System.IDisposable.Dispose()"" IL_0061: nop IL_0062: endfinally } IL_0063: ret } ") Dim method0 = compilation0.GetMember(Of MethodSymbol)("C.M") Dim method1 = compilation1.GetMember(Of MethodSymbol)("C.M") Dim generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), testData0.GetMethodData("C.M").EncDebugInfoProvider) Dim diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(New SemanticEdit(SemanticEditKind.Update, method0, method1, preserveLocalVariables:=True))) diff1.VerifyIL("C.M", " { // Code size 100 (0x64) .maxstack 1 .locals init (System.Collections.Generic.List(Of Integer) V_0, //x Integer V_1, //i System.Collections.Generic.List(Of Integer).Enumerator V_2, Boolean V_3, System.Collections.Generic.List(Of Integer).Enumerator V_4, Boolean V_5) IL_0000: nop IL_0001: ldnull IL_0002: stloc.0 .try { IL_0003: ldloc.0 IL_0004: callvirt ""Function System.Collections.Generic.List(Of Integer).GetEnumerator() As System.Collections.Generic.List(Of Integer).Enumerator"" IL_0009: stloc.2 IL_000a: br.s IL_0015 IL_000c: ldloca.s V_2 IL_000e: call ""Function System.Collections.Generic.List(Of Integer).Enumerator.get_Current() As Integer"" IL_0013: stloc.1 IL_0014: nop IL_0015: ldloca.s V_2 IL_0017: call ""Function System.Collections.Generic.List(Of Integer).Enumerator.MoveNext() As Boolean"" IL_001c: stloc.3 IL_001d: ldloc.3 IL_001e: brtrue.s IL_000c IL_0020: leave.s IL_0031 } finally { IL_0022: ldloca.s V_2 IL_0024: constrained. ""System.Collections.Generic.List(Of Integer).Enumerator"" IL_002a: callvirt ""Sub System.IDisposable.Dispose()"" IL_002f: nop IL_0030: endfinally } IL_0031: nop .try { IL_0032: ldloc.0 IL_0033: callvirt ""Function System.Collections.Generic.List(Of Integer).GetEnumerator() As System.Collections.Generic.List(Of Integer).Enumerator"" IL_0038: stloc.s V_4 IL_003a: br.s IL_0045 IL_003c: ldloca.s V_4 IL_003e: call ""Function System.Collections.Generic.List(Of Integer).Enumerator.get_Current() As Integer"" IL_0043: stloc.1 IL_0044: nop IL_0045: ldloca.s V_4 IL_0047: call ""Function System.Collections.Generic.List(Of Integer).Enumerator.MoveNext() As Boolean"" IL_004c: stloc.s V_5 IL_004e: ldloc.s V_5 IL_0050: brtrue.s IL_003c IL_0052: leave.s IL_0063 } finally { IL_0054: ldloca.s V_4 IL_0056: constrained. ""System.Collections.Generic.List(Of Integer).Enumerator"" IL_005c: callvirt ""Sub System.IDisposable.Dispose()"" IL_0061: nop IL_0062: endfinally } IL_0063: ret } ") End Sub ''' <summary> ''' Local slots must be preserved based on signature. ''' </summary> <Fact> Public Sub PreserveLocalSlotsFor001() Dim sources0 = <compilation> <file name="a.vb"><![CDATA[ Class A(Of T) End Class Class C Inherits A(Of C) Shared Function F() As C Return Nothing End Function Shared Sub M(o As object) for i as double = goo() to goo() step goo() for j as double = goo() to goo() step goo() next next End Sub shared function goo() as double return 1 end function End Class ]]></file> </compilation> Dim compilation0 = CreateCompilationWithMscorlib40(sources0, options:=TestOptions.DebugDll) Dim compilation1 = compilation0.Clone() Dim testData0 = New CompilationTestData() Dim bytes0 = compilation0.EmitToArray(testData:=testData0) testData0.GetMethodData("C.M").VerifyIL(" { // Code size 148 (0x94) .maxstack 2 .locals init (Double V_0, Double V_1, Double V_2, Boolean V_3, Double V_4, //i Double V_5, Double V_6, Double V_7, Boolean V_8, Double V_9) //j IL_0000: nop IL_0001: call ""Function C.goo() As Double"" IL_0006: stloc.0 IL_0007: call ""Function C.goo() As Double"" IL_000c: stloc.1 IL_000d: call ""Function C.goo() As Double"" IL_0012: stloc.2 IL_0013: ldloc.2 IL_0014: ldc.r8 0 IL_001d: clt.un IL_001f: ldc.i4.0 IL_0020: ceq IL_0022: stloc.3 IL_0023: ldloc.0 IL_0024: stloc.s V_4 IL_0026: br.s IL_007c IL_0028: call ""Function C.goo() As Double"" IL_002d: stloc.s V_5 IL_002f: call ""Function C.goo() As Double"" IL_0034: stloc.s V_6 IL_0036: call ""Function C.goo() As Double"" IL_003b: stloc.s V_7 IL_003d: ldloc.s V_7 IL_003f: ldc.r8 0 IL_0048: clt.un IL_004a: ldc.i4.0 IL_004b: ceq IL_004d: stloc.s V_8 IL_004f: ldloc.s V_5 IL_0051: stloc.s V_9 IL_0053: br.s IL_005c IL_0055: ldloc.s V_9 IL_0057: ldloc.s V_7 IL_0059: add IL_005a: stloc.s V_9 IL_005c: ldloc.s V_8 IL_005e: brtrue.s IL_006b IL_0060: ldloc.s V_9 IL_0062: ldloc.s V_6 IL_0064: clt.un IL_0066: ldc.i4.0 IL_0067: ceq IL_0069: br.s IL_0074 IL_006b: ldloc.s V_9 IL_006d: ldloc.s V_6 IL_006f: cgt.un IL_0071: ldc.i4.0 IL_0072: ceq IL_0074: brtrue.s IL_0055 IL_0076: ldloc.s V_4 IL_0078: ldloc.2 IL_0079: add IL_007a: stloc.s V_4 IL_007c: ldloc.3 IL_007d: brtrue.s IL_0089 IL_007f: ldloc.s V_4 IL_0081: ldloc.1 IL_0082: clt.un IL_0084: ldc.i4.0 IL_0085: ceq IL_0087: br.s IL_0091 IL_0089: ldloc.s V_4 IL_008b: ldloc.1 IL_008c: cgt.un IL_008e: ldc.i4.0 IL_008f: ceq IL_0091: brtrue.s IL_0028 IL_0093: ret } ") Dim method0 = compilation0.GetMember(Of MethodSymbol)("C.M") Dim method1 = compilation1.GetMember(Of MethodSymbol)("C.M") Dim generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), testData0.GetMethodData("C.M").EncDebugInfoProvider) Dim diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(New SemanticEdit(SemanticEditKind.Update, method0, method1, preserveLocalVariables:=True))) diff1.VerifyIL("C.M", " { // Code size 148 (0x94) .maxstack 2 .locals init (Double V_0, Double V_1, Double V_2, Boolean V_3, Double V_4, //i Double V_5, Double V_6, Double V_7, Boolean V_8, Double V_9) //j IL_0000: nop IL_0001: call ""Function C.goo() As Double"" IL_0006: stloc.0 IL_0007: call ""Function C.goo() As Double"" IL_000c: stloc.1 IL_000d: call ""Function C.goo() As Double"" IL_0012: stloc.2 IL_0013: ldloc.2 IL_0014: ldc.r8 0 IL_001d: clt.un IL_001f: ldc.i4.0 IL_0020: ceq IL_0022: stloc.3 IL_0023: ldloc.0 IL_0024: stloc.s V_4 IL_0026: br.s IL_007c IL_0028: call ""Function C.goo() As Double"" IL_002d: stloc.s V_5 IL_002f: call ""Function C.goo() As Double"" IL_0034: stloc.s V_6 IL_0036: call ""Function C.goo() As Double"" IL_003b: stloc.s V_7 IL_003d: ldloc.s V_7 IL_003f: ldc.r8 0 IL_0048: clt.un IL_004a: ldc.i4.0 IL_004b: ceq IL_004d: stloc.s V_8 IL_004f: ldloc.s V_5 IL_0051: stloc.s V_9 IL_0053: br.s IL_005c IL_0055: ldloc.s V_9 IL_0057: ldloc.s V_7 IL_0059: add IL_005a: stloc.s V_9 IL_005c: ldloc.s V_8 IL_005e: brtrue.s IL_006b IL_0060: ldloc.s V_9 IL_0062: ldloc.s V_6 IL_0064: clt.un IL_0066: ldc.i4.0 IL_0067: ceq IL_0069: br.s IL_0074 IL_006b: ldloc.s V_9 IL_006d: ldloc.s V_6 IL_006f: cgt.un IL_0071: ldc.i4.0 IL_0072: ceq IL_0074: brtrue.s IL_0055 IL_0076: ldloc.s V_4 IL_0078: ldloc.2 IL_0079: add IL_007a: stloc.s V_4 IL_007c: ldloc.3 IL_007d: brtrue.s IL_0089 IL_007f: ldloc.s V_4 IL_0081: ldloc.1 IL_0082: clt.un IL_0084: ldc.i4.0 IL_0085: ceq IL_0087: br.s IL_0091 IL_0089: ldloc.s V_4 IL_008b: ldloc.1 IL_008c: cgt.un IL_008e: ldc.i4.0 IL_008f: ceq IL_0091: brtrue.s IL_0028 IL_0093: ret } ") End Sub ''' <summary> ''' Local slots must be preserved based on signature. ''' </summary> <Fact> Public Sub PreserveLocalSlotsImplicit() Dim sources0 = <compilation> <file name="a.vb"><![CDATA[ option explicit off Class A(Of T) End Class Class C Inherits A(Of C) Shared Function F() As C Return Nothing End Function Shared Sub M(o As Object) dim x as System.Guid() = nothing With x Dim z = .ToString y = z end With End Sub End Class ]]></file> </compilation> Dim compilation0 = CreateCompilationWithMscorlib40(sources0, options:=TestOptions.DebugDll) Dim compilation1 = compilation0.Clone() Dim testData0 = New CompilationTestData() Dim bytes0 = compilation0.EmitToArray(testData:=testData0) testData0.GetMethodData("C.M").VerifyIL(" { // Code size 19 (0x13) .maxstack 1 .locals init (Object V_0, //y System.Guid() V_1, //x System.Guid() V_2, //$W0 String V_3) //z IL_0000: nop IL_0001: ldnull IL_0002: stloc.1 IL_0003: nop IL_0004: ldloc.1 IL_0005: stloc.2 IL_0006: ldloc.2 IL_0007: callvirt ""Function Object.ToString() As String"" IL_000c: stloc.3 IL_000d: ldloc.3 IL_000e: stloc.0 IL_000f: nop IL_0010: ldnull IL_0011: stloc.2 IL_0012: ret } ") Dim method0 = compilation0.GetMember(Of MethodSymbol)("C.M") Dim method1 = compilation1.GetMember(Of MethodSymbol)("C.M") Dim generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), testData0.GetMethodData("C.M").EncDebugInfoProvider) Dim edit = New SemanticEdit(SemanticEditKind.Update, method0, method1, preserveLocalVariables:=True) Dim diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(edit)) diff1.VerifyIL("C.M", " { // Code size 19 (0x13) .maxstack 1 .locals init (Object V_0, //y System.Guid() V_1, //x System.Guid() V_2, //$W0 String V_3) //z IL_0000: nop IL_0001: ldnull IL_0002: stloc.1 IL_0003: nop IL_0004: ldloc.1 IL_0005: stloc.2 IL_0006: ldloc.2 IL_0007: callvirt ""Function Object.ToString() As String"" IL_000c: stloc.3 IL_000d: ldloc.3 IL_000e: stloc.0 IL_000f: nop IL_0010: ldnull IL_0011: stloc.2 IL_0012: ret } ") End Sub ''' <summary> ''' Local slots must be preserved based on signature. ''' </summary> <Fact> Public Sub PreserveLocalSlotsImplicitQualified() Dim sources0 = <compilation> <file name="a.vb"><![CDATA[ option explicit off Class A(Of T) End Class Class C Inherits A(Of C) Shared Function F() As C Return Nothing End Function Shared Sub M(o As Object) dim x as System.Guid() = nothing goto Length ' this does not declare Length Length: ' this does not declare Length dim y = x.Length ' this does not declare Length Length = 5 ' this does End Sub End Class ]]></file> </compilation> Dim compilation0 = CreateCompilationWithMscorlib40(sources0, options:=TestOptions.DebugDll) Dim compilation1 = compilation0.Clone() Dim testData0 = New CompilationTestData() Dim bytes0 = compilation0.EmitToArray(testData:=testData0) Dim actualIL0 = testData0.GetMethodData("C.M").GetMethodIL() Dim expectedIL0 = " { // Code size 18 (0x12) .maxstack 1 .locals init (Object V_0, //Length System.Guid() V_1, //x Integer V_2) //y IL_0000: nop IL_0001: ldnull IL_0002: stloc.1 IL_0003: br.s IL_0005 IL_0005: nop IL_0006: ldloc.1 IL_0007: ldlen IL_0008: conv.i4 IL_0009: stloc.2 IL_000a: ldc.i4.5 IL_000b: box ""Integer"" IL_0010: stloc.0 IL_0011: ret } " AssertEx.AssertEqualToleratingWhitespaceDifferences(expectedIL0, actualIL0) Dim method0 = compilation0.GetMember(Of MethodSymbol)("C.M") Dim method1 = compilation1.GetMember(Of MethodSymbol)("C.M") Dim generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), testData0.GetMethodData("C.M").EncDebugInfoProvider) Dim edit = New SemanticEdit(SemanticEditKind.Update, method0, method1, preserveLocalVariables:=True) Dim diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(edit)) diff1.VerifyIL("C.M", " { // Code size 18 (0x12) .maxstack 1 .locals init (Object V_0, //Length System.Guid() V_1, //x Integer V_2) //y IL_0000: nop IL_0001: ldnull IL_0002: stloc.1 IL_0003: br.s IL_0005 IL_0005: nop IL_0006: ldloc.1 IL_0007: ldlen IL_0008: conv.i4 IL_0009: stloc.2 IL_000a: ldc.i4.5 IL_000b: box ""Integer"" IL_0010: stloc.0 IL_0011: ret } ") End Sub ''' <summary> ''' Local slots must be preserved based on signature. ''' </summary> <Fact> Public Sub PreserveLocalSlotsImplicitXmlNs() Dim sources0 = <compilation> <file name="a.vb"><![CDATA[ option explicit off Imports <xmlns:Length="http: //roslyn/F"> Class A(Of T) End Class Class C Inherits A(Of C) Shared Function F() As C Return Nothing End Function Shared Sub M(o As Object) dim x as System.Guid() = nothing GetXmlNamespace(Length).ToString() ' this does not declare Length dim z as object = GetXmlNamespace(Length) ' this does not declare Length Length = 5 ' this does Dim aa = Length End Sub End Class ]]></file> </compilation> Dim compilation0 = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(sources0, XmlReferences, TestOptions.DebugDll) Dim compilation1 = compilation0.Clone() Dim testData0 = New CompilationTestData() Dim bytes0 = compilation0.EmitToArray(testData:=testData0) testData0.GetMethodData("C.M").VerifyIL(" { // Code size 45 (0x2d) .maxstack 1 .locals init (Object V_0, //Length System.Guid() V_1, //x Object V_2, //z Object V_3) //aa IL_0000: nop IL_0001: ldnull IL_0002: stloc.1 IL_0003: ldstr ""http: //roslyn/F"" IL_0008: call ""Function System.Xml.Linq.XNamespace.Get(String) As System.Xml.Linq.XNamespace"" IL_000d: callvirt ""Function System.Xml.Linq.XNamespace.ToString() As String"" IL_0012: pop IL_0013: ldstr ""http: //roslyn/F"" IL_0018: call ""Function System.Xml.Linq.XNamespace.Get(String) As System.Xml.Linq.XNamespace"" IL_001d: stloc.2 IL_001e: ldc.i4.5 IL_001f: box ""Integer"" IL_0024: stloc.0 IL_0025: ldloc.0 IL_0026: call ""Function System.Runtime.CompilerServices.RuntimeHelpers.GetObjectValue(Object) As Object"" IL_002b: stloc.3 IL_002c: ret } ") Dim method0 = compilation0.GetMember(Of MethodSymbol)("C.M") Dim method1 = compilation1.GetMember(Of MethodSymbol)("C.M") Dim generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), testData0.GetMethodData("C.M").EncDebugInfoProvider) Dim edit = New SemanticEdit(SemanticEditKind.Update, method0, method1, preserveLocalVariables:=True) Dim diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(edit)) diff1.VerifyIL("C.M", " { // Code size 45 (0x2d) .maxstack 1 .locals init (Object V_0, //Length System.Guid() V_1, //x Object V_2, //z Object V_3) //aa IL_0000: nop IL_0001: ldnull IL_0002: stloc.1 IL_0003: ldstr ""http: //roslyn/F"" IL_0008: call ""Function System.Xml.Linq.XNamespace.Get(String) As System.Xml.Linq.XNamespace"" IL_000d: callvirt ""Function System.Xml.Linq.XNamespace.ToString() As String"" IL_0012: pop IL_0013: ldstr ""http: //roslyn/F"" IL_0018: call ""Function System.Xml.Linq.XNamespace.Get(String) As System.Xml.Linq.XNamespace"" IL_001d: stloc.2 IL_001e: ldc.i4.5 IL_001f: box ""Integer"" IL_0024: stloc.0 IL_0025: ldloc.0 IL_0026: call ""Function System.Runtime.CompilerServices.RuntimeHelpers.GetObjectValue(Object) As Object"" IL_002b: stloc.3 IL_002c: ret } ") End Sub ''' <summary> ''' Local slots must be preserved based on signature. ''' </summary> <Fact> Public Sub PreserveLocalSlotsImplicitNamedArgXml() Dim sources0 = <compilation> <file name="a.vb"><![CDATA[ Option Explicit Off Class A(Of T) End Class Class C Inherits A(Of C) Shared Function F() As C Return Nothing End Function Shared Sub F(qq As Object) End Sub Shared Sub M(o As Object) F(qq:=<qq a="qq"></>) 'does not declare qq qq = 5 Dim aa = qq End Sub End Class ]]></file> </compilation> Dim compilation0 = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(sources0, XmlReferences, TestOptions.DebugDll) Dim compilation1 = compilation0.Clone() Dim testData0 = New CompilationTestData() Dim bytes0 = compilation0.EmitToArray(testData:=testData0) Dim actualIL0 = testData0.GetMethodData("C.M").GetMethodIL() Dim expectedIL0 = <![CDATA[ { // Code size 88 (0x58) .maxstack 3 .locals init (Object V_0, //qq Object V_1, //aa System.Xml.Linq.XElement V_2) IL_0000: nop IL_0001: ldstr "qq" IL_0006: ldstr "" IL_000b: call "Function System.Xml.Linq.XName.Get(String, String) As System.Xml.Linq.XName" IL_0010: newobj "Sub System.Xml.Linq.XElement..ctor(System.Xml.Linq.XName)" IL_0015: stloc.2 IL_0016: ldloc.2 IL_0017: ldstr "a" IL_001c: ldstr "" IL_0021: call "Function System.Xml.Linq.XName.Get(String, String) As System.Xml.Linq.XName" IL_0026: ldstr "qq" IL_002b: newobj "Sub System.Xml.Linq.XAttribute..ctor(System.Xml.Linq.XName, Object)" IL_0030: callvirt "Sub System.Xml.Linq.XContainer.Add(Object)" IL_0035: nop IL_0036: ldloc.2 IL_0037: ldstr "" IL_003c: callvirt "Sub System.Xml.Linq.XContainer.Add(Object)" IL_0041: nop IL_0042: ldloc.2 IL_0043: call "Sub C.F(Object)" IL_0048: nop IL_0049: ldc.i4.5 IL_004a: box "Integer" IL_004f: stloc.0 IL_0050: ldloc.0 IL_0051: call "Function System.Runtime.CompilerServices.RuntimeHelpers.GetObjectValue(Object) As Object" IL_0056: stloc.1 IL_0057: ret } ]]>.Value AssertEx.AssertEqualToleratingWhitespaceDifferences(expectedIL0, actualIL0) Dim method0 = compilation0.GetMember(Of MethodSymbol)("C.M") Dim method1 = compilation1.GetMember(Of MethodSymbol)("C.M") Dim generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), testData0.GetMethodData("C.M").EncDebugInfoProvider) Dim edit = New SemanticEdit(SemanticEditKind.Update, method0, method1, preserveLocalVariables:=True) Dim diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(edit)) diff1.VerifyIL("C.M", <![CDATA[ { // Code size 88 (0x58) .maxstack 3 .locals init (Object V_0, //qq Object V_1, //aa [unchanged] V_2, System.Xml.Linq.XElement V_3) IL_0000: nop IL_0001: ldstr "qq" IL_0006: ldstr "" IL_000b: call "Function System.Xml.Linq.XName.Get(String, String) As System.Xml.Linq.XName" IL_0010: newobj "Sub System.Xml.Linq.XElement..ctor(System.Xml.Linq.XName)" IL_0015: stloc.3 IL_0016: ldloc.3 IL_0017: ldstr "a" IL_001c: ldstr "" IL_0021: call "Function System.Xml.Linq.XName.Get(String, String) As System.Xml.Linq.XName" IL_0026: ldstr "qq" IL_002b: newobj "Sub System.Xml.Linq.XAttribute..ctor(System.Xml.Linq.XName, Object)" IL_0030: callvirt "Sub System.Xml.Linq.XContainer.Add(Object)" IL_0035: nop IL_0036: ldloc.3 IL_0037: ldstr "" IL_003c: callvirt "Sub System.Xml.Linq.XContainer.Add(Object)" IL_0041: nop IL_0042: ldloc.3 IL_0043: call "Sub C.F(Object)" IL_0048: nop IL_0049: ldc.i4.5 IL_004a: box "Integer" IL_004f: stloc.0 IL_0050: ldloc.0 IL_0051: call "Function System.Runtime.CompilerServices.RuntimeHelpers.GetObjectValue(Object) As Object" IL_0056: stloc.1 IL_0057: ret } ]]>.Value) End Sub <Fact> Public Sub AnonymousTypes_Update() Dim source0 = MarkedSource(" Class C Shared Sub F() Dim <N:0>x</N:0> = New With { .A = 1 } End Sub End Class ") Dim source1 = MarkedSource(" Class C Shared Sub F() Dim <N:0>x</N:0> = New With { .A = 2 } End Sub End Class ") Dim source2 = MarkedSource(" Class C Shared Sub F() Dim <N:0>x</N:0> = New With { .A = 3 } End Sub End Class ") Dim compilation0 = CreateCompilationWithMscorlib40(source0.Tree, options:=ComSafeDebugDll.WithMetadataImportOptions(MetadataImportOptions.All)) Dim compilation1 = compilation0.WithSource(source1.Tree) Dim compilation2 = compilation1.WithSource(source2.Tree) Dim v0 = CompileAndVerify(compilation0) Dim md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData) Dim f0 = compilation0.GetMember(Of MethodSymbol)("C.F") Dim f1 = compilation1.GetMember(Of MethodSymbol)("C.F") Dim f2 = compilation2.GetMember(Of MethodSymbol)("C.F") Dim generation0 = EmitBaseline.CreateInitialBaseline(md0, AddressOf v0.CreateSymReader().GetEncMethodDebugInfo) v0.VerifyIL("C.F", " { // Code size 9 (0x9) .maxstack 1 .locals init (VB$AnonymousType_0(Of Integer) V_0) //x IL_0000: nop IL_0001: ldc.i4.1 IL_0002: newobj ""Sub VB$AnonymousType_0(Of Integer)..ctor(Integer)"" IL_0007: stloc.0 IL_0008: ret } ") Dim diff1 = compilation1.EmitDifference(generation0, ImmutableArray.Create( New SemanticEdit(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables:=True))) diff1.VerifyIL("C.F", " { // Code size 9 (0x9) .maxstack 1 .locals init (VB$AnonymousType_0(Of Integer) V_0) //x IL_0000: nop IL_0001: ldc.i4.2 IL_0002: newobj ""Sub VB$AnonymousType_0(Of Integer)..ctor(Integer)"" IL_0007: stloc.0 IL_0008: ret } ") ' expect a single TypeRef for System.Object Dim md1 = diff1.GetMetadata() AssertEx.Equal({"[0x23000002] 0x0000020d.0x0000021a"}, DumpTypeRefs(md1.Reader)) Dim diff2 = compilation2.EmitDifference(diff1.NextGeneration, ImmutableArray.Create( New SemanticEdit(SemanticEditKind.Update, f1, f2, GetSyntaxMapFromMarkers(source1, source2), preserveLocalVariables:=True))) diff2.VerifyIL("C.F", " { // Code size 9 (0x9) .maxstack 1 .locals init (VB$AnonymousType_0(Of Integer) V_0) //x IL_0000: nop IL_0001: ldc.i4.3 IL_0002: newobj ""Sub VB$AnonymousType_0(Of Integer)..ctor(Integer)"" IL_0007: stloc.0 IL_0008: ret } ") ' expect a single TypeRef for System.Object Dim md2 = diff2.GetMetadata() AssertEx.Equal({"[0x23000003] 0x00000256.0x00000263"}, DumpTypeRefs(md2.Reader)) End Sub <Fact> Public Sub AnonymousTypes_UpdateAfterAdd() Dim source0 = MarkedSource(" Class C Shared Sub F() End Sub End Class ") Dim source1 = MarkedSource(" Class C Shared Sub F() Dim <N:0>x</N:0> = New With { .A = 2 } End Sub End Class ") Dim source2 = MarkedSource(" Class C Shared Sub F() Dim <N:0>x</N:0> = New With { .A = 3 } End Sub End Class ") Dim compilation0 = CreateCompilationWithMscorlib40(source0.Tree, options:=ComSafeDebugDll.WithMetadataImportOptions(MetadataImportOptions.All)) Dim compilation1 = compilation0.WithSource(source1.Tree) Dim compilation2 = compilation1.WithSource(source2.Tree) Dim v0 = CompileAndVerify(compilation0) Dim md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData) Dim f0 = compilation0.GetMember(Of MethodSymbol)("C.F") Dim f1 = compilation1.GetMember(Of MethodSymbol)("C.F") Dim f2 = compilation2.GetMember(Of MethodSymbol)("C.F") Dim generation0 = EmitBaseline.CreateInitialBaseline(md0, AddressOf v0.CreateSymReader().GetEncMethodDebugInfo) Dim diff1 = compilation1.EmitDifference(generation0, ImmutableArray.Create( New SemanticEdit(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables:=True))) diff1.VerifyIL("C.F", " { // Code size 9 (0x9) .maxstack 1 .locals init (VB$AnonymousType_0(Of Integer) V_0) //x IL_0000: nop IL_0001: ldc.i4.2 IL_0002: newobj ""Sub VB$AnonymousType_0(Of Integer)..ctor(Integer)"" IL_0007: stloc.0 IL_0008: ret } ") Dim diff2 = compilation2.EmitDifference(diff1.NextGeneration, ImmutableArray.Create( New SemanticEdit(SemanticEditKind.Update, f1, f2, GetSyntaxMapFromMarkers(source1, source2), preserveLocalVariables:=True))) diff2.VerifyIL("C.F", " { // Code size 9 (0x9) .maxstack 1 .locals init (VB$AnonymousType_0(Of Integer) V_0) //x IL_0000: nop IL_0001: ldc.i4.3 IL_0002: newobj ""Sub VB$AnonymousType_0(Of Integer)..ctor(Integer)"" IL_0007: stloc.0 IL_0008: ret } ") ' expect a single TypeRef for System.Object Dim md2 = diff2.GetMetadata() AssertEx.Equal({"[0x23000003] 0x00000289.0x00000296"}, DumpTypeRefs(md2.Reader)) End Sub Private Shared Iterator Function DumpTypeRefs(reader As MetadataReader) As IEnumerable(Of String) For Each typeRefHandle In reader.TypeReferences Dim typeRef = reader.GetTypeReference(typeRefHandle) Yield $"[0x{MetadataTokens.GetToken(typeRef.ResolutionScope):x8}] 0x{MetadataTokens.GetHeapOffset(typeRef.Namespace):x8}.0x{MetadataTokens.GetHeapOffset(typeRef.Name):x8}" Next End Function <Fact> Public Sub AnonymousTypes() Dim sources0 = <compilation> <file name="a.vb"><![CDATA[ Namespace N Class A Shared F As Object = New With {.A = 1, .B = 2} End Class End Namespace Namespace M Class B Shared Sub M() Dim x As New With {.B = 3, .A = 4} Dim y = x.A Dim z As New With {.C = 5} End Sub End Class End Namespace ]]></file> </compilation> Dim sources1 = <compilation> <file name="a.vb"><![CDATA[ Namespace N Class A Shared F As Object = New With {.A = 1, .B = 2} End Class End Namespace Namespace M Class B Shared Sub M() Dim x As New With {.B = 3, .A = 4} Dim y As New With {.A = x.A} Dim z As New With {.C = 5} End Sub End Class End Namespace ]]></file> </compilation> Dim compilation0 = CreateCompilationWithMscorlib40(sources0, options:=TestOptions.DebugDll) Dim compilation1 = compilation0.WithSource(sources1) Dim testData0 = New CompilationTestData() Dim bytes0 = compilation0.EmitToArray(testData:=testData0) Using md0 = ModuleMetadata.CreateFromImage(bytes0) Dim generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), testData0.GetMethodData("M.B.M").EncDebugInfoProvider) Dim method0 = compilation0.GetMember(Of MethodSymbol)("M.B.M") Dim reader0 = md0.MetadataReader CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "VB$AnonymousType_0`2", "VB$AnonymousType_1`2", "VB$AnonymousType_2`1", "A", "B") Dim method1 = compilation1.GetMember(Of MethodSymbol)("M.B.M") Dim diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(New SemanticEdit(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables:=True))) Using md1 = diff1.GetMetadata() Dim reader1 = md1.Reader CheckNames({reader0, reader1}, reader1.GetTypeDefNames(), "VB$AnonymousType_3`1") diff1.VerifyIL("M.B.M", " { // Code size 29 (0x1d) .maxstack 2 .locals init (VB$AnonymousType_1(Of Integer, Integer) V_0, //x [int] V_1, VB$AnonymousType_2(Of Integer) V_2, //z VB$AnonymousType_3(Of Integer) V_3) //y IL_0000: nop IL_0001: ldc.i4.3 IL_0002: ldc.i4.4 IL_0003: newobj ""Sub VB$AnonymousType_1(Of Integer, Integer)..ctor(Integer, Integer)"" IL_0008: stloc.0 IL_0009: ldloc.0 IL_000a: callvirt ""Function VB$AnonymousType_1(Of Integer, Integer).get_A() As Integer"" IL_000f: newobj ""Sub VB$AnonymousType_3(Of Integer)..ctor(Integer)"" IL_0014: stloc.3 IL_0015: ldc.i4.5 IL_0016: newobj ""Sub VB$AnonymousType_2(Of Integer)..ctor(Integer)"" IL_001b: stloc.2 IL_001c: ret } ") End Using End Using End Sub ''' <summary> ''' Update method with anonymous type that was ''' not directly referenced in previous generation. ''' </summary> <Fact> Public Sub AnonymousTypes_SkipGeneration() Dim source0 = MarkedSource(" Class A End Class Class B <N:3>Shared Function F() As Object</N:3> Dim <N:0>x</N:0> As New With {.A = 1} Return x.A End Function <N:4>Shared Function G() As Object</N:4> Dim <N:1>x</N:1> As Integer = 1 Return x End Function End Class ") Dim source1 = MarkedSource(" Class A End Class Class B <N:3>Shared Function F() As Object</N:3> Dim <N:0>x</N:0> As New With {.A = 1} Return x.A End Function <N:4>Shared Function G() As Object</N:4> Dim <N:1>x</N:1> As Integer = 1 Return x + 1 End Function End Class ") Dim source2 = MarkedSource(" Class A End Class Class B <N:3>Shared Function F() As Object</N:3> Dim <N:0>x</N:0> As New With {.A = 1} Return x.A End Function <N:4>Shared Function G() As Object</N:4> Dim <N:1>x</N:1> As New With {.A = New A()} Dim <N:2>y</N:2> As New With {.B = 2} Return x.A End Function End Class ") Dim source3 = MarkedSource(" Class A End Class Class B <N:3>Shared Function F() As Object</N:3> Dim <N:0>x</N:0> As New With {.A = 1} Return x.A End Function <N:4>Shared Function G() As Object</N:4> Dim <N:1>x</N:1> As New With {.A = New A()} Dim <N:2>y</N:2> As New With {.B = 3} Return y.B End Function End Class ") Dim compilation0 = CreateCompilationWithMscorlib40(source0.Tree, options:=ComSafeDebugDll) Dim compilation1 = compilation0.WithSource(source1.Tree) Dim compilation2 = compilation1.WithSource(source2.Tree) Dim compilation3 = compilation2.WithSource(source3.Tree) Dim v0 = CompileAndVerify(compilation0) Dim md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData) Dim generation0 = EmitBaseline.CreateInitialBaseline(md0, AddressOf v0.CreateSymReader().GetEncMethodDebugInfo) Dim method0 = compilation0.GetMember(Of MethodSymbol)("B.G") Dim method1 = compilation1.GetMember(Of MethodSymbol)("B.G") Dim method2 = compilation2.GetMember(Of MethodSymbol)("B.G") Dim method3 = compilation3.GetMember(Of MethodSymbol)("B.G") Dim reader0 = md0.MetadataReader CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "VB$AnonymousType_0`1", "A", "B") Dim diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(New SemanticEdit(SemanticEditKind.Update, method0, method1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables:=True))) Dim md1 = diff1.GetMetadata() Dim reader1 = md1.Reader CheckNames({reader0, reader1}, reader1.GetTypeDefNames()) ' no additional types diff1.VerifyIL("B.G", " { // Code size 16 (0x10) .maxstack 2 .locals init (Object V_0, //G Integer V_1) //x IL_0000: nop IL_0001: ldc.i4.1 IL_0002: stloc.1 IL_0003: ldloc.1 IL_0004: ldc.i4.1 IL_0005: add.ovf IL_0006: box ""Integer"" IL_000b: stloc.0 IL_000c: br.s IL_000e IL_000e: ldloc.0 IL_000f: ret } ") Dim diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create(New SemanticEdit(SemanticEditKind.Update, method1, method2, GetSyntaxMapFromMarkers(source1, source2), preserveLocalVariables:=True))) Dim md2 = diff2.GetMetadata() Dim reader2 = md2.Reader CheckNames({reader0, reader1, reader2}, reader2.GetTypeDefNames(), "VB$AnonymousType_1`1") ' one additional type diff2.VerifyIL("B.G", " { // Code size 30 (0x1e) .maxstack 1 .locals init (Object V_0, //G [int] V_1, VB$AnonymousType_0(Of A) V_2, //x VB$AnonymousType_1(Of Integer) V_3) //y IL_0000: nop IL_0001: newobj ""Sub A..ctor()"" IL_0006: newobj ""Sub VB$AnonymousType_0(Of A)..ctor(A)"" IL_000b: stloc.2 IL_000c: ldc.i4.2 IL_000d: newobj ""Sub VB$AnonymousType_1(Of Integer)..ctor(Integer)"" IL_0012: stloc.3 IL_0013: ldloc.2 IL_0014: callvirt ""Function VB$AnonymousType_0(Of A).get_A() As A"" IL_0019: stloc.0 IL_001a: br.s IL_001c IL_001c: ldloc.0 IL_001d: ret } ") Dim diff3 = compilation3.EmitDifference( diff2.NextGeneration, ImmutableArray.Create(New SemanticEdit(SemanticEditKind.Update, method2, method3, GetSyntaxMapFromMarkers(source2, source3), preserveLocalVariables:=True))) Dim md3 = diff3.GetMetadata() Dim reader3 = md3.Reader CheckNames({reader0, reader1, reader2, reader3}, reader3.GetTypeDefNames()) ' no additional types diff3.VerifyIL("B.G", " { // Code size 35 (0x23) .maxstack 1 .locals init (Object V_0, //G [int] V_1, VB$AnonymousType_0(Of A) V_2, //x VB$AnonymousType_1(Of Integer) V_3) //y IL_0000: nop IL_0001: newobj ""Sub A..ctor()"" IL_0006: newobj ""Sub VB$AnonymousType_0(Of A)..ctor(A)"" IL_000b: stloc.2 IL_000c: ldc.i4.3 IL_000d: newobj ""Sub VB$AnonymousType_1(Of Integer)..ctor(Integer)"" IL_0012: stloc.3 IL_0013: ldloc.3 IL_0014: callvirt ""Function VB$AnonymousType_1(Of Integer).get_B() As Integer"" IL_0019: box ""Integer"" IL_001e: stloc.0 IL_001f: br.s IL_0021 IL_0021: ldloc.0 IL_0022: ret } ") End Sub ''' <summary> ''' Update another method (without directly referencing ''' anonymous type) after updating method with anonymous type. ''' </summary> <Fact> Public Sub AnonymousTypes_SkipGeneration_2() Dim sources0 = <compilation> <file name="a.vb"><![CDATA[ Class C Shared Function F() As Object Dim x As New With {.A = 1} Return x.A End Function Shared Function G() As Object Dim x As Integer = 1 Return x End Function End Class ]]></file> </compilation> Dim sources1 = <compilation> <file name="a.vb"><![CDATA[ Class C Shared Function F() As Object Dim x As New With {.A = 2, .B = 3} Return x.A End Function Shared Function G() As Object Dim x As Integer = 1 Return x End Function End Class ]]></file> </compilation> Dim sources2 = <compilation> <file name="a.vb"><![CDATA[ Class C Shared Function F() As Object Dim x As New With {.A = 2, .B = 3} Return x.A End Function Shared Function G() As Object Dim x As Integer = 1 Return x + 1 End Function End Class ]]></file> </compilation> Dim sources3 = <compilation> <file name="a.vb"><![CDATA[ Class C Shared Function F() As Object Dim x As New With {.A = 2, .B = 3} Return x.A End Function Shared Function G() As Object Dim x As New With {.A = DirectCast(Nothing, Object)} Dim y As New With {.A = "a"c, .B = "b"c} Return x End Function End Class ]]></file> </compilation> Dim compilation0 = CreateCompilationWithMscorlib40(sources0, options:=TestOptions.DebugDll) Dim compilation1 = compilation0.WithSource(sources1) Dim compilation2 = compilation1.WithSource(sources2) Dim compilation3 = compilation2.WithSource(sources3) Dim testData0 = New CompilationTestData() Dim bytes0 = compilation0.EmitToArray(testData:=testData0) Using md0 = ModuleMetadata.CreateFromImage(bytes0) Dim generation0 = EmitBaseline.CreateInitialBaseline( ModuleMetadata.CreateFromImage(bytes0), Function(m) Select Case md0.MetadataReader.GetString(md0.MetadataReader.GetMethodDefinition(m).Name) Case "F" : Return testData0.GetMethodData("C.F").GetEncDebugInfo() Case "G" : Return testData0.GetMethodData("C.G").GetEncDebugInfo() End Select Return Nothing End Function) Dim method0F = compilation0.GetMember(Of MethodSymbol)("C.F") Dim reader0 = md0.MetadataReader CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "VB$AnonymousType_0`1", "C") Dim method1F = compilation1.GetMember(Of MethodSymbol)("C.F") Dim method1G = compilation1.GetMember(Of MethodSymbol)("C.G") Dim diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(New SemanticEdit(SemanticEditKind.Update, method0F, method1F, GetEquivalentNodesMap(method1F, method0F), preserveLocalVariables:=True))) Using md1 = diff1.GetMetadata() Dim reader1 = md1.Reader CheckNames({reader0, reader1}, reader1.GetTypeDefNames(), "VB$AnonymousType_1`2") ' one additional type Dim method2G = compilation2.GetMember(Of MethodSymbol)("C.G") Dim diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create(New SemanticEdit(SemanticEditKind.Update, method1G, method2G, GetEquivalentNodesMap(method2G, method1G), preserveLocalVariables:=True))) Using md2 = diff2.GetMetadata() Dim reader2 = md2.Reader CheckNames({reader0, reader1, reader2}, reader2.GetTypeDefNames()) ' no additional types Dim method3G = compilation3.GetMember(Of MethodSymbol)("C.G") Dim diff3 = compilation3.EmitDifference( diff2.NextGeneration, ImmutableArray.Create(New SemanticEdit(SemanticEditKind.Update, method2G, method3G, GetEquivalentNodesMap(method3G, method2G), preserveLocalVariables:=True))) Using md3 = diff3.GetMetadata() Dim reader3 = md3.Reader CheckNames({reader0, reader1, reader2, reader3}, reader3.GetTypeDefNames()) ' no additional types End Using End Using End Using End Using End Sub <WorkItem(1292, "https://github.com/dotnet/roslyn/issues/1292")> <Fact> Public Sub AnonymousTypes_Key() Dim sources0 = <compilation> <file name="a.vb"><![CDATA[ Class C Shared Sub M() Dim x As New With {.A = 1, .B = 2} Dim y As New With {Key .A = 3, .B = 4} Dim z As New With {.A = 5, Key .B = 6} End Sub End Class ]]></file> </compilation> Dim sources1 = <compilation> <file name="a.vb"><![CDATA[ Class C Shared Sub M() Dim x As New With {.A = 1, .B = 2} Dim y As New With {Key .A = 3, Key .B = 4} Dim z As New With {Key .A = 5, .B = 6} End Sub End Class ]]></file> </compilation> Dim compilation0 = CreateCompilationWithMscorlib40(sources0, options:=TestOptions.DebugDll) Dim compilation1 = compilation0.WithSource(sources1) Dim testData0 = New CompilationTestData() Dim bytes0 = compilation0.EmitToArray(testData:=testData0) Using md0 = ModuleMetadata.CreateFromImage(bytes0) Dim generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), testData0.GetMethodData("C.M").EncDebugInfoProvider) Dim method0 = compilation0.GetMember(Of MethodSymbol)("C.M") Dim reader0 = md0.MetadataReader CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "VB$AnonymousType_0`2", "VB$AnonymousType_1`2", "VB$AnonymousType_2`2", "C") Dim method1 = compilation1.GetMember(Of MethodSymbol)("C.M") Dim diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(New SemanticEdit(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables:=True))) Using md1 = diff1.GetMetadata() Dim reader1 = md1.Reader CheckNames({reader0, reader1}, reader1.GetTypeDefNames(), "VB$AnonymousType_3`2") diff1.VerifyIL("C.M", "{ // Code size 27 (0x1b) .maxstack 2 .locals init (VB$AnonymousType_0(Of Integer, Integer) V_0, //x [unchanged] V_1, [unchanged] V_2, VB$AnonymousType_3(Of Integer, Integer) V_3, //y VB$AnonymousType_1(Of Integer, Integer) V_4) //z IL_0000: nop IL_0001: ldc.i4.1 IL_0002: ldc.i4.2 IL_0003: newobj ""Sub VB$AnonymousType_0(Of Integer, Integer)..ctor(Integer, Integer)"" IL_0008: stloc.0 IL_0009: ldc.i4.3 IL_000a: ldc.i4.4 IL_000b: newobj ""Sub VB$AnonymousType_3(Of Integer, Integer)..ctor(Integer, Integer)"" IL_0010: stloc.3 IL_0011: ldc.i4.5 IL_0012: ldc.i4.6 IL_0013: newobj ""Sub VB$AnonymousType_1(Of Integer, Integer)..ctor(Integer, Integer)"" IL_0018: stloc.s V_4 IL_001a: ret }") End Using End Using End Sub <Fact> Public Sub AnonymousTypes_DifferentCase() Dim sources0 = <compilation> <file name="a.vb"><![CDATA[ Class C Shared Sub M() Dim x As New With {.A = 1, .B = 2} Dim y As New With {.a = 3, .b = 4} End Sub End Class ]]></file> </compilation> Dim sources1 = <compilation> <file name="a.vb"><![CDATA[ Class C Shared Sub M() Dim x As New With {.a = 1, .B = 2} Dim y As New With {.AB = 3} Dim z As New With {.ab = 4} End Sub End Class ]]></file> </compilation> Dim sources2 = <compilation> <file name="a.vb"><![CDATA[ Class C Shared Sub M() Dim x As New With {.a = 1, .B = 2} Dim z As New With {.Ab = 5} End Sub End Class ]]></file> </compilation> Dim compilation0 = CreateCompilationWithMscorlib40(sources0, options:=TestOptions.DebugDll) Dim compilation1 = compilation0.WithSource(sources1) Dim compilation2 = compilation1.WithSource(sources2) Dim testData0 = New CompilationTestData() Dim bytes0 = compilation0.EmitToArray(testData:=testData0) Using md0 = ModuleMetadata.CreateFromImage(bytes0) Dim generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), testData0.GetMethodData("C.M").EncDebugInfoProvider) Dim method0 = compilation0.GetMember(Of MethodSymbol)("C.M") Dim reader0 = md0.MetadataReader CheckNames(reader0, reader0.GetTypeDefNames(), "<Module>", "VB$AnonymousType_0`2", "C") Dim method1 = compilation1.GetMember(Of MethodSymbol)("C.M") Dim diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(New SemanticEdit(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables:=True))) Using md1 = diff1.GetMetadata() Dim reader1 = md1.Reader CheckNames({reader0, reader1}, reader1.GetTypeDefNames(), "VB$AnonymousType_1`1") diff1.VerifyIL("C.M", "{ // Code size 25 (0x19) .maxstack 2 .locals init ([unchanged] V_0, [unchanged] V_1, VB$AnonymousType_0(Of Integer, Integer) V_2, //x VB$AnonymousType_1(Of Integer) V_3, //y VB$AnonymousType_1(Of Integer) V_4) //z IL_0000: nop IL_0001: ldc.i4.1 IL_0002: ldc.i4.2 IL_0003: newobj ""Sub VB$AnonymousType_0(Of Integer, Integer)..ctor(Integer, Integer)"" IL_0008: stloc.2 IL_0009: ldc.i4.3 IL_000a: newobj ""Sub VB$AnonymousType_1(Of Integer)..ctor(Integer)"" IL_000f: stloc.3 IL_0010: ldc.i4.4 IL_0011: newobj ""Sub VB$AnonymousType_1(Of Integer)..ctor(Integer)"" IL_0016: stloc.s V_4 IL_0018: ret }") Dim method2 = compilation2.GetMember(Of MethodSymbol)("C.M") Dim diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create(New SemanticEdit(SemanticEditKind.Update, method1, method2, GetEquivalentNodesMap(method2, method1), preserveLocalVariables:=True))) Using md2 = diff2.GetMetadata() Dim reader2 = md2.Reader CheckNames({reader0, reader1, reader2}, reader2.GetTypeDefNames()) diff2.VerifyIL("C.M", "{ // Code size 18 (0x12) .maxstack 2 .locals init ([unchanged] V_0, [unchanged] V_1, VB$AnonymousType_0(Of Integer, Integer) V_2, //x [unchanged] V_3, [unchanged] V_4, VB$AnonymousType_1(Of Integer) V_5) //z IL_0000: nop IL_0001: ldc.i4.1 IL_0002: ldc.i4.2 IL_0003: newobj ""Sub VB$AnonymousType_0(Of Integer, Integer)..ctor(Integer, Integer)"" IL_0008: stloc.2 IL_0009: ldc.i4.5 IL_000a: newobj ""Sub VB$AnonymousType_1(Of Integer)..ctor(Integer)"" IL_000f: stloc.s V_5 IL_0011: ret }") End Using End Using End Using End Sub <Fact> Public Sub AnonymousTypes_Nested() Dim template = " Imports System Imports System.Linq Class C Sub F(args As String()) Dim <N:4>result</N:4> = From a in args Let <N:0>x = a.Reverse()</N:0> Let <N:1>y = x.Reverse()</N:1> <N:2>Where x.SequenceEqual(y)</N:2> Select <N:3>Value = a</N:3>, Length = a.Length Console.WriteLine(<<VALUE>>) End Sub End Class " Dim source0 = MarkedSource(template.Replace("<<VALUE>>", "0")) Dim source1 = MarkedSource(template.Replace("<<VALUE>>", "1")) Dim source2 = MarkedSource(template.Replace("<<VALUE>>", "2")) Dim compilation0 = CreateCompilationWithMscorlib45({source0.Tree}, {SystemCoreRef}, options:=ComSafeDebugDll) Dim compilation1 = compilation0.WithSource(source1.Tree) Dim compilation2 = compilation0.WithSource(source2.Tree) Dim v0 = CompileAndVerify(compilation0) Dim md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData) Dim f0 = compilation0.GetMember(Of MethodSymbol)("C.F") Dim f1 = compilation1.GetMember(Of MethodSymbol)("C.F") Dim f2 = compilation2.GetMember(Of MethodSymbol)("C.F") Dim generation0 = EmitBaseline.CreateInitialBaseline(md0, AddressOf v0.CreateSymReader().GetEncMethodDebugInfo) Dim expectedIL = " { // Code size 175 (0xaf) .maxstack 3 .locals init (System.Collections.Generic.IEnumerable(Of <anonymous type: Key Value As String, Key Length As Integer>) V_0) //result IL_0000: nop IL_0001: ldarg.1 IL_0002: ldsfld ""C._Closure$__.$I1-0 As System.Func(Of String, <anonymous type: Key a As String, Key x As System.Collections.Generic.IEnumerable(Of Char)>)"" IL_0007: brfalse.s IL_0010 IL_0009: ldsfld ""C._Closure$__.$I1-0 As System.Func(Of String, <anonymous type: Key a As String, Key x As System.Collections.Generic.IEnumerable(Of Char)>)"" IL_000e: br.s IL_0026 IL_0010: ldsfld ""C._Closure$__.$I As C._Closure$__"" IL_0015: ldftn ""Function C._Closure$__._Lambda$__1-0(String) As <anonymous type: Key a As String, Key x As System.Collections.Generic.IEnumerable(Of Char)>"" IL_001b: newobj ""Sub System.Func(Of String, <anonymous type: Key a As String, Key x As System.Collections.Generic.IEnumerable(Of Char)>)..ctor(Object, System.IntPtr)"" IL_0020: dup IL_0021: stsfld ""C._Closure$__.$I1-0 As System.Func(Of String, <anonymous type: Key a As String, Key x As System.Collections.Generic.IEnumerable(Of Char)>)"" IL_0026: call ""Function System.Linq.Enumerable.Select(Of String, <anonymous type: Key a As String, Key x As System.Collections.Generic.IEnumerable(Of Char)>)(System.Collections.Generic.IEnumerable(Of String), System.Func(Of String, <anonymous type: Key a As String, Key x As System.Collections.Generic.IEnumerable(Of Char)>)) As System.Collections.Generic.IEnumerable(Of <anonymous type: Key a As String, Key x As System.Collections.Generic.IEnumerable(Of Char)>)"" IL_002b: ldsfld ""C._Closure$__.$I1-1 As System.Func(Of <anonymous type: Key a As String, Key x As System.Collections.Generic.IEnumerable(Of Char)>, <anonymous type: Key $VB$It As <anonymous type: Key a As String, Key x As System.Collections.Generic.IEnumerable(Of Char)>, Key y As System.Collections.Generic.IEnumerable(Of Char)>)"" IL_0030: brfalse.s IL_0039 IL_0032: ldsfld ""C._Closure$__.$I1-1 As System.Func(Of <anonymous type: Key a As String, Key x As System.Collections.Generic.IEnumerable(Of Char)>, <anonymous type: Key $VB$It As <anonymous type: Key a As String, Key x As System.Collections.Generic.IEnumerable(Of Char)>, Key y As System.Collections.Generic.IEnumerable(Of Char)>)"" IL_0037: br.s IL_004f IL_0039: ldsfld ""C._Closure$__.$I As C._Closure$__"" IL_003e: ldftn ""Function C._Closure$__._Lambda$__1-1(<anonymous type: Key a As String, Key x As System.Collections.Generic.IEnumerable(Of Char)>) As <anonymous type: Key $VB$It As <anonymous type: Key a As String, Key x As System.Collections.Generic.IEnumerable(Of Char)>, Key y As System.Collections.Generic.IEnumerable(Of Char)>"" IL_0044: newobj ""Sub System.Func(Of <anonymous type: Key a As String, Key x As System.Collections.Generic.IEnumerable(Of Char)>, <anonymous type: Key $VB$It As <anonymous type: Key a As String, Key x As System.Collections.Generic.IEnumerable(Of Char)>, Key y As System.Collections.Generic.IEnumerable(Of Char)>)..ctor(Object, System.IntPtr)"" IL_0049: dup IL_004a: stsfld ""C._Closure$__.$I1-1 As System.Func(Of <anonymous type: Key a As String, Key x As System.Collections.Generic.IEnumerable(Of Char)>, <anonymous type: Key $VB$It As <anonymous type: Key a As String, Key x As System.Collections.Generic.IEnumerable(Of Char)>, Key y As System.Collections.Generic.IEnumerable(Of Char)>)"" IL_004f: call ""Function System.Linq.Enumerable.Select(Of <anonymous type: Key a As String, Key x As System.Collections.Generic.IEnumerable(Of Char)>, <anonymous type: Key $VB$It As <anonymous type: Key a As String, Key x As System.Collections.Generic.IEnumerable(Of Char)>, Key y As System.Collections.Generic.IEnumerable(Of Char)>)(System.Collections.Generic.IEnumerable(Of <anonymous type: Key a As String, Key x As System.Collections.Generic.IEnumerable(Of Char)>), System.Func(Of <anonymous type: Key a As String, Key x As System.Collections.Generic.IEnumerable(Of Char)>, <anonymous type: Key $VB$It As <anonymous type: Key a As String, Key x As System.Collections.Generic.IEnumerable(Of Char)>, Key y As System.Collections.Generic.IEnumerable(Of Char)>)) As System.Collections.Generic.IEnumerable(Of <anonymous type: Key $VB$It As <anonymous type: Key a As String, Key x As System.Collections.Generic.IEnumerable(Of Char)>, Key y As System.Collections.Generic.IEnumerable(Of Char)>)"" IL_0054: ldsfld ""C._Closure$__.$I1-2 As System.Func(Of <anonymous type: Key $VB$It As <anonymous type: Key a As String, Key x As System.Collections.Generic.IEnumerable(Of Char)>, Key y As System.Collections.Generic.IEnumerable(Of Char)>, Boolean)"" IL_0059: brfalse.s IL_0062 IL_005b: ldsfld ""C._Closure$__.$I1-2 As System.Func(Of <anonymous type: Key $VB$It As <anonymous type: Key a As String, Key x As System.Collections.Generic.IEnumerable(Of Char)>, Key y As System.Collections.Generic.IEnumerable(Of Char)>, Boolean)"" IL_0060: br.s IL_0078 IL_0062: ldsfld ""C._Closure$__.$I As C._Closure$__"" IL_0067: ldftn ""Function C._Closure$__._Lambda$__1-2(<anonymous type: Key $VB$It As <anonymous type: Key a As String, Key x As System.Collections.Generic.IEnumerable(Of Char)>, Key y As System.Collections.Generic.IEnumerable(Of Char)>) As Boolean"" IL_006d: newobj ""Sub System.Func(Of <anonymous type: Key $VB$It As <anonymous type: Key a As String, Key x As System.Collections.Generic.IEnumerable(Of Char)>, Key y As System.Collections.Generic.IEnumerable(Of Char)>, Boolean)..ctor(Object, System.IntPtr)"" IL_0072: dup IL_0073: stsfld ""C._Closure$__.$I1-2 As System.Func(Of <anonymous type: Key $VB$It As <anonymous type: Key a As String, Key x As System.Collections.Generic.IEnumerable(Of Char)>, Key y As System.Collections.Generic.IEnumerable(Of Char)>, Boolean)"" IL_0078: call ""Function System.Linq.Enumerable.Where(Of <anonymous type: Key $VB$It As <anonymous type: Key a As String, Key x As System.Collections.Generic.IEnumerable(Of Char)>, Key y As System.Collections.Generic.IEnumerable(Of Char)>)(System.Collections.Generic.IEnumerable(Of <anonymous type: Key $VB$It As <anonymous type: Key a As String, Key x As System.Collections.Generic.IEnumerable(Of Char)>, Key y As System.Collections.Generic.IEnumerable(Of Char)>), System.Func(Of <anonymous type: Key $VB$It As <anonymous type: Key a As String, Key x As System.Collections.Generic.IEnumerable(Of Char)>, Key y As System.Collections.Generic.IEnumerable(Of Char)>, Boolean)) As System.Collections.Generic.IEnumerable(Of <anonymous type: Key $VB$It As <anonymous type: Key a As String, Key x As System.Collections.Generic.IEnumerable(Of Char)>, Key y As System.Collections.Generic.IEnumerable(Of Char)>)"" IL_007d: ldsfld ""C._Closure$__.$I1-3 As System.Func(Of <anonymous type: Key $VB$It As <anonymous type: Key a As String, Key x As System.Collections.Generic.IEnumerable(Of Char)>, Key y As System.Collections.Generic.IEnumerable(Of Char)>, <anonymous type: Key Value As String, Key Length As Integer>)"" IL_0082: brfalse.s IL_008b IL_0084: ldsfld ""C._Closure$__.$I1-3 As System.Func(Of <anonymous type: Key $VB$It As <anonymous type: Key a As String, Key x As System.Collections.Generic.IEnumerable(Of Char)>, Key y As System.Collections.Generic.IEnumerable(Of Char)>, <anonymous type: Key Value As String, Key Length As Integer>)"" IL_0089: br.s IL_00a1 IL_008b: ldsfld ""C._Closure$__.$I As C._Closure$__"" IL_0090: ldftn ""Function C._Closure$__._Lambda$__1-3(<anonymous type: Key $VB$It As <anonymous type: Key a As String, Key x As System.Collections.Generic.IEnumerable(Of Char)>, Key y As System.Collections.Generic.IEnumerable(Of Char)>) As <anonymous type: Key Value As String, Key Length As Integer>"" IL_0096: newobj ""Sub System.Func(Of <anonymous type: Key $VB$It As <anonymous type: Key a As String, Key x As System.Collections.Generic.IEnumerable(Of Char)>, Key y As System.Collections.Generic.IEnumerable(Of Char)>, <anonymous type: Key Value As String, Key Length As Integer>)..ctor(Object, System.IntPtr)"" IL_009b: dup IL_009c: stsfld ""C._Closure$__.$I1-3 As System.Func(Of <anonymous type: Key $VB$It As <anonymous type: Key a As String, Key x As System.Collections.Generic.IEnumerable(Of Char)>, Key y As System.Collections.Generic.IEnumerable(Of Char)>, <anonymous type: Key Value As String, Key Length As Integer>)"" IL_00a1: call ""Function System.Linq.Enumerable.Select(Of <anonymous type: Key $VB$It As <anonymous type: Key a As String, Key x As System.Collections.Generic.IEnumerable(Of Char)>, Key y As System.Collections.Generic.IEnumerable(Of Char)>, <anonymous type: Key Value As String, Key Length As Integer>)(System.Collections.Generic.IEnumerable(Of <anonymous type: Key $VB$It As <anonymous type: Key a As String, Key x As System.Collections.Generic.IEnumerable(Of Char)>, Key y As System.Collections.Generic.IEnumerable(Of Char)>), System.Func(Of <anonymous type: Key $VB$It As <anonymous type: Key a As String, Key x As System.Collections.Generic.IEnumerable(Of Char)>, Key y As System.Collections.Generic.IEnumerable(Of Char)>, <anonymous type: Key Value As String, Key Length As Integer>)) As System.Collections.Generic.IEnumerable(Of <anonymous type: Key Value As String, Key Length As Integer>)"" IL_00a6: stloc.0 IL_00a7: ldc.i4.<<VALUE>> IL_00a8: call ""Sub System.Console.WriteLine(Integer)"" IL_00ad: nop IL_00ae: ret }" v0.VerifyIL("C.F", expectedIL.Replace("<<VALUE>>", "0")) Dim diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( New SemanticEdit(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables:=True))) diff1.VerifySynthesizedMembers( "C: {_Closure$__}", "C._Closure$__: {$I1-0, $I1-1, $I1-2, $I1-3, _Lambda$__1-0, _Lambda$__1-1, _Lambda$__1-2, _Lambda$__1-3}") diff1.VerifyIL("C.F", expectedIL.Replace("<<VALUE>>", "1")) Dim diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create( New SemanticEdit(SemanticEditKind.Update, f1, f2, GetSyntaxMapFromMarkers(source1, source2), preserveLocalVariables:=True))) diff2.VerifySynthesizedMembers( "C: {_Closure$__}", "C._Closure$__: {$I1-0, $I1-1, $I1-2, $I1-3, _Lambda$__1-0, _Lambda$__1-1, _Lambda$__1-2, _Lambda$__1-3}") diff2.VerifyIL("C.F", expectedIL.Replace("<<VALUE>>", "2")) End Sub <Fact> Public Sub AnonymousDelegates1() Dim source0 = MarkedSource(" Class C Private Sub F() Dim <N:0>g</N:0> = <N:1>Function(ByRef arg As String) arg</N:1> System.Console.WriteLine(1) End Sub End Class ") Dim source1 = MarkedSource(" Class C Private Sub F() Dim <N:0>g</N:0> = <N:1>Function(ByRef arg As String) arg</N:1> System.Console.WriteLine(2) End Sub End Class ") Dim source2 = MarkedSource(" Class C Private Sub F() Dim <N:0>g</N:0> = <N:1>Function(ByRef arg As String) arg</N:1> System.Console.WriteLine(3) End Sub End Class ") Dim compilation0 = CreateCompilationWithMscorlib40({source0.Tree}, options:=ComSafeDebugDll) Dim compilation1 = compilation0.WithSource(source1.Tree) Dim compilation2 = compilation1.WithSource(source2.Tree) Dim v0 = CompileAndVerify(compilation0) v0.VerifyIL("C.F", " { // Code size 46 (0x2e) .maxstack 2 .locals init (VB$AnonymousDelegate_0(Of String, String) V_0) //g IL_0000: nop IL_0001: ldsfld ""C._Closure$__.$I1-0 As <generated method>"" IL_0006: brfalse.s IL_000f IL_0008: ldsfld ""C._Closure$__.$I1-0 As <generated method>"" IL_000d: br.s IL_0025 IL_000f: ldsfld ""C._Closure$__.$I As C._Closure$__"" IL_0014: ldftn ""Function C._Closure$__._Lambda$__1-0(ByRef String) As String"" IL_001a: newobj ""Sub VB$AnonymousDelegate_0(Of String, String)..ctor(Object, System.IntPtr)"" IL_001f: dup IL_0020: stsfld ""C._Closure$__.$I1-0 As <generated method>"" IL_0025: stloc.0 IL_0026: ldc.i4.1 IL_0027: call ""Sub System.Console.WriteLine(Integer)"" IL_002c: nop IL_002d: ret } ") Dim md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData) Dim generation0 = EmitBaseline.CreateInitialBaseline(md0, AddressOf v0.CreateSymReader().GetEncMethodDebugInfo) Dim f0 = compilation0.GetMember(Of MethodSymbol)("C.F") Dim f1 = compilation1.GetMember(Of MethodSymbol)("C.F") Dim f2 = compilation2.GetMember(Of MethodSymbol)("C.F") Dim diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(New SemanticEdit(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables:=True))) diff1.VerifyIL("C.F", " { // Code size 46 (0x2e) .maxstack 2 .locals init (VB$AnonymousDelegate_0(Of String, String) V_0) //g IL_0000: nop IL_0001: ldsfld ""C._Closure$__.$I1-0 As <generated method>"" IL_0006: brfalse.s IL_000f IL_0008: ldsfld ""C._Closure$__.$I1-0 As <generated method>"" IL_000d: br.s IL_0025 IL_000f: ldsfld ""C._Closure$__.$I As C._Closure$__"" IL_0014: ldftn ""Function C._Closure$__._Lambda$__1-0(ByRef String) As String"" IL_001a: newobj ""Sub VB$AnonymousDelegate_0(Of String, String)..ctor(Object, System.IntPtr)"" IL_001f: dup IL_0020: stsfld ""C._Closure$__.$I1-0 As <generated method>"" IL_0025: stloc.0 IL_0026: ldc.i4.2 IL_0027: call ""Sub System.Console.WriteLine(Integer)"" IL_002c: nop IL_002d: ret } ") Dim diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create(New SemanticEdit(SemanticEditKind.Update, f1, f2, GetSyntaxMapFromMarkers(source1, source2), preserveLocalVariables:=True))) diff2.VerifyIL("C.F", " { // Code size 46 (0x2e) .maxstack 2 .locals init (VB$AnonymousDelegate_0(Of String, String) V_0) //g IL_0000: nop IL_0001: ldsfld ""C._Closure$__.$I1-0 As <generated method>"" IL_0006: brfalse.s IL_000f IL_0008: ldsfld ""C._Closure$__.$I1-0 As <generated method>"" IL_000d: br.s IL_0025 IL_000f: ldsfld ""C._Closure$__.$I As C._Closure$__"" IL_0014: ldftn ""Function C._Closure$__._Lambda$__1-0(ByRef String) As String"" IL_001a: newobj ""Sub VB$AnonymousDelegate_0(Of String, String)..ctor(Object, System.IntPtr)"" IL_001f: dup IL_0020: stsfld ""C._Closure$__.$I1-0 As <generated method>"" IL_0025: stloc.0 IL_0026: ldc.i4.3 IL_0027: call ""Sub System.Console.WriteLine(Integer)"" IL_002c: nop IL_002d: ret } ") End Sub ''' <summary> ''' Should not re-use locals with custom modifiers. ''' </summary> <Fact(Skip:="9854")> <WorkItem(9854, "https://github.com/dotnet/roslyn/issues/9854")> Public Sub LocalType_CustomModifiers() ' Equivalent method signature to VB, but ' with optional modifiers on locals. Dim ilSource = <![CDATA[ .assembly extern mscorlib { .ver 4:0:0:0 .publickeytoken = (B7 7A 5C 56 19 34 E0 89) } .assembly '<<GeneratedFileName>>' { } .class public C { .method public specialname rtspecialname instance void .ctor() { ret } .method public static object F(class [mscorlib]System.IDisposable d) { .locals init ([0] object F, [1] class C modopt(int32) c, [2] class [mscorlib]System.IDisposable modopt(object) VB$Using, [3] bool V_3) ldnull ret } } ]]>.Value Dim source = <compilation> <file name="c.vb"><![CDATA[ Class C Shared Function F(d As System.IDisposable) As Object Dim c As C Using d c = DirectCast(d, C) End Using Return c End Function End Class ]]> </file> </compilation> Dim metadata0 = DirectCast(CompileIL(ilSource, prependDefaultHeader:=False), MetadataImageReference) ' Still need a compilation with source for the initial ' generation - to get a MethodSymbol and syntax map. Dim compilation0 = CreateCompilationWithMscorlib40(source, options:=TestOptions.DebugDll) Dim compilation1 = compilation0.Clone() Dim moduleMetadata0 = DirectCast(metadata0.GetMetadataNoCopy(), AssemblyMetadata).GetModules(0) Dim method0 = compilation0.GetMember(Of MethodSymbol)("C.F") Dim generation0 = EmitBaseline.CreateInitialBaseline( moduleMetadata0, Function(m) Nothing) Dim testData1 = New CompilationTestData() Dim method1 = compilation1.GetMember(Of MethodSymbol)("C.F") Dim edit = New SemanticEdit(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables:=True) Dim diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(edit)) diff1.VerifyIL("C.F", " { // Code size 45 (0x2d) .maxstack 2 .locals init ([object] V_0, [unchanged] V_1, [unchanged] V_2, [bool] V_3, Object V_4, //F C V_5, //c System.IDisposable V_6, //VB$Using Boolean V_7) IL_0000: nop IL_0001: nop IL_0002: ldarg.0 IL_0003: stloc.s V_6 .try { IL_0005: ldarg.0 IL_0006: castclass ""C"" IL_000b: stloc.s V_5 IL_000d: leave.s IL_0024 } finally { IL_000f: nop IL_0010: ldloc.s V_6 IL_0012: ldnull IL_0013: ceq IL_0015: stloc.s V_7 IL_0017: ldloc.s V_7 IL_0019: brtrue.s IL_0023 IL_001b: ldloc.s V_6 IL_001d: callvirt ""Sub System.IDisposable.Dispose()"" IL_0022: nop IL_0023: endfinally } IL_0024: ldloc.s V_5 IL_0026: stloc.s V_4 IL_0028: br.s IL_002a IL_002a: ldloc.s V_4 IL_002c: ret } ") End Sub <WorkItem(839414, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/839414")> <Fact> Public Sub Bug839414() Dim source0 = <compilation> <file name="a.vb"> Module M Function F() As Object Static x = 1 Return x End Function End Module </file> </compilation> Dim source1 = <compilation> <file name="a.vb"> Module M Function F() As Object Static x = "2" Return x End Function End Module </file> </compilation> Dim compilation0 = CreateCompilationWithMscorlib40AndVBRuntime(source0, TestOptions.DebugDll) Dim compilation1 = compilation0.WithSource(source1) Dim bytes0 = compilation0.EmitToArray() Dim method0 = compilation0.GetMember(Of MethodSymbol)("M.F") Dim method1 = compilation1.GetMember(Of MethodSymbol)("M.F") Dim generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), EmptyLocalsProvider) compilation1.EmitDifference( generation0, ImmutableArray.Create(New SemanticEdit(SemanticEditKind.Update, method0, method1))) End Sub <WorkItem(849649, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/849649")> <Fact> Public Sub Bug849649() Dim source0 = <compilation> <file name="a.vb"> Module M Sub F() Dim x(5) As Integer x(3) = 2 End Sub End Module </file> </compilation> Dim source1 = <compilation> <file name="a.vb"> Module M Sub F() Dim x(5) As Integer x(3) = 3 End Sub End Module </file> </compilation> Dim compilation0 = CreateCompilationWithMscorlib40AndVBRuntime(source0, TestOptions.DebugDll) Dim compilation1 = compilation0.WithSource(source1) Dim bytes0 = compilation0.EmitToArray() Dim method0 = compilation0.GetMember(Of MethodSymbol)("M.F") Dim method1 = compilation1.GetMember(Of MethodSymbol)("M.F") Dim generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), EmptyLocalsProvider) Dim diff0 = compilation1.EmitDifference( generation0, ImmutableArray.Create(New SemanticEdit(SemanticEditKind.Update, method0, method1, GetEquivalentNodesMap(method1, method0), preserveLocalVariables:=True))) diff0.VerifyIL(" { // Code size 13 (0xd) .maxstack 3 IL_0000: nop IL_0001: ldc.i4.6 IL_0002: newarr 0x0100000A IL_0007: stloc.1 IL_0008: ldloc.1 IL_0009: ldc.i4.3 IL_000a: ldc.i4.3 IL_000b: stelem.i4 IL_000c: ret } ") End Sub #End Region <ConditionalFact(GetType(WindowsOnly), Reason:=ConditionalSkipReason.NativePdbRequiresDesktop)> Public Sub SymWriterErrors() Dim source0 = <compilation> <file name="a.vb"><![CDATA[ Class C End Class ]]></file> </compilation> Dim source1 = <compilation> <file name="a.vb"><![CDATA[ Class C Sub Main() End Sub End Class ]]></file> </compilation> Dim compilation0 = CreateCompilationWithMscorlib40(source0, options:=TestOptions.DebugDll) Dim compilation1 = compilation0.WithSource(source1) ' Verify full metadata contains expected rows. Dim bytes0 = compilation0.EmitToArray() Using md0 = ModuleMetadata.CreateFromImage(bytes0) Dim diff1 = compilation1.EmitDifference( EmitBaseline.CreateInitialBaseline(md0, EmptyLocalsProvider), ImmutableArray.Create(New SemanticEdit(SemanticEditKind.Insert, Nothing, compilation1.GetMember(Of MethodSymbol)("C.Main"))), testData:=New CompilationTestData With {.SymWriterFactory = Function() New MockSymUnmanagedWriter()}) diff1.EmitResult.Diagnostics.Verify( Diagnostic(ERRID.ERR_PDBWritingFailed).WithArguments("MockSymUnmanagedWriter error message")) Assert.False(diff1.EmitResult.Success) End Using End Sub <WorkItem(1003274, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1003274")> <Fact> Public Sub ConditionalAttribute() Const source0 = " Imports System.Diagnostics Class C Sub M() ' Body End Sub <Conditional(""Defined"")> Sub N1() End Sub <Conditional(""Undefined"")> Sub N2() End Sub End Class " Dim parseOptions As New VisualBasicParseOptions(preprocessorSymbols:={New KeyValuePair(Of String, Object)("Defined", True)}) Dim tree0 = VisualBasicSyntaxTree.ParseText(source0, parseOptions) Dim tree1 = VisualBasicSyntaxTree.ParseText(source0.Replace("' Body", "N1(): N2()"), parseOptions) Dim compilation0 = CreateCompilationWithMscorlib40({tree0}, options:=TestOptions.DebugDll) Dim compilation1 = compilation0.ReplaceSyntaxTree(tree0, tree1) Dim bytes0 = compilation0.EmitToArray() Using md0 = ModuleMetadata.CreateFromImage(bytes0) Dim reader0 = md0.MetadataReader Dim method0 = compilation0.GetMember(Of MethodSymbol)("C.M") Dim method1 = compilation1.GetMember(Of MethodSymbol)("C.M") Dim generation0 = EmitBaseline.CreateInitialBaseline(ModuleMetadata.CreateFromImage(bytes0), EmptyLocalsProvider) Dim diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(New SemanticEdit(SemanticEditKind.Update, method0, method1))) diff1.EmitResult.Diagnostics.AssertNoErrors() diff1.VerifyIL("C.M", " { // Code size 9 (0x9) .maxstack 1 IL_0000: nop IL_0001: ldarg.0 IL_0002: call ""Sub C.N1()"" IL_0007: nop IL_0008: ret } ") End Using End Sub <Fact> Public Sub ReferenceToMemberAddedToAnotherAssembly1() Dim sourceA0 = " Public Class A End Class " Dim sourceA1 = " Public Class A Public Sub M() System.Console.WriteLine(1) End Sub End Class Public Class X End Class " Dim sourceB0 = " Public Class B Public Shared Sub F() End Sub End Class" Dim sourceB1 = " Public Class B Public Shared Sub F() Dim a = New A() a.M() End Sub End Class Public Class Y Inherits X End Class " Dim compilationA0 = CreateCompilationWithMscorlib40({sourceA0}, options:=TestOptions.DebugDll, assemblyName:="LibA") Dim compilationA1 = compilationA0.WithSource(sourceA1) Dim compilationB0 = CreateCompilationWithMscorlib40({sourceB0}, {compilationA0.ToMetadataReference()}, options:=TestOptions.DebugDll, assemblyName:="LibB") Dim compilationB1 = CreateCompilationWithMscorlib40({sourceB1}, {compilationA1.ToMetadataReference()}, options:=TestOptions.DebugDll, assemblyName:="LibB") Dim bytesA0 = compilationA0.EmitToArray() Dim bytesB0 = compilationB0.EmitToArray() Dim mdA0 = ModuleMetadata.CreateFromImage(bytesA0) Dim mdB0 = ModuleMetadata.CreateFromImage(bytesB0) Dim generationA0 = EmitBaseline.CreateInitialBaseline(mdA0, EmptyLocalsProvider) Dim generationB0 = EmitBaseline.CreateInitialBaseline(mdB0, EmptyLocalsProvider) Dim mA1 = compilationA1.GetMember(Of MethodSymbol)("A.M") Dim mX1 = compilationA1.GetMember(Of TypeSymbol)("X") Dim allAddedSymbols = New ISymbol() {mA1, mX1} Dim diffA1 = compilationA1.EmitDifference( generationA0, ImmutableArray.Create( New SemanticEdit(SemanticEditKind.Insert, Nothing, mA1), New SemanticEdit(SemanticEditKind.Insert, Nothing, mX1)), allAddedSymbols) diffA1.EmitResult.Diagnostics.Verify() Dim diffB1 = compilationB1.EmitDifference( generationB0, ImmutableArray.Create( New SemanticEdit(SemanticEditKind.Update, compilationB0.GetMember(Of MethodSymbol)("B.F"), compilationB1.GetMember(Of MethodSymbol)("B.F")), New SemanticEdit(SemanticEditKind.Insert, Nothing, compilationB1.GetMember(Of TypeSymbol)("Y"))), allAddedSymbols) diffB1.EmitResult.Diagnostics.Verify( Diagnostic(ERRID.ERR_EncReferenceToAddedMember, "X").WithArguments("X", "LibA").WithLocation(8, 14), Diagnostic(ERRID.ERR_EncReferenceToAddedMember, "M").WithArguments("M", "LibA").WithLocation(3, 16)) End Sub <Fact> Public Sub ReferenceToMemberAddedToAnotherAssembly2() Dim sourceA = " Public Class A Public Sub M() End Sub End Class" Dim sourceB0 = " Public Class B Public Shared Sub F() Dim a = New A() End Sub End Class" Dim sourceB1 = " Public Class B Public Shared Sub F() Dim a = New A() a.M() End Sub End Class" Dim sourceB2 = " Public Class B Public Shared Sub F() Dim a = New A() End Sub End Class" Dim compilationA = CreateCompilationWithMscorlib40({sourceA}, options:=TestOptions.DebugDll, assemblyName:="AssemblyA") Dim aRef = compilationA.ToMetadataReference() Dim compilationB0 = CreateCompilationWithMscorlib40({sourceB0}, {aRef}, options:=TestOptions.DebugDll, assemblyName:="AssemblyB") Dim compilationB1 = compilationB0.WithSource(sourceB1) Dim compilationB2 = compilationB1.WithSource(sourceB2) Dim testDataB0 = New CompilationTestData() Dim bytesB0 = compilationB0.EmitToArray(testData:=testDataB0) Dim mdB0 = ModuleMetadata.CreateFromImage(bytesB0) Dim generationB0 = EmitBaseline.CreateInitialBaseline(mdB0, testDataB0.GetMethodData("B.F").EncDebugInfoProvider()) Dim f0 = compilationB0.GetMember(Of MethodSymbol)("B.F") Dim f1 = compilationB1.GetMember(Of MethodSymbol)("B.F") Dim f2 = compilationB2.GetMember(Of MethodSymbol)("B.F") Dim diffB1 = compilationB1.EmitDifference( generationB0, ImmutableArray.Create(New SemanticEdit(SemanticEditKind.Update, f0, f1, GetEquivalentNodesMap(f1, f0), preserveLocalVariables:=True))) diffB1.VerifyIL("B.F", " { // Code size 15 (0xf) .maxstack 1 .locals init (A V_0) //a IL_0000: nop IL_0001: newobj ""Sub A..ctor()"" IL_0006: stloc.0 IL_0007: ldloc.0 IL_0008: callvirt ""Sub A.M()"" IL_000d: nop IL_000e: ret } ") Dim diffB2 = compilationB2.EmitDifference( diffB1.NextGeneration, ImmutableArray.Create(New SemanticEdit(SemanticEditKind.Update, f1, f2, GetEquivalentNodesMap(f2, f1), preserveLocalVariables:=True))) diffB2.VerifyIL("B.F", " { // Code size 8 (0x8) .maxstack 1 .locals init (A V_0) //a IL_0000: nop IL_0001: newobj ""Sub A..ctor()"" IL_0006: stloc.0 IL_0007: ret } ") End Sub <Fact> Public Sub ForStatement() Dim source0 = MarkedSource(" Imports System Class C Sub F() <N:0><N:1>For a = G(0) To G(1) Step G(2)</N:1> Console.WriteLine(1) Next</N:0> End Sub Function G(a As Integer) As Integer Return 10 End Function End Class ") Dim source1 = MarkedSource(" Imports System Class C Sub F() <N:0><N:1>For a = G(0) To G(1) Step G(2)</N:1> Console.WriteLine(2) Next</N:0> End Sub Function G(a As Integer) As Integer Return 10 End Function End Class ") Dim compilation0 = CreateCompilationWithMscorlib40(source0.Tree, {MsvbRef}, ComSafeDebugDll) Dim compilation1 = compilation0.WithSource(source1.Tree) Dim v0 = CompileAndVerify(compilation0) Dim md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData) Dim generation0 = EmitBaseline.CreateInitialBaseline(md0, AddressOf v0.CreateSymReader().GetEncMethodDebugInfo) Dim f0 = compilation0.GetMember(Of MethodSymbol)("C.F") Dim f1 = compilation1.GetMember(Of MethodSymbol)("C.F") Dim diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(New SemanticEdit(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables:=True))) Dim md1 = diff1.GetMetadata() Dim reader1 = md1.Reader v0.VerifyIL("C.F", " { // Code size 55 (0x37) .maxstack 3 .locals init (Integer V_0, Integer V_1, Integer V_2, Integer V_3) //a IL_0000: nop IL_0001: ldarg.0 IL_0002: ldc.i4.0 IL_0003: call ""Function C.G(Integer) As Integer"" IL_0008: stloc.0 IL_0009: ldarg.0 IL_000a: ldc.i4.1 IL_000b: call ""Function C.G(Integer) As Integer"" IL_0010: stloc.1 IL_0011: ldarg.0 IL_0012: ldc.i4.2 IL_0013: call ""Function C.G(Integer) As Integer"" IL_0018: stloc.2 IL_0019: ldloc.0 IL_001a: stloc.3 IL_001b: br.s IL_0028 IL_001d: ldc.i4.1 IL_001e: call ""Sub System.Console.WriteLine(Integer)"" IL_0023: nop IL_0024: ldloc.3 IL_0025: ldloc.2 IL_0026: add.ovf IL_0027: stloc.3 IL_0028: ldloc.2 IL_0029: ldc.i4.s 31 IL_002b: shr IL_002c: ldloc.3 IL_002d: xor IL_002e: ldloc.2 IL_002f: ldc.i4.s 31 IL_0031: shr IL_0032: ldloc.1 IL_0033: xor IL_0034: ble.s IL_001d IL_0036: ret } ") ' Note that all variables are mapped to their previous slots diff1.VerifyIL("C.F", " { // Code size 55 (0x37) .maxstack 3 .locals init (Integer V_0, Integer V_1, Integer V_2, Integer V_3) //a IL_0000: nop IL_0001: ldarg.0 IL_0002: ldc.i4.0 IL_0003: call ""Function C.G(Integer) As Integer"" IL_0008: stloc.0 IL_0009: ldarg.0 IL_000a: ldc.i4.1 IL_000b: call ""Function C.G(Integer) As Integer"" IL_0010: stloc.1 IL_0011: ldarg.0 IL_0012: ldc.i4.2 IL_0013: call ""Function C.G(Integer) As Integer"" IL_0018: stloc.2 IL_0019: ldloc.0 IL_001a: stloc.3 IL_001b: br.s IL_0028 IL_001d: ldc.i4.2 IL_001e: call ""Sub System.Console.WriteLine(Integer)"" IL_0023: nop IL_0024: ldloc.3 IL_0025: ldloc.2 IL_0026: add.ovf IL_0027: stloc.3 IL_0028: ldloc.2 IL_0029: ldc.i4.s 31 IL_002b: shr IL_002c: ldloc.3 IL_002d: xor IL_002e: ldloc.2 IL_002f: ldc.i4.s 31 IL_0031: shr IL_0032: ldloc.1 IL_0033: xor IL_0034: ble.s IL_001d IL_0036: ret } ") End Sub <Fact> Public Sub ForStatement_LateBound() Dim source0 = MarkedSource(" Option Strict On Public Class C Public Shared Sub F() Dim <N:0>a</N:0> As Object = 0 Dim <N:1>b</N:1> As Object = 0 Dim <N:2>c</N:2> As Object = 0 Dim <N:3>d</N:3> As Object = 0 <N:4>For a = b To c Step d System.Console.Write(a) Next</N:4> End Sub End Class") Dim source1 = MarkedSource(" Option Strict On Public Class C Public Shared Sub F() Dim <N:0>a</N:0> As Object = 0 Dim <N:1>b</N:1> As Object = 0 Dim <N:2>c</N:2> As Object = 0 Dim <N:3>d</N:3> As Object = 0 <N:4>For a = b To c Step d System.Console.WriteLine(a) Next</N:4> End Sub End Class") Dim compilation0 = CreateCompilationWithMscorlib40(source0.Tree, {MsvbRef}, ComSafeDebugDll) Dim compilation1 = compilation0.WithSource(source1.Tree) Dim v0 = CompileAndVerify(compilation0) Dim md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData) Dim generation0 = EmitBaseline.CreateInitialBaseline(md0, AddressOf v0.CreateSymReader().GetEncMethodDebugInfo) Dim f0 = compilation0.GetMember(Of MethodSymbol)("C.F") Dim f1 = compilation1.GetMember(Of MethodSymbol)("C.F") Dim diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create(New SemanticEdit(SemanticEditKind.Update, f0, f1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables:=True))) Dim md1 = diff1.GetMetadata() Dim reader1 = md1.Reader v0.VerifyIL("C.F", " { // Code size 77 (0x4d) .maxstack 6 .locals init (Object V_0, //a Object V_1, //b Object V_2, //c Object V_3, //d Object V_4, Boolean V_5, Boolean V_6) IL_0000: nop IL_0001: ldc.i4.0 IL_0002: box ""Integer"" IL_0007: stloc.0 IL_0008: ldc.i4.0 IL_0009: box ""Integer"" IL_000e: stloc.1 IL_000f: ldc.i4.0 IL_0010: box ""Integer"" IL_0015: stloc.2 IL_0016: ldc.i4.0 IL_0017: box ""Integer"" IL_001c: stloc.3 IL_001d: ldloc.0 IL_001e: ldloc.1 IL_001f: ldloc.2 IL_0020: ldloc.3 IL_0021: ldloca.s V_4 IL_0023: ldloca.s V_0 IL_0025: call ""Function Microsoft.VisualBasic.CompilerServices.ObjectFlowControl.ForLoopControl.ForLoopInitObj(Object, Object, Object, Object, ByRef Object, ByRef Object) As Boolean"" IL_002a: stloc.s V_5 IL_002c: ldloc.s V_5 IL_002e: brfalse.s IL_004c IL_0030: ldloc.0 IL_0031: call ""Function System.Runtime.CompilerServices.RuntimeHelpers.GetObjectValue(Object) As Object"" IL_0036: call ""Sub System.Console.Write(Object)"" IL_003b: nop IL_003c: ldloc.0 IL_003d: ldloc.s V_4 IL_003f: ldloca.s V_0 IL_0041: call ""Function Microsoft.VisualBasic.CompilerServices.ObjectFlowControl.ForLoopControl.ForNextCheckObj(Object, Object, ByRef Object) As Boolean"" IL_0046: stloc.s V_6 IL_0048: ldloc.s V_6 IL_004a: brtrue.s IL_0030 IL_004c: ret } ") ' Note that all variables are mapped to their previous slots diff1.VerifyIL("C.F", " { // Code size 77 (0x4d) .maxstack 6 .locals init (Object V_0, //a Object V_1, //b Object V_2, //c Object V_3, //d Object V_4, Boolean V_5, Boolean V_6) IL_0000: nop IL_0001: ldc.i4.0 IL_0002: box ""Integer"" IL_0007: stloc.0 IL_0008: ldc.i4.0 IL_0009: box ""Integer"" IL_000e: stloc.1 IL_000f: ldc.i4.0 IL_0010: box ""Integer"" IL_0015: stloc.2 IL_0016: ldc.i4.0 IL_0017: box ""Integer"" IL_001c: stloc.3 IL_001d: ldloc.0 IL_001e: ldloc.1 IL_001f: ldloc.2 IL_0020: ldloc.3 IL_0021: ldloca.s V_4 IL_0023: ldloca.s V_0 IL_0025: call ""Function Microsoft.VisualBasic.CompilerServices.ObjectFlowControl.ForLoopControl.ForLoopInitObj(Object, Object, Object, Object, ByRef Object, ByRef Object) As Boolean"" IL_002a: stloc.s V_5 IL_002c: ldloc.s V_5 IL_002e: brfalse.s IL_004c IL_0030: ldloc.0 IL_0031: call ""Function System.Runtime.CompilerServices.RuntimeHelpers.GetObjectValue(Object) As Object"" IL_0036: call ""Sub System.Console.WriteLine(Object)"" IL_003b: nop IL_003c: ldloc.0 IL_003d: ldloc.s V_4 IL_003f: ldloca.s V_0 IL_0041: call ""Function Microsoft.VisualBasic.CompilerServices.ObjectFlowControl.ForLoopControl.ForNextCheckObj(Object, Object, ByRef Object) As Boolean"" IL_0046: stloc.s V_6 IL_0048: ldloc.s V_6 IL_004a: brtrue.s IL_0030 IL_004c: ret } ") End Sub <Fact> Public Sub AddImports_AmbiguousCode() Dim source0 = MarkedSource(" Imports System.Threading Class C Shared Sub E() Dim t = New Timer(Sub(s) System.Console.WriteLine(s)) End Sub End Class ") Dim source1 = MarkedSource(" Imports System.Threading Imports System.Timers Class C Shared Sub E() Dim t = New Timer(Sub(s) System.Console.WriteLine(s)) End Sub Shared Sub G() System.Console.WriteLine(new TimersDescriptionAttribute("""")) End Sub End Class ") Dim compilation0 = CreateCompilation(source0.Tree, targetFramework:=TargetFramework.NetStandard20, options:=ComSafeDebugDll) Dim compilation1 = compilation0.WithSource(source1.Tree) Dim e0 = compilation0.GetMember(Of MethodSymbol)("C.E") Dim e1 = compilation1.GetMember(Of MethodSymbol)("C.E") Dim g1 = compilation1.GetMember(Of MethodSymbol)("C.G") Dim v0 = CompileAndVerify(compilation0) Dim md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData) Dim generation0 = EmitBaseline.CreateInitialBaseline(md0, AddressOf v0.CreateSymReader().GetEncMethodDebugInfo) ' Pretend there was an update to C.E to ensure we haven't invalidated the test Dim diffError = compilation1.EmitDifference( generation0, ImmutableArray.Create(New SemanticEdit(SemanticEditKind.Update, e0, e1, GetSyntaxMapFromMarkers(source0, source1), preserveLocalVariables:=True))) diffError.EmitResult.Diagnostics.Verify( Diagnostic(ERRID.ERR_AmbiguousInImports2, "Timer").WithArguments("Timer", "System.Threading, System.Timers").WithLocation(7, 21)) Dim diff = compilation1.EmitDifference( generation0, ImmutableArray.Create(New SemanticEdit(SemanticEditKind.Insert, Nothing, g1))) diff.EmitResult.Diagnostics.Verify() diff.VerifyIL("C.G", " { // Code size 18 (0x12) .maxstack 1 IL_0000: nop IL_0001: ldstr """" IL_0006: newobj ""Sub System.Timers.TimersDescriptionAttribute..ctor(String)"" IL_000b: call ""Sub System.Console.WriteLine(Object)"" IL_0010: nop IL_0011: ret }") End Sub End Class End Namespace
1
dotnet/roslyn
55,428
Test adding nested namespaces
Fixes https://github.com/dotnet/roslyn/issues/54939 The "workaround" that's already implemented is actually the correct behavior.
tmat
2021-08-05T01:19:03Z
2021-08-11T18:38:54Z
bc874ebc5111a2a33221409f895953b1536f6612
1cbbd423e17b186a8f1de89febb4db9a386d180d
Test adding nested namespaces. Fixes https://github.com/dotnet/roslyn/issues/54939 The "workaround" that's already implemented is actually the correct behavior.
./src/EditorFeatures/VisualBasic/LineCommit/AfterCommitCaretMoveUndoPrimitive.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.VisualStudio.Text Imports Microsoft.VisualStudio.Text.Editor Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.LineCommit Friend Class AfterCommitCaretMoveUndoPrimitive Inherits AbstractCommitCaretMoveUndoPrimitive Private ReadOnly _newPosition As Integer Private ReadOnly _newVirtualSpaces As Integer Public Sub New(textBuffer As ITextBuffer, textBufferAssociatedViewService As ITextBufferAssociatedViewService, position As CaretPosition) MyBase.New(textBuffer, textBufferAssociatedViewService) ' Grab the old position and virtual spaces. This is cheaper than holding onto ' a VirtualSnapshotPoint as it won't hold old snapshots alive _newPosition = position.VirtualBufferPosition.Position _newVirtualSpaces = position.VirtualBufferPosition.VirtualSpaces End Sub Public Overrides Sub [Do]() Dim view = TryGetView() If view IsNot Nothing Then view.Caret.MoveTo(New VirtualSnapshotPoint(New SnapshotPoint(view.TextSnapshot, _newPosition), _newVirtualSpaces)) view.Caret.EnsureVisible() End If End Sub Public Overrides Sub Undo() ' When we are going forward, we do nothing here since the BeforeCommitCaretMoveUndoPrimitive ' will take care of it End Sub End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports Microsoft.VisualStudio.Text Imports Microsoft.VisualStudio.Text.Editor Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.LineCommit Friend Class AfterCommitCaretMoveUndoPrimitive Inherits AbstractCommitCaretMoveUndoPrimitive Private ReadOnly _newPosition As Integer Private ReadOnly _newVirtualSpaces As Integer Public Sub New(textBuffer As ITextBuffer, textBufferAssociatedViewService As ITextBufferAssociatedViewService, position As CaretPosition) MyBase.New(textBuffer, textBufferAssociatedViewService) ' Grab the old position and virtual spaces. This is cheaper than holding onto ' a VirtualSnapshotPoint as it won't hold old snapshots alive _newPosition = position.VirtualBufferPosition.Position _newVirtualSpaces = position.VirtualBufferPosition.VirtualSpaces End Sub Public Overrides Sub [Do]() Dim view = TryGetView() If view IsNot Nothing Then view.Caret.MoveTo(New VirtualSnapshotPoint(New SnapshotPoint(view.TextSnapshot, _newPosition), _newVirtualSpaces)) view.Caret.EnsureVisible() End If End Sub Public Overrides Sub Undo() ' When we are going forward, we do nothing here since the BeforeCommitCaretMoveUndoPrimitive ' will take care of it End Sub End Class End Namespace
-1
dotnet/roslyn
55,428
Test adding nested namespaces
Fixes https://github.com/dotnet/roslyn/issues/54939 The "workaround" that's already implemented is actually the correct behavior.
tmat
2021-08-05T01:19:03Z
2021-08-11T18:38:54Z
bc874ebc5111a2a33221409f895953b1536f6612
1cbbd423e17b186a8f1de89febb4db9a386d180d
Test adding nested namespaces. Fixes https://github.com/dotnet/roslyn/issues/54939 The "workaround" that's already implemented is actually the correct behavior.
./src/Compilers/VisualBasic/Portable/Syntax/BaseSyntaxExtensions.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Runtime.CompilerServices Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.Syntax Friend Module BaseSyntaxExtensions ' Methods <Extension()> Friend Function ToGreen(node As InternalSyntax.VisualBasicSyntaxNode) As InternalSyntax.VisualBasicSyntaxNode Debug.Assert(False, "just use the node") Return node End Function <Extension()> Friend Function ToGreen(node As VisualBasicSyntaxNode) As InternalSyntax.VisualBasicSyntaxNode Return If(node Is Nothing, Nothing, node.VbGreen) End Function <Extension()> Friend Function ToRed(node As InternalSyntax.VisualBasicSyntaxNode) As SyntaxNode If node Is Nothing Then Return Nothing End If Dim red = node.CreateRed(Nothing, 0) Return red End Function <Extension()> Friend Function ToRed(node As VisualBasicSyntaxNode) As VisualBasicSyntaxNode Debug.Assert(False, "just use the node") Return node End Function End Module End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Runtime.CompilerServices Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.Syntax Friend Module BaseSyntaxExtensions ' Methods <Extension()> Friend Function ToGreen(node As InternalSyntax.VisualBasicSyntaxNode) As InternalSyntax.VisualBasicSyntaxNode Debug.Assert(False, "just use the node") Return node End Function <Extension()> Friend Function ToGreen(node As VisualBasicSyntaxNode) As InternalSyntax.VisualBasicSyntaxNode Return If(node Is Nothing, Nothing, node.VbGreen) End Function <Extension()> Friend Function ToRed(node As InternalSyntax.VisualBasicSyntaxNode) As SyntaxNode If node Is Nothing Then Return Nothing End If Dim red = node.CreateRed(Nothing, 0) Return red End Function <Extension()> Friend Function ToRed(node As VisualBasicSyntaxNode) As VisualBasicSyntaxNode Debug.Assert(False, "just use the node") Return node End Function End Module End Namespace
-1
dotnet/roslyn
55,428
Test adding nested namespaces
Fixes https://github.com/dotnet/roslyn/issues/54939 The "workaround" that's already implemented is actually the correct behavior.
tmat
2021-08-05T01:19:03Z
2021-08-11T18:38:54Z
bc874ebc5111a2a33221409f895953b1536f6612
1cbbd423e17b186a8f1de89febb4db9a386d180d
Test adding nested namespaces. Fixes https://github.com/dotnet/roslyn/issues/54939 The "workaround" that's already implemented is actually the correct behavior.
./src/VisualStudio/Core/Impl/CodeModel/InternalElements/CodeClass.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Runtime.InteropServices; using Microsoft.CodeAnalysis; using Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.Collections; using Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.Interop; using Microsoft.VisualStudio.LanguageServices.Implementation.Interop; namespace Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.InternalElements { [ComVisible(true)] [ComDefaultInterface(typeof(EnvDTE80.CodeClass2))] public sealed class CodeClass : AbstractCodeType, EnvDTE.CodeClass, EnvDTE80.CodeClass2, ICodeClassBase { private static readonly SymbolDisplayFormat s_BaseNameFormat = new SymbolDisplayFormat( typeQualificationStyle: SymbolDisplayTypeQualificationStyle.NameAndContainingTypesAndNamespaces, genericsOptions: SymbolDisplayGenericsOptions.IncludeTypeParameters, memberOptions: SymbolDisplayMemberOptions.IncludeContainingType, miscellaneousOptions: SymbolDisplayMiscellaneousOptions.UseSpecialTypes); internal static EnvDTE.CodeClass Create( CodeModelState state, FileCodeModel fileCodeModel, SyntaxNodeKey nodeKey, int? nodeKind) { var element = new CodeClass(state, fileCodeModel, nodeKey, nodeKind); var result = (EnvDTE.CodeClass)ComAggregate.CreateAggregatedObject(element); fileCodeModel.OnCodeElementCreated(nodeKey, (EnvDTE.CodeElement)result); return result; } internal static EnvDTE.CodeClass CreateUnknown( CodeModelState state, FileCodeModel fileCodeModel, int nodeKind, string name) { var element = new CodeClass(state, fileCodeModel, nodeKind, name); return (EnvDTE.CodeClass)ComAggregate.CreateAggregatedObject(element); } private CodeClass( CodeModelState state, FileCodeModel fileCodeModel, SyntaxNodeKey nodeKey, int? nodeKind) : base(state, fileCodeModel, nodeKey, nodeKind) { } private CodeClass( CodeModelState state, FileCodeModel fileCodeModel, int nodeKind, string name) : base(state, fileCodeModel, nodeKind, name) { } public override EnvDTE.vsCMElement Kind { get { return this.CodeModelService.GetElementKind(LookupNode()); } } public bool IsAbstract { get { return (InheritanceKind & EnvDTE80.vsCMInheritanceKind.vsCMInheritanceKindAbstract) != 0; } set { var inheritanceKind = InheritanceKind; var newInheritanceKind = inheritanceKind; if (value) { newInheritanceKind |= EnvDTE80.vsCMInheritanceKind.vsCMInheritanceKindAbstract; newInheritanceKind &= ~EnvDTE80.vsCMInheritanceKind.vsCMInheritanceKindSealed; } else { newInheritanceKind &= ~EnvDTE80.vsCMInheritanceKind.vsCMInheritanceKindAbstract; } if (inheritanceKind != newInheritanceKind) { InheritanceKind = newInheritanceKind; } } } public EnvDTE80.vsCMClassKind ClassKind { get { return CodeModelService.GetClassKind(LookupNode(), (INamedTypeSymbol)LookupSymbol()); } set { UpdateNode(FileCodeModel.UpdateClassKind, value); } } public EnvDTE80.vsCMInheritanceKind InheritanceKind { get { return CodeModelService.GetInheritanceKind(LookupNode(), (INamedTypeSymbol)LookupSymbol()); } set { UpdateNode(FileCodeModel.UpdateInheritanceKind, value); } } public EnvDTE.CodeElements PartialClasses { get { return PartialTypeCollection.Create(State, this); } } public EnvDTE.CodeElements Parts { get { return PartialTypeCollection.Create(State, this); } } public EnvDTE.CodeClass AddClass(string name, object position, object bases, object implementedInterfaces, EnvDTE.vsCMAccess access) { return FileCodeModel.EnsureEditor(() => { return FileCodeModel.AddClass(LookupNode(), name, position, bases, implementedInterfaces, access); }); } public EnvDTE.CodeDelegate AddDelegate(string name, object type, object position, EnvDTE.vsCMAccess access) { return FileCodeModel.EnsureEditor(() => { return FileCodeModel.AddDelegate(LookupNode(), name, type, position, access); }); } public EnvDTE.CodeEnum AddEnum(string name, object position, object bases, EnvDTE.vsCMAccess access) { return FileCodeModel.EnsureEditor(() => { return FileCodeModel.AddEnum(LookupNode(), name, position, bases, access); }); } public EnvDTE80.CodeEvent AddEvent(string name, string fullDelegateName, bool createPropertyStyleEvent, object location, EnvDTE.vsCMAccess access) { return FileCodeModel.EnsureEditor(() => { return FileCodeModel.AddEvent(LookupNode(), name, fullDelegateName, createPropertyStyleEvent, location, access); }); } public EnvDTE.CodeFunction AddFunction(string name, EnvDTE.vsCMFunction kind, object type, object position, EnvDTE.vsCMAccess access, object location) { return FileCodeModel.EnsureEditor(() => { return FileCodeModel.AddFunction(LookupNode(), name, kind, type, position, access); }); } public EnvDTE.CodeProperty AddProperty(string getterName, string putterName, object type, object position, EnvDTE.vsCMAccess access, object location) { return FileCodeModel.EnsureEditor(() => { return FileCodeModel.AddProperty(LookupNode(), getterName, putterName, type, position, access); }); } public EnvDTE.CodeStruct AddStruct(string name, object position, object bases, object implementedInterfaces, EnvDTE.vsCMAccess access) { return FileCodeModel.EnsureEditor(() => { return FileCodeModel.AddStruct(LookupNode(), name, position, bases, implementedInterfaces, access); }); } public EnvDTE.CodeVariable AddVariable(string name, object type, object position, EnvDTE.vsCMAccess access, object location) { return FileCodeModel.EnsureEditor(() => { // NOTE: C# ignores this location parameter. return FileCodeModel.AddVariable(LookupNode(), name, type, position, access); }); } public int GetBaseName(out string pBaseName) { var typeSymbol = LookupTypeSymbol(); if (typeSymbol?.BaseType == null) { pBaseName = null; return VSConstants.E_FAIL; } pBaseName = typeSymbol.BaseType.ToDisplayString(s_BaseNameFormat); return VSConstants.S_OK; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Runtime.InteropServices; using Microsoft.CodeAnalysis; using Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.Collections; using Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.Interop; using Microsoft.VisualStudio.LanguageServices.Implementation.Interop; namespace Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.InternalElements { [ComVisible(true)] [ComDefaultInterface(typeof(EnvDTE80.CodeClass2))] public sealed class CodeClass : AbstractCodeType, EnvDTE.CodeClass, EnvDTE80.CodeClass2, ICodeClassBase { private static readonly SymbolDisplayFormat s_BaseNameFormat = new SymbolDisplayFormat( typeQualificationStyle: SymbolDisplayTypeQualificationStyle.NameAndContainingTypesAndNamespaces, genericsOptions: SymbolDisplayGenericsOptions.IncludeTypeParameters, memberOptions: SymbolDisplayMemberOptions.IncludeContainingType, miscellaneousOptions: SymbolDisplayMiscellaneousOptions.UseSpecialTypes); internal static EnvDTE.CodeClass Create( CodeModelState state, FileCodeModel fileCodeModel, SyntaxNodeKey nodeKey, int? nodeKind) { var element = new CodeClass(state, fileCodeModel, nodeKey, nodeKind); var result = (EnvDTE.CodeClass)ComAggregate.CreateAggregatedObject(element); fileCodeModel.OnCodeElementCreated(nodeKey, (EnvDTE.CodeElement)result); return result; } internal static EnvDTE.CodeClass CreateUnknown( CodeModelState state, FileCodeModel fileCodeModel, int nodeKind, string name) { var element = new CodeClass(state, fileCodeModel, nodeKind, name); return (EnvDTE.CodeClass)ComAggregate.CreateAggregatedObject(element); } private CodeClass( CodeModelState state, FileCodeModel fileCodeModel, SyntaxNodeKey nodeKey, int? nodeKind) : base(state, fileCodeModel, nodeKey, nodeKind) { } private CodeClass( CodeModelState state, FileCodeModel fileCodeModel, int nodeKind, string name) : base(state, fileCodeModel, nodeKind, name) { } public override EnvDTE.vsCMElement Kind { get { return this.CodeModelService.GetElementKind(LookupNode()); } } public bool IsAbstract { get { return (InheritanceKind & EnvDTE80.vsCMInheritanceKind.vsCMInheritanceKindAbstract) != 0; } set { var inheritanceKind = InheritanceKind; var newInheritanceKind = inheritanceKind; if (value) { newInheritanceKind |= EnvDTE80.vsCMInheritanceKind.vsCMInheritanceKindAbstract; newInheritanceKind &= ~EnvDTE80.vsCMInheritanceKind.vsCMInheritanceKindSealed; } else { newInheritanceKind &= ~EnvDTE80.vsCMInheritanceKind.vsCMInheritanceKindAbstract; } if (inheritanceKind != newInheritanceKind) { InheritanceKind = newInheritanceKind; } } } public EnvDTE80.vsCMClassKind ClassKind { get { return CodeModelService.GetClassKind(LookupNode(), (INamedTypeSymbol)LookupSymbol()); } set { UpdateNode(FileCodeModel.UpdateClassKind, value); } } public EnvDTE80.vsCMInheritanceKind InheritanceKind { get { return CodeModelService.GetInheritanceKind(LookupNode(), (INamedTypeSymbol)LookupSymbol()); } set { UpdateNode(FileCodeModel.UpdateInheritanceKind, value); } } public EnvDTE.CodeElements PartialClasses { get { return PartialTypeCollection.Create(State, this); } } public EnvDTE.CodeElements Parts { get { return PartialTypeCollection.Create(State, this); } } public EnvDTE.CodeClass AddClass(string name, object position, object bases, object implementedInterfaces, EnvDTE.vsCMAccess access) { return FileCodeModel.EnsureEditor(() => { return FileCodeModel.AddClass(LookupNode(), name, position, bases, implementedInterfaces, access); }); } public EnvDTE.CodeDelegate AddDelegate(string name, object type, object position, EnvDTE.vsCMAccess access) { return FileCodeModel.EnsureEditor(() => { return FileCodeModel.AddDelegate(LookupNode(), name, type, position, access); }); } public EnvDTE.CodeEnum AddEnum(string name, object position, object bases, EnvDTE.vsCMAccess access) { return FileCodeModel.EnsureEditor(() => { return FileCodeModel.AddEnum(LookupNode(), name, position, bases, access); }); } public EnvDTE80.CodeEvent AddEvent(string name, string fullDelegateName, bool createPropertyStyleEvent, object location, EnvDTE.vsCMAccess access) { return FileCodeModel.EnsureEditor(() => { return FileCodeModel.AddEvent(LookupNode(), name, fullDelegateName, createPropertyStyleEvent, location, access); }); } public EnvDTE.CodeFunction AddFunction(string name, EnvDTE.vsCMFunction kind, object type, object position, EnvDTE.vsCMAccess access, object location) { return FileCodeModel.EnsureEditor(() => { return FileCodeModel.AddFunction(LookupNode(), name, kind, type, position, access); }); } public EnvDTE.CodeProperty AddProperty(string getterName, string putterName, object type, object position, EnvDTE.vsCMAccess access, object location) { return FileCodeModel.EnsureEditor(() => { return FileCodeModel.AddProperty(LookupNode(), getterName, putterName, type, position, access); }); } public EnvDTE.CodeStruct AddStruct(string name, object position, object bases, object implementedInterfaces, EnvDTE.vsCMAccess access) { return FileCodeModel.EnsureEditor(() => { return FileCodeModel.AddStruct(LookupNode(), name, position, bases, implementedInterfaces, access); }); } public EnvDTE.CodeVariable AddVariable(string name, object type, object position, EnvDTE.vsCMAccess access, object location) { return FileCodeModel.EnsureEditor(() => { // NOTE: C# ignores this location parameter. return FileCodeModel.AddVariable(LookupNode(), name, type, position, access); }); } public int GetBaseName(out string pBaseName) { var typeSymbol = LookupTypeSymbol(); if (typeSymbol?.BaseType == null) { pBaseName = null; return VSConstants.E_FAIL; } pBaseName = typeSymbol.BaseType.ToDisplayString(s_BaseNameFormat); return VSConstants.S_OK; } } }
-1
dotnet/roslyn
55,428
Test adding nested namespaces
Fixes https://github.com/dotnet/roslyn/issues/54939 The "workaround" that's already implemented is actually the correct behavior.
tmat
2021-08-05T01:19:03Z
2021-08-11T18:38:54Z
bc874ebc5111a2a33221409f895953b1536f6612
1cbbd423e17b186a8f1de89febb4db9a386d180d
Test adding nested namespaces. Fixes https://github.com/dotnet/roslyn/issues/54939 The "workaround" that's already implemented is actually the correct behavior.
./src/Analyzers/VisualBasic/Analyzers/SimplifyBooleanExpression/VisualBasicSimplifyConditionalDiagnosticAnalyzer.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.VisualBasic.LanguageServices Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Microsoft.CodeAnalysis.Diagnostics Imports Microsoft.CodeAnalysis.LanguageServices Imports Microsoft.CodeAnalysis.Operations Imports Microsoft.CodeAnalysis.SimplifyBooleanExpression Namespace Microsoft.CodeAnalysis.VisualBasic.SimplifyBooleanExpression <DiagnosticAnalyzer(LanguageNames.VisualBasic)> Friend Class VisualBasicSimplifyConditionalDiagnosticAnalyzer Inherits AbstractSimplifyConditionalDiagnosticAnalyzer(Of SyntaxKind, ExpressionSyntax, TernaryConditionalExpressionSyntax) Protected Overrides ReadOnly Property SyntaxFacts As ISyntaxFacts = VisualBasicSyntaxFacts.Instance Protected Overrides Function GetConversion(semanticModel As SemanticModel, node As ExpressionSyntax, cancellationToken As CancellationToken) As CommonConversion Return semanticModel.GetConversion(node, cancellationToken).ToCommonConversion() 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.VisualBasic.LanguageServices Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Microsoft.CodeAnalysis.Diagnostics Imports Microsoft.CodeAnalysis.LanguageServices Imports Microsoft.CodeAnalysis.Operations Imports Microsoft.CodeAnalysis.SimplifyBooleanExpression Namespace Microsoft.CodeAnalysis.VisualBasic.SimplifyBooleanExpression <DiagnosticAnalyzer(LanguageNames.VisualBasic)> Friend Class VisualBasicSimplifyConditionalDiagnosticAnalyzer Inherits AbstractSimplifyConditionalDiagnosticAnalyzer(Of SyntaxKind, ExpressionSyntax, TernaryConditionalExpressionSyntax) Protected Overrides ReadOnly Property SyntaxFacts As ISyntaxFacts = VisualBasicSyntaxFacts.Instance Protected Overrides Function GetConversion(semanticModel As SemanticModel, node As ExpressionSyntax, cancellationToken As CancellationToken) As CommonConversion Return semanticModel.GetConversion(node, cancellationToken).ToCommonConversion() End Function End Class End Namespace
-1
dotnet/roslyn
55,428
Test adding nested namespaces
Fixes https://github.com/dotnet/roslyn/issues/54939 The "workaround" that's already implemented is actually the correct behavior.
tmat
2021-08-05T01:19:03Z
2021-08-11T18:38:54Z
bc874ebc5111a2a33221409f895953b1536f6612
1cbbd423e17b186a8f1de89febb4db9a386d180d
Test adding nested namespaces. Fixes https://github.com/dotnet/roslyn/issues/54939 The "workaround" that's already implemented is actually the correct behavior.
./src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/Extensions/TextDocumentExtensions.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Shared.Extensions { internal static partial class TextDocumentExtensions { /// <summary> /// Creates a new instance of this text document updated to have the text specified. /// </summary> public static TextDocument WithText(this TextDocument textDocument, SourceText text) { switch (textDocument) { case Document document: return document.WithText(text); case AnalyzerConfigDocument analyzerConfigDocument: return analyzerConfigDocument.WithAnalyzerConfigDocumentText(text); case AdditionalDocument additionalDocument: return additionalDocument.WithAdditionalDocumentText(text); default: throw ExceptionUtilities.Unreachable; } } /// <summary> /// Creates a new instance of this additional document updated to have the text specified. /// </summary> public static TextDocument WithAdditionalDocumentText(this TextDocument textDocument, SourceText text) { Contract.ThrowIfFalse(textDocument is AdditionalDocument); return textDocument.Project.Solution.WithAdditionalDocumentText(textDocument.Id, text, PreservationMode.PreserveIdentity).GetTextDocument(textDocument.Id)!; } /// <summary> /// Creates a new instance of this analyzer config document updated to have the text specified. /// </summary> public static TextDocument WithAnalyzerConfigDocumentText(this TextDocument textDocument, SourceText text) { Contract.ThrowIfFalse(textDocument is AnalyzerConfigDocument); return textDocument.Project.Solution.WithAnalyzerConfigDocumentText(textDocument.Id, text, PreservationMode.PreserveIdentity).GetTextDocument(textDocument.Id)!; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Shared.Extensions { internal static partial class TextDocumentExtensions { /// <summary> /// Creates a new instance of this text document updated to have the text specified. /// </summary> public static TextDocument WithText(this TextDocument textDocument, SourceText text) { switch (textDocument) { case Document document: return document.WithText(text); case AnalyzerConfigDocument analyzerConfigDocument: return analyzerConfigDocument.WithAnalyzerConfigDocumentText(text); case AdditionalDocument additionalDocument: return additionalDocument.WithAdditionalDocumentText(text); default: throw ExceptionUtilities.Unreachable; } } /// <summary> /// Creates a new instance of this additional document updated to have the text specified. /// </summary> public static TextDocument WithAdditionalDocumentText(this TextDocument textDocument, SourceText text) { Contract.ThrowIfFalse(textDocument is AdditionalDocument); return textDocument.Project.Solution.WithAdditionalDocumentText(textDocument.Id, text, PreservationMode.PreserveIdentity).GetTextDocument(textDocument.Id)!; } /// <summary> /// Creates a new instance of this analyzer config document updated to have the text specified. /// </summary> public static TextDocument WithAnalyzerConfigDocumentText(this TextDocument textDocument, SourceText text) { Contract.ThrowIfFalse(textDocument is AnalyzerConfigDocument); return textDocument.Project.Solution.WithAnalyzerConfigDocumentText(textDocument.Id, text, PreservationMode.PreserveIdentity).GetTextDocument(textDocument.Id)!; } } }
-1
dotnet/roslyn
55,428
Test adding nested namespaces
Fixes https://github.com/dotnet/roslyn/issues/54939 The "workaround" that's already implemented is actually the correct behavior.
tmat
2021-08-05T01:19:03Z
2021-08-11T18:38:54Z
bc874ebc5111a2a33221409f895953b1536f6612
1cbbd423e17b186a8f1de89febb4db9a386d180d
Test adding nested namespaces. Fixes https://github.com/dotnet/roslyn/issues/54939 The "workaround" that's already implemented is actually the correct behavior.
./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Formatting/Context/FormattingContext.AnchorData.cs
// Licensed to the .NET Foundation under one or more agreements. // 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.Formatting.Rules; using Microsoft.CodeAnalysis.Shared.Collections; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.Formatting { internal partial class FormattingContext { /// <summary> /// data that will be used in an interval tree related to Anchor. /// </summary> private class AnchorData { private readonly AnchorIndentationOperation _operation; public AnchorData(AnchorIndentationOperation operation, int originalColumn) { _operation = operation; this.OriginalColumn = originalColumn; } public TextSpan TextSpan => _operation.TextSpan; public SyntaxToken AnchorToken => _operation.AnchorToken; public SyntaxToken StartToken => _operation.StartToken; public SyntaxToken EndToken => _operation.EndToken; public int OriginalColumn { get; } } private readonly struct FormattingContextIntervalIntrospector : IIntervalIntrospector<AnchorData>, IIntervalIntrospector<IndentationData>, IIntervalIntrospector<RelativeIndentationData> { int IIntervalIntrospector<AnchorData>.GetStart(AnchorData value) => value.TextSpan.Start; int IIntervalIntrospector<AnchorData>.GetLength(AnchorData value) => value.TextSpan.Length; int IIntervalIntrospector<IndentationData>.GetStart(IndentationData value) => value.TextSpan.Start; int IIntervalIntrospector<IndentationData>.GetLength(IndentationData value) => value.TextSpan.Length; int IIntervalIntrospector<RelativeIndentationData>.GetStart(RelativeIndentationData value) => value.InseparableRegionSpan.Start; int IIntervalIntrospector<RelativeIndentationData>.GetLength(RelativeIndentationData value) => value.InseparableRegionSpan.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. using Microsoft.CodeAnalysis.Formatting.Rules; using Microsoft.CodeAnalysis.Shared.Collections; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.Formatting { internal partial class FormattingContext { /// <summary> /// data that will be used in an interval tree related to Anchor. /// </summary> private class AnchorData { private readonly AnchorIndentationOperation _operation; public AnchorData(AnchorIndentationOperation operation, int originalColumn) { _operation = operation; this.OriginalColumn = originalColumn; } public TextSpan TextSpan => _operation.TextSpan; public SyntaxToken AnchorToken => _operation.AnchorToken; public SyntaxToken StartToken => _operation.StartToken; public SyntaxToken EndToken => _operation.EndToken; public int OriginalColumn { get; } } private readonly struct FormattingContextIntervalIntrospector : IIntervalIntrospector<AnchorData>, IIntervalIntrospector<IndentationData>, IIntervalIntrospector<RelativeIndentationData> { int IIntervalIntrospector<AnchorData>.GetStart(AnchorData value) => value.TextSpan.Start; int IIntervalIntrospector<AnchorData>.GetLength(AnchorData value) => value.TextSpan.Length; int IIntervalIntrospector<IndentationData>.GetStart(IndentationData value) => value.TextSpan.Start; int IIntervalIntrospector<IndentationData>.GetLength(IndentationData value) => value.TextSpan.Length; int IIntervalIntrospector<RelativeIndentationData>.GetStart(RelativeIndentationData value) => value.InseparableRegionSpan.Start; int IIntervalIntrospector<RelativeIndentationData>.GetLength(RelativeIndentationData value) => value.InseparableRegionSpan.Length; } } }
-1
dotnet/roslyn
55,428
Test adding nested namespaces
Fixes https://github.com/dotnet/roslyn/issues/54939 The "workaround" that's already implemented is actually the correct behavior.
tmat
2021-08-05T01:19:03Z
2021-08-11T18:38:54Z
bc874ebc5111a2a33221409f895953b1536f6612
1cbbd423e17b186a8f1de89febb4db9a386d180d
Test adding nested namespaces. Fixes https://github.com/dotnet/roslyn/issues/54939 The "workaround" that's already implemented is actually the correct behavior.
./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Collections/IntervalTree`1.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Shared.Collections { /// <summary> /// An interval tree represents an ordered tree data structure to store intervals of the form /// [start, end). It allows you to efficiently find all intervals that intersect or overlap /// a provided interval. /// </summary> internal partial class IntervalTree<T> : IEnumerable<T> { public static readonly IntervalTree<T> Empty = new(); protected Node? root; private delegate bool TestInterval<TIntrospector>(T value, int start, int length, in TIntrospector introspector) where TIntrospector : struct, IIntervalIntrospector<T>; private static readonly ObjectPool<Stack<(Node? node, bool firstTime)>> s_stackPool = SharedPools.Default<Stack<(Node? node, bool firstTime)>>(); public IntervalTree() { } public static IntervalTree<T> Create<TIntrospector>(in TIntrospector introspector, IEnumerable<T> values) where TIntrospector : struct, IIntervalIntrospector<T> { var result = new IntervalTree<T>(); foreach (var value in values) { result.root = Insert(result.root, new Node(value), in introspector); } return result; } protected static bool Contains<TIntrospector>(T value, int start, int length, in TIntrospector introspector) where TIntrospector : struct, IIntervalIntrospector<T> { var otherStart = start; var otherEnd = start + length; var thisEnd = GetEnd(value, in introspector); var thisStart = introspector.GetStart(value); // make sure "Contains" test to be same as what TextSpan does if (length == 0) { return thisStart <= otherStart && otherEnd < thisEnd; } return thisStart <= otherStart && otherEnd <= thisEnd; } private static bool IntersectsWith<TIntrospector>(T value, int start, int length, in TIntrospector introspector) where TIntrospector : struct, IIntervalIntrospector<T> { var otherStart = start; var otherEnd = start + length; var thisEnd = GetEnd(value, in introspector); var thisStart = introspector.GetStart(value); return otherStart <= thisEnd && otherEnd >= thisStart; } private static bool OverlapsWith<TIntrospector>(T value, int start, int length, in TIntrospector introspector) where TIntrospector : struct, IIntervalIntrospector<T> { var otherStart = start; var otherEnd = start + length; var thisEnd = GetEnd(value, in introspector); var thisStart = introspector.GetStart(value); if (length == 0) { return thisStart < otherStart && otherStart < thisEnd; } var overlapStart = Math.Max(thisStart, otherStart); var overlapEnd = Math.Min(thisEnd, otherEnd); return overlapStart < overlapEnd; } public ImmutableArray<T> GetIntervalsThatOverlapWith<TIntrospector>(int start, int length, in TIntrospector introspector) where TIntrospector : struct, IIntervalIntrospector<T> => this.GetIntervalsThatMatch(start, length, Tests<TIntrospector>.OverlapsWithTest, in introspector); public ImmutableArray<T> GetIntervalsThatIntersectWith<TIntrospector>(int start, int length, in TIntrospector introspector) where TIntrospector : struct, IIntervalIntrospector<T> => this.GetIntervalsThatMatch(start, length, Tests<TIntrospector>.IntersectsWithTest, in introspector); public ImmutableArray<T> GetIntervalsThatContain<TIntrospector>(int start, int length, in TIntrospector introspector) where TIntrospector : struct, IIntervalIntrospector<T> => this.GetIntervalsThatMatch(start, length, Tests<TIntrospector>.ContainsTest, in introspector); public void FillWithIntervalsThatOverlapWith<TIntrospector>(int start, int length, ref TemporaryArray<T> builder, in TIntrospector introspector) where TIntrospector : struct, IIntervalIntrospector<T> => this.FillWithIntervalsThatMatch(start, length, Tests<TIntrospector>.OverlapsWithTest, ref builder, in introspector, stopAfterFirst: false); public void FillWithIntervalsThatIntersectWith<TIntrospector>(int start, int length, ref TemporaryArray<T> builder, in TIntrospector introspector) where TIntrospector : struct, IIntervalIntrospector<T> => this.FillWithIntervalsThatMatch(start, length, Tests<TIntrospector>.IntersectsWithTest, ref builder, in introspector, stopAfterFirst: false); public void FillWithIntervalsThatContain<TIntrospector>(int start, int length, ref TemporaryArray<T> builder, in TIntrospector introspector) where TIntrospector : struct, IIntervalIntrospector<T> => this.FillWithIntervalsThatMatch(start, length, Tests<TIntrospector>.ContainsTest, ref builder, in introspector, stopAfterFirst: false); public bool HasIntervalThatIntersectsWith<TIntrospector>(int position, in TIntrospector introspector) where TIntrospector : struct, IIntervalIntrospector<T> => HasIntervalThatIntersectsWith(position, 0, in introspector); public bool HasIntervalThatIntersectsWith<TIntrospector>(int start, int length, in TIntrospector introspector) where TIntrospector : struct, IIntervalIntrospector<T> => Any(start, length, Tests<TIntrospector>.IntersectsWithTest, in introspector); public bool HasIntervalThatOverlapsWith<TIntrospector>(int start, int length, in TIntrospector introspector) where TIntrospector : struct, IIntervalIntrospector<T> => Any(start, length, Tests<TIntrospector>.OverlapsWithTest, in introspector); public bool HasIntervalThatContains<TIntrospector>(int start, int length, in TIntrospector introspector) where TIntrospector : struct, IIntervalIntrospector<T> => Any(start, length, Tests<TIntrospector>.ContainsTest, in introspector); private bool Any<TIntrospector>(int start, int length, TestInterval<TIntrospector> testInterval, in TIntrospector introspector) where TIntrospector : struct, IIntervalIntrospector<T> { using var result = TemporaryArray<T>.Empty; var matches = FillWithIntervalsThatMatch(start, length, testInterval, ref result.AsRef(), in introspector, stopAfterFirst: true); return matches > 0; } private ImmutableArray<T> GetIntervalsThatMatch<TIntrospector>( int start, int length, TestInterval<TIntrospector> testInterval, in TIntrospector introspector) where TIntrospector : struct, IIntervalIntrospector<T> { using var result = TemporaryArray<T>.Empty; FillWithIntervalsThatMatch(start, length, testInterval, ref result.AsRef(), in introspector, stopAfterFirst: false); return result.ToImmutableAndClear(); } /// <returns>The number of matching intervals found by the method.</returns> private int FillWithIntervalsThatMatch<TIntrospector>( int start, int length, TestInterval<TIntrospector> testInterval, ref TemporaryArray<T> builder, in TIntrospector introspector, bool stopAfterFirst) where TIntrospector : struct, IIntervalIntrospector<T> { if (root == null) { return 0; } var candidates = s_stackPool.Allocate(); var matches = FillWithIntervalsThatMatch( start, length, testInterval, ref builder, in introspector, stopAfterFirst, candidates); s_stackPool.ClearAndFree(candidates); return matches; } /// <returns>The number of matching intervals found by the method.</returns> private int FillWithIntervalsThatMatch<TIntrospector>( int start, int length, TestInterval<TIntrospector> testInterval, ref TemporaryArray<T> builder, in TIntrospector introspector, bool stopAfterFirst, Stack<(Node? node, bool firstTime)> candidates) where TIntrospector : struct, IIntervalIntrospector<T> { var matches = 0; var end = start + length; candidates.Push((root, firstTime: true)); while (candidates.Count > 0) { var currentTuple = candidates.Pop(); var currentNode = currentTuple.node; RoslynDebug.Assert(currentNode != null); var firstTime = currentTuple.firstTime; if (!firstTime) { // We're seeing this node for the second time (as we walk back up the left // side of it). Now see if it matches our test, and if so return it out. if (testInterval(currentNode.Value, start, length, in introspector)) { matches++; builder.Add(currentNode.Value); if (stopAfterFirst) { return 1; } } } else { // First time we're seeing this node. In order to see the node 'in-order', // we push the right side, then the node again, then the left side. This // time we mark the current node with 'false' to indicate that it's the // second time we're seeing it the next time it comes around. // right children's starts will never be to the left of the parent's start // so we should consider right subtree only if root's start overlaps with // interval's End, if (introspector.GetStart(currentNode.Value) <= end) { var right = currentNode.Right; if (right != null && GetEnd(right.MaxEndNode.Value, in introspector) >= start) { candidates.Push((right, firstTime: true)); } } candidates.Push((currentNode, firstTime: false)); // only if left's maxVal overlaps with interval's start, we should consider // left subtree var left = currentNode.Left; if (left != null && GetEnd(left.MaxEndNode.Value, in introspector) >= start) { candidates.Push((left, firstTime: true)); } } } return matches; } public bool IsEmpty() => this.root == null; protected static Node Insert<TIntrospector>(Node? root, Node newNode, in TIntrospector introspector) where TIntrospector : struct, IIntervalIntrospector<T> { var newNodeStart = introspector.GetStart(newNode.Value); return Insert(root, newNode, newNodeStart, in introspector); } private static Node Insert<TIntrospector>(Node? root, Node newNode, int newNodeStart, in TIntrospector introspector) where TIntrospector : struct, IIntervalIntrospector<T> { if (root == null) { return newNode; } Node? newLeft, newRight; if (newNodeStart < introspector.GetStart(root.Value)) { newLeft = Insert(root.Left, newNode, newNodeStart, in introspector); newRight = root.Right; } else { newLeft = root.Left; newRight = Insert(root.Right, newNode, newNodeStart, in introspector); } root.SetLeftRight(newLeft, newRight, in introspector); var newRoot = root; return Balance(newRoot, in introspector); } private static Node Balance<TIntrospector>(Node node, in TIntrospector introspector) where TIntrospector : struct, IIntervalIntrospector<T> { var balanceFactor = BalanceFactor(node); if (balanceFactor == -2) { var rightBalance = BalanceFactor(node.Right); if (rightBalance == -1) { return node.LeftRotation(in introspector); } else { Debug.Assert(rightBalance == 1); return node.InnerRightOuterLeftRotation(in introspector); } } else if (balanceFactor == 2) { var leftBalance = BalanceFactor(node.Left); if (leftBalance == 1) { return node.RightRotation(in introspector); } else { Debug.Assert(leftBalance == -1); return node.InnerLeftOuterRightRotation(in introspector); } } return node; } public IEnumerator<T> GetEnumerator() { if (root == null) { yield break; } var candidates = new Stack<(Node? node, bool firstTime)>(); candidates.Push((root, firstTime: true)); while (candidates.Count != 0) { var (currentNode, firstTime) = candidates.Pop(); if (currentNode != null) { if (firstTime) { // First time seeing this node. Mark that we've been seen and recurse // down the left side. The next time we see this node we'll yield it // out. candidates.Push((currentNode.Right, firstTime: true)); candidates.Push((currentNode, firstTime: false)); candidates.Push((currentNode.Left, firstTime: true)); } else { yield return currentNode.Value; } } } } IEnumerator IEnumerable.GetEnumerator() => this.GetEnumerator(); protected static int GetEnd<TIntrospector>(T value, in TIntrospector introspector) where TIntrospector : struct, IIntervalIntrospector<T> => introspector.GetStart(value) + introspector.GetLength(value); protected static int MaxEndValue<TIntrospector>(Node? node, in TIntrospector introspector) where TIntrospector : struct, IIntervalIntrospector<T> => node == null ? 0 : GetEnd(node.MaxEndNode.Value, in introspector); private static int Height(Node? node) => node == null ? 0 : node.Height; private static int BalanceFactor(Node? node) => node == null ? 0 : Height(node.Left) - Height(node.Right); private static class Tests<TIntrospector> where TIntrospector : struct, IIntervalIntrospector<T> { public static readonly TestInterval<TIntrospector> IntersectsWithTest = IntersectsWith; public static readonly TestInterval<TIntrospector> ContainsTest = Contains; public static readonly TestInterval<TIntrospector> OverlapsWithTest = OverlapsWith; } } }
// Licensed to the .NET Foundation under one or more agreements. // 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; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Shared.Collections { /// <summary> /// An interval tree represents an ordered tree data structure to store intervals of the form /// [start, end). It allows you to efficiently find all intervals that intersect or overlap /// a provided interval. /// </summary> internal partial class IntervalTree<T> : IEnumerable<T> { public static readonly IntervalTree<T> Empty = new(); protected Node? root; private delegate bool TestInterval<TIntrospector>(T value, int start, int length, in TIntrospector introspector) where TIntrospector : struct, IIntervalIntrospector<T>; private static readonly ObjectPool<Stack<(Node? node, bool firstTime)>> s_stackPool = SharedPools.Default<Stack<(Node? node, bool firstTime)>>(); public IntervalTree() { } public static IntervalTree<T> Create<TIntrospector>(in TIntrospector introspector, IEnumerable<T> values) where TIntrospector : struct, IIntervalIntrospector<T> { var result = new IntervalTree<T>(); foreach (var value in values) { result.root = Insert(result.root, new Node(value), in introspector); } return result; } protected static bool Contains<TIntrospector>(T value, int start, int length, in TIntrospector introspector) where TIntrospector : struct, IIntervalIntrospector<T> { var otherStart = start; var otherEnd = start + length; var thisEnd = GetEnd(value, in introspector); var thisStart = introspector.GetStart(value); // make sure "Contains" test to be same as what TextSpan does if (length == 0) { return thisStart <= otherStart && otherEnd < thisEnd; } return thisStart <= otherStart && otherEnd <= thisEnd; } private static bool IntersectsWith<TIntrospector>(T value, int start, int length, in TIntrospector introspector) where TIntrospector : struct, IIntervalIntrospector<T> { var otherStart = start; var otherEnd = start + length; var thisEnd = GetEnd(value, in introspector); var thisStart = introspector.GetStart(value); return otherStart <= thisEnd && otherEnd >= thisStart; } private static bool OverlapsWith<TIntrospector>(T value, int start, int length, in TIntrospector introspector) where TIntrospector : struct, IIntervalIntrospector<T> { var otherStart = start; var otherEnd = start + length; var thisEnd = GetEnd(value, in introspector); var thisStart = introspector.GetStart(value); if (length == 0) { return thisStart < otherStart && otherStart < thisEnd; } var overlapStart = Math.Max(thisStart, otherStart); var overlapEnd = Math.Min(thisEnd, otherEnd); return overlapStart < overlapEnd; } public ImmutableArray<T> GetIntervalsThatOverlapWith<TIntrospector>(int start, int length, in TIntrospector introspector) where TIntrospector : struct, IIntervalIntrospector<T> => this.GetIntervalsThatMatch(start, length, Tests<TIntrospector>.OverlapsWithTest, in introspector); public ImmutableArray<T> GetIntervalsThatIntersectWith<TIntrospector>(int start, int length, in TIntrospector introspector) where TIntrospector : struct, IIntervalIntrospector<T> => this.GetIntervalsThatMatch(start, length, Tests<TIntrospector>.IntersectsWithTest, in introspector); public ImmutableArray<T> GetIntervalsThatContain<TIntrospector>(int start, int length, in TIntrospector introspector) where TIntrospector : struct, IIntervalIntrospector<T> => this.GetIntervalsThatMatch(start, length, Tests<TIntrospector>.ContainsTest, in introspector); public void FillWithIntervalsThatOverlapWith<TIntrospector>(int start, int length, ref TemporaryArray<T> builder, in TIntrospector introspector) where TIntrospector : struct, IIntervalIntrospector<T> => this.FillWithIntervalsThatMatch(start, length, Tests<TIntrospector>.OverlapsWithTest, ref builder, in introspector, stopAfterFirst: false); public void FillWithIntervalsThatIntersectWith<TIntrospector>(int start, int length, ref TemporaryArray<T> builder, in TIntrospector introspector) where TIntrospector : struct, IIntervalIntrospector<T> => this.FillWithIntervalsThatMatch(start, length, Tests<TIntrospector>.IntersectsWithTest, ref builder, in introspector, stopAfterFirst: false); public void FillWithIntervalsThatContain<TIntrospector>(int start, int length, ref TemporaryArray<T> builder, in TIntrospector introspector) where TIntrospector : struct, IIntervalIntrospector<T> => this.FillWithIntervalsThatMatch(start, length, Tests<TIntrospector>.ContainsTest, ref builder, in introspector, stopAfterFirst: false); public bool HasIntervalThatIntersectsWith<TIntrospector>(int position, in TIntrospector introspector) where TIntrospector : struct, IIntervalIntrospector<T> => HasIntervalThatIntersectsWith(position, 0, in introspector); public bool HasIntervalThatIntersectsWith<TIntrospector>(int start, int length, in TIntrospector introspector) where TIntrospector : struct, IIntervalIntrospector<T> => Any(start, length, Tests<TIntrospector>.IntersectsWithTest, in introspector); public bool HasIntervalThatOverlapsWith<TIntrospector>(int start, int length, in TIntrospector introspector) where TIntrospector : struct, IIntervalIntrospector<T> => Any(start, length, Tests<TIntrospector>.OverlapsWithTest, in introspector); public bool HasIntervalThatContains<TIntrospector>(int start, int length, in TIntrospector introspector) where TIntrospector : struct, IIntervalIntrospector<T> => Any(start, length, Tests<TIntrospector>.ContainsTest, in introspector); private bool Any<TIntrospector>(int start, int length, TestInterval<TIntrospector> testInterval, in TIntrospector introspector) where TIntrospector : struct, IIntervalIntrospector<T> { using var result = TemporaryArray<T>.Empty; var matches = FillWithIntervalsThatMatch(start, length, testInterval, ref result.AsRef(), in introspector, stopAfterFirst: true); return matches > 0; } private ImmutableArray<T> GetIntervalsThatMatch<TIntrospector>( int start, int length, TestInterval<TIntrospector> testInterval, in TIntrospector introspector) where TIntrospector : struct, IIntervalIntrospector<T> { using var result = TemporaryArray<T>.Empty; FillWithIntervalsThatMatch(start, length, testInterval, ref result.AsRef(), in introspector, stopAfterFirst: false); return result.ToImmutableAndClear(); } /// <returns>The number of matching intervals found by the method.</returns> private int FillWithIntervalsThatMatch<TIntrospector>( int start, int length, TestInterval<TIntrospector> testInterval, ref TemporaryArray<T> builder, in TIntrospector introspector, bool stopAfterFirst) where TIntrospector : struct, IIntervalIntrospector<T> { if (root == null) { return 0; } var candidates = s_stackPool.Allocate(); var matches = FillWithIntervalsThatMatch( start, length, testInterval, ref builder, in introspector, stopAfterFirst, candidates); s_stackPool.ClearAndFree(candidates); return matches; } /// <returns>The number of matching intervals found by the method.</returns> private int FillWithIntervalsThatMatch<TIntrospector>( int start, int length, TestInterval<TIntrospector> testInterval, ref TemporaryArray<T> builder, in TIntrospector introspector, bool stopAfterFirst, Stack<(Node? node, bool firstTime)> candidates) where TIntrospector : struct, IIntervalIntrospector<T> { var matches = 0; var end = start + length; candidates.Push((root, firstTime: true)); while (candidates.Count > 0) { var currentTuple = candidates.Pop(); var currentNode = currentTuple.node; RoslynDebug.Assert(currentNode != null); var firstTime = currentTuple.firstTime; if (!firstTime) { // We're seeing this node for the second time (as we walk back up the left // side of it). Now see if it matches our test, and if so return it out. if (testInterval(currentNode.Value, start, length, in introspector)) { matches++; builder.Add(currentNode.Value); if (stopAfterFirst) { return 1; } } } else { // First time we're seeing this node. In order to see the node 'in-order', // we push the right side, then the node again, then the left side. This // time we mark the current node with 'false' to indicate that it's the // second time we're seeing it the next time it comes around. // right children's starts will never be to the left of the parent's start // so we should consider right subtree only if root's start overlaps with // interval's End, if (introspector.GetStart(currentNode.Value) <= end) { var right = currentNode.Right; if (right != null && GetEnd(right.MaxEndNode.Value, in introspector) >= start) { candidates.Push((right, firstTime: true)); } } candidates.Push((currentNode, firstTime: false)); // only if left's maxVal overlaps with interval's start, we should consider // left subtree var left = currentNode.Left; if (left != null && GetEnd(left.MaxEndNode.Value, in introspector) >= start) { candidates.Push((left, firstTime: true)); } } } return matches; } public bool IsEmpty() => this.root == null; protected static Node Insert<TIntrospector>(Node? root, Node newNode, in TIntrospector introspector) where TIntrospector : struct, IIntervalIntrospector<T> { var newNodeStart = introspector.GetStart(newNode.Value); return Insert(root, newNode, newNodeStart, in introspector); } private static Node Insert<TIntrospector>(Node? root, Node newNode, int newNodeStart, in TIntrospector introspector) where TIntrospector : struct, IIntervalIntrospector<T> { if (root == null) { return newNode; } Node? newLeft, newRight; if (newNodeStart < introspector.GetStart(root.Value)) { newLeft = Insert(root.Left, newNode, newNodeStart, in introspector); newRight = root.Right; } else { newLeft = root.Left; newRight = Insert(root.Right, newNode, newNodeStart, in introspector); } root.SetLeftRight(newLeft, newRight, in introspector); var newRoot = root; return Balance(newRoot, in introspector); } private static Node Balance<TIntrospector>(Node node, in TIntrospector introspector) where TIntrospector : struct, IIntervalIntrospector<T> { var balanceFactor = BalanceFactor(node); if (balanceFactor == -2) { var rightBalance = BalanceFactor(node.Right); if (rightBalance == -1) { return node.LeftRotation(in introspector); } else { Debug.Assert(rightBalance == 1); return node.InnerRightOuterLeftRotation(in introspector); } } else if (balanceFactor == 2) { var leftBalance = BalanceFactor(node.Left); if (leftBalance == 1) { return node.RightRotation(in introspector); } else { Debug.Assert(leftBalance == -1); return node.InnerLeftOuterRightRotation(in introspector); } } return node; } public IEnumerator<T> GetEnumerator() { if (root == null) { yield break; } var candidates = new Stack<(Node? node, bool firstTime)>(); candidates.Push((root, firstTime: true)); while (candidates.Count != 0) { var (currentNode, firstTime) = candidates.Pop(); if (currentNode != null) { if (firstTime) { // First time seeing this node. Mark that we've been seen and recurse // down the left side. The next time we see this node we'll yield it // out. candidates.Push((currentNode.Right, firstTime: true)); candidates.Push((currentNode, firstTime: false)); candidates.Push((currentNode.Left, firstTime: true)); } else { yield return currentNode.Value; } } } } IEnumerator IEnumerable.GetEnumerator() => this.GetEnumerator(); protected static int GetEnd<TIntrospector>(T value, in TIntrospector introspector) where TIntrospector : struct, IIntervalIntrospector<T> => introspector.GetStart(value) + introspector.GetLength(value); protected static int MaxEndValue<TIntrospector>(Node? node, in TIntrospector introspector) where TIntrospector : struct, IIntervalIntrospector<T> => node == null ? 0 : GetEnd(node.MaxEndNode.Value, in introspector); private static int Height(Node? node) => node == null ? 0 : node.Height; private static int BalanceFactor(Node? node) => node == null ? 0 : Height(node.Left) - Height(node.Right); private static class Tests<TIntrospector> where TIntrospector : struct, IIntervalIntrospector<T> { public static readonly TestInterval<TIntrospector> IntersectsWithTest = IntersectsWith; public static readonly TestInterval<TIntrospector> ContainsTest = Contains; public static readonly TestInterval<TIntrospector> OverlapsWithTest = OverlapsWith; } } }
-1
dotnet/roslyn
55,428
Test adding nested namespaces
Fixes https://github.com/dotnet/roslyn/issues/54939 The "workaround" that's already implemented is actually the correct behavior.
tmat
2021-08-05T01:19:03Z
2021-08-11T18:38:54Z
bc874ebc5111a2a33221409f895953b1536f6612
1cbbd423e17b186a8f1de89febb4db9a386d180d
Test adding nested namespaces. Fixes https://github.com/dotnet/roslyn/issues/54939 The "workaround" that's already implemented is actually the correct behavior.
./src/Features/CSharp/Portable/RemoveAsyncModifier/CSharpRemoveAsyncModifierCodeFixProvider.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Immutable; using System.Composition; using System.Diagnostics.CodeAnalysis; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.MakeMethodSynchronous; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.RemoveAsyncModifier; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.RemoveAsyncModifier { [ExportCodeFixProvider(LanguageNames.CSharp, Name = PredefinedCodeFixProviderNames.RemoveAsyncModifier), Shared] [ExtensionOrder(After = PredefinedCodeFixProviderNames.MakeMethodSynchronous)] internal partial class CSharpRemoveAsyncModifierCodeFixProvider : AbstractRemoveAsyncModifierCodeFixProvider<ReturnStatementSyntax, ExpressionSyntax> { private const string CS1998 = nameof(CS1998); // This async method lacks 'await' operators and will run synchronously. [ImportingConstructor] [SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification = "Used in test code: https://github.com/dotnet/roslyn/issues/42814")] public CSharpRemoveAsyncModifierCodeFixProvider() { } public override ImmutableArray<string> FixableDiagnosticIds { get; } = ImmutableArray.Create(CS1998); protected override bool IsAsyncSupportingFunctionSyntax(SyntaxNode node) => node.IsAsyncSupportingFunctionSyntax(); protected override SyntaxNode? ConvertToBlockBody(SyntaxNode node, ExpressionSyntax expressionBody) { var semicolonToken = SyntaxFactory.Token(SyntaxKind.SemicolonToken); if (expressionBody.TryConvertToStatement(semicolonToken, createReturnStatementForExpression: false, out var statement)) { var block = SyntaxFactory.Block(statement); return node switch { MethodDeclarationSyntax method => method.WithBody(block).WithExpressionBody(null).WithSemicolonToken(default), LocalFunctionStatementSyntax localFunction => localFunction.WithBody(block).WithExpressionBody(null).WithSemicolonToken(default), AnonymousFunctionExpressionSyntax anonymousFunction => anonymousFunction.WithBody(block).WithExpressionBody(null), _ => throw ExceptionUtilities.Unreachable }; } return null; } protected override SyntaxNode RemoveAsyncModifier(SyntaxGenerator generator, SyntaxNode methodLikeNode) => methodLikeNode switch { MethodDeclarationSyntax method => RemoveAsyncModifierHelpers.WithoutAsyncModifier(method, method.ReturnType), LocalFunctionStatementSyntax localFunction => RemoveAsyncModifierHelpers.WithoutAsyncModifier(localFunction, localFunction.ReturnType), AnonymousMethodExpressionSyntax method => AnnotateBlock(generator, RemoveAsyncModifierHelpers.WithoutAsyncModifier(method)), ParenthesizedLambdaExpressionSyntax lambda => AnnotateBlock(generator, RemoveAsyncModifierHelpers.WithoutAsyncModifier(lambda)), SimpleLambdaExpressionSyntax lambda => AnnotateBlock(generator, RemoveAsyncModifierHelpers.WithoutAsyncModifier(lambda)), _ => methodLikeNode, }; // Block bodied lambdas and anonymous methods need to be formatted after changing their modifiers, or their indentation is broken private static SyntaxNode AnnotateBlock(SyntaxGenerator generator, SyntaxNode node) => generator.GetExpression(node) == null ? node.WithAdditionalAnnotations(Formatter.Annotation) : node; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Immutable; using System.Composition; using System.Diagnostics.CodeAnalysis; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.MakeMethodSynchronous; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.RemoveAsyncModifier; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.RemoveAsyncModifier { [ExportCodeFixProvider(LanguageNames.CSharp, Name = PredefinedCodeFixProviderNames.RemoveAsyncModifier), Shared] [ExtensionOrder(After = PredefinedCodeFixProviderNames.MakeMethodSynchronous)] internal partial class CSharpRemoveAsyncModifierCodeFixProvider : AbstractRemoveAsyncModifierCodeFixProvider<ReturnStatementSyntax, ExpressionSyntax> { private const string CS1998 = nameof(CS1998); // This async method lacks 'await' operators and will run synchronously. [ImportingConstructor] [SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification = "Used in test code: https://github.com/dotnet/roslyn/issues/42814")] public CSharpRemoveAsyncModifierCodeFixProvider() { } public override ImmutableArray<string> FixableDiagnosticIds { get; } = ImmutableArray.Create(CS1998); protected override bool IsAsyncSupportingFunctionSyntax(SyntaxNode node) => node.IsAsyncSupportingFunctionSyntax(); protected override SyntaxNode? ConvertToBlockBody(SyntaxNode node, ExpressionSyntax expressionBody) { var semicolonToken = SyntaxFactory.Token(SyntaxKind.SemicolonToken); if (expressionBody.TryConvertToStatement(semicolonToken, createReturnStatementForExpression: false, out var statement)) { var block = SyntaxFactory.Block(statement); return node switch { MethodDeclarationSyntax method => method.WithBody(block).WithExpressionBody(null).WithSemicolonToken(default), LocalFunctionStatementSyntax localFunction => localFunction.WithBody(block).WithExpressionBody(null).WithSemicolonToken(default), AnonymousFunctionExpressionSyntax anonymousFunction => anonymousFunction.WithBody(block).WithExpressionBody(null), _ => throw ExceptionUtilities.Unreachable }; } return null; } protected override SyntaxNode RemoveAsyncModifier(SyntaxGenerator generator, SyntaxNode methodLikeNode) => methodLikeNode switch { MethodDeclarationSyntax method => RemoveAsyncModifierHelpers.WithoutAsyncModifier(method, method.ReturnType), LocalFunctionStatementSyntax localFunction => RemoveAsyncModifierHelpers.WithoutAsyncModifier(localFunction, localFunction.ReturnType), AnonymousMethodExpressionSyntax method => AnnotateBlock(generator, RemoveAsyncModifierHelpers.WithoutAsyncModifier(method)), ParenthesizedLambdaExpressionSyntax lambda => AnnotateBlock(generator, RemoveAsyncModifierHelpers.WithoutAsyncModifier(lambda)), SimpleLambdaExpressionSyntax lambda => AnnotateBlock(generator, RemoveAsyncModifierHelpers.WithoutAsyncModifier(lambda)), _ => methodLikeNode, }; // Block bodied lambdas and anonymous methods need to be formatted after changing their modifiers, or their indentation is broken private static SyntaxNode AnnotateBlock(SyntaxGenerator generator, SyntaxNode node) => generator.GetExpression(node) == null ? node.WithAdditionalAnnotations(Formatter.Annotation) : node; } }
-1
dotnet/roslyn
55,428
Test adding nested namespaces
Fixes https://github.com/dotnet/roslyn/issues/54939 The "workaround" that's already implemented is actually the correct behavior.
tmat
2021-08-05T01:19:03Z
2021-08-11T18:38:54Z
bc874ebc5111a2a33221409f895953b1536f6612
1cbbd423e17b186a8f1de89febb4db9a386d180d
Test adding nested namespaces. Fixes https://github.com/dotnet/roslyn/issues/54939 The "workaround" that's already implemented is actually the correct behavior.
./src/Compilers/VisualBasic/Portable/Semantics/TypeInference/RequiredConversion.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic Friend Enum RequiredConversion ' "ConversionRequired" in Dev10 compiler '// When we do type inference, we have to unify the types supplied and infer generic parameters. '// e.g. if we have Sub f(ByVal x as T(), ByVal y as T) and invoke it with x=AnimalArray, y=Mammal, '// then we have to figure out that T should be an Animal. The way that's done: '// (1) All the requirements on T are gathered together, e.g. '// T:{Mammal+vb, Animal+arr} means '// (+vb) "T is something such that argument Mammal can be supplied to parameter T" '// (+arr) "T is something such that argument Animal() can be supplied to parameter T()" '// (2) We'll go through each candidate type to see if they work. First T=Mammal. Does it work for each requirement? '// (+vb) Yes, argument Mammal can be supplied to parameter Mammal through identity '// (+arr) Sort-of, argument Animal() can be supplied to parameter Mammal() only through narrowing '// (3) Now try the next candidate, T=Animal. Does it work for each requirement? '// (+vb) Yes, argument Mammal can be supplied to parameter Animal through widening '// (+arr) Yes, argument Animal() can be supplied to parameter Animal() through identity '// (4) At the end, we pick out the one that worked "best". In this case T=Animal worked best. '// The criteria for "best" are documented and implemented in ConversionResolution.cpp/FindDominantType. '// This enumeration contains the different kinds of requirements... '// Each requirement is that some X->Y be a conversion. Inside FindDominantType we will grade each candidate '// on whether it could satisfy that requirement with an Identity, a Widening, a Narrowing, or not at all. '// Identity: '// This restriction requires that req->candidate be an identity conversion according to the CLR. '// e.g. supplying "New List(Of Mammal)" to parameter "List(Of T)", we require that Mammal->T be identity '// e.g. supplying "New List(Of Mammal)" to a parameter "List(Of T)" we require that Mammal->T be identity '// e.g. supplying "Dim ml as ICovariant(Of Mammal) = Nothing" to a parameter "*ByRef* ICovariant(Of T)" we require that Mammal->T be identity '// (but for non-ByRef covariance see "ReferenceConversion" below.) '// Note that CLR does not include lambda->delegate, and doesn't include user-defined conversions. Identity '// Any: '// This restriction requires that req->candidate be a conversion according to VB. '// e.g. supplying "New Mammal" to parameter "T", we require that Mammal->T be a VB conversion '// It includes user-defined conversions and all the VB-specific conversions. Any '// AnyReverse: '// This restriction requires that candidate->req be a conversion according to VB. '// It might hypothetically be used for "out" parameters if VB ever gets them: '// e.g. supplying "Dim m as Mammal" to parameter "Out T" we require that T->Mammal be a VB conversion. '// But the actual reason it's included now is as be a symmetric form of AnyConversion: '// this simplifies the implementation of InvertConversionRequirement and CombineConversionRequirements AnyReverse '// AnyAndReverse: '// This restriction requires that req->candidate and candidate->hint be conversions according to VB. '// e.g. supplying "Dim m as New Mammal" to "ByRef T", we require that Mammal->T be a conversion, and also T->Mammal for the copyback. '// Again, each direction includes user-defined conversions and all the VB-specific conversions. AnyAndReverse '// ArrayElement: '// This restriction requires that req->candidate be a array element conversion. '// e.g. supplying "new Mammal(){}" to "ByVal T()", we require that Mammal->T be an array-element-conversion. '// It consists of the subset of CLR-array-element-conversions that are also allowed by VB. '// Note: ArrayElementConversion gives us array covariance, and also by enum()->underlying_integral(). ArrayElement '// Reference: '// This restriction requires that req->candidate be a reference conversion. '// e.g. supplying "Dim x as ICovariant(Of Mammal)" to "ICovariant(Of T)", we require that Mammal->T be a reference conversion. '// It consists of the subset of CLR-reference-conversions that are also allowed by VB. Reference '// ReverseReference: '// This restriction requires that candidate->req be a reference conversion. '// e.g. supplying "Dim x as IContravariant(Of Animal)" to "IContravariant(Of T)", we require that T->Animal be a reference conversion. '// Note that just because T->U is a widening reference conversion, it doesn't mean that U->T is narrowing, nor vice versa. '// Again it consists of the subset of CLR-reference-conversions that are also allowed by VB. ReverseReference '// None: '// This is not a restriction. It allows for the candidate to have any relation, even be completely unrelated, '// to the hint type. It is used as a way of feeding in candidate suggestions into the algorithm, but leaving '// them purely as suggestions, without any requirement to be satisfied. (e.g. you might add the restriction '// that there be a conversion from some literal "1L", and add the type hint "Long", so that Long can be used '// as a candidate but it's not required. This is used in computing the dominant type of an array literal.) None '// These restrictions form a partial order composed of three chains: from less strict to more strict, we have: '// [reverse chain] [None] < AnyReverse < ReverseReference < Identity '// [middle chain] None < [Any,AnyReverse] < AnyConversionAndReverse < Identity '// [forward chain] [None] < Any < ArrayElement < Reference < Identity '// '// = KEY: '// / | \ = Identity '// / | \ +r Reference '// -r | +r -r ReverseReference '// | +-any | +-any AnyConversionAndReverse '// | /|\ +arr +arr ArrayElement '// | / | \ | +any Any '// -any | +any -any AnyReverse '// \ | / none None '// \ | / '// none '// '// The routine "CombineConversionRequirements" finds the least upper bound of two elements. '// The routine "StrengthenConversionRequirementToReference" walks up the current chain to a reference conversion. '// The routine "InvertConversionRequirement" switches from reverse chain to forwards chain or vice versa, '// and asserts if given ArrayElementConversion since this has no counterparts in the reverse chain. '// These three routines are called by InferTypeArgumentsFromArgumentDirectly, as it matches an '// argument type against a parameter. '// The routine "CheckHintSatisfaction" is what actually implements the satisfaction-of-restriction check. '// '// If you make any changes to this enum or the partial order, you'll have to change all the above functions. '// They do "VSASSERT(Count==8)" to help remind you to change them, should you make any additions to this enum. Count End Enum End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic Friend Enum RequiredConversion ' "ConversionRequired" in Dev10 compiler '// When we do type inference, we have to unify the types supplied and infer generic parameters. '// e.g. if we have Sub f(ByVal x as T(), ByVal y as T) and invoke it with x=AnimalArray, y=Mammal, '// then we have to figure out that T should be an Animal. The way that's done: '// (1) All the requirements on T are gathered together, e.g. '// T:{Mammal+vb, Animal+arr} means '// (+vb) "T is something such that argument Mammal can be supplied to parameter T" '// (+arr) "T is something such that argument Animal() can be supplied to parameter T()" '// (2) We'll go through each candidate type to see if they work. First T=Mammal. Does it work for each requirement? '// (+vb) Yes, argument Mammal can be supplied to parameter Mammal through identity '// (+arr) Sort-of, argument Animal() can be supplied to parameter Mammal() only through narrowing '// (3) Now try the next candidate, T=Animal. Does it work for each requirement? '// (+vb) Yes, argument Mammal can be supplied to parameter Animal through widening '// (+arr) Yes, argument Animal() can be supplied to parameter Animal() through identity '// (4) At the end, we pick out the one that worked "best". In this case T=Animal worked best. '// The criteria for "best" are documented and implemented in ConversionResolution.cpp/FindDominantType. '// This enumeration contains the different kinds of requirements... '// Each requirement is that some X->Y be a conversion. Inside FindDominantType we will grade each candidate '// on whether it could satisfy that requirement with an Identity, a Widening, a Narrowing, or not at all. '// Identity: '// This restriction requires that req->candidate be an identity conversion according to the CLR. '// e.g. supplying "New List(Of Mammal)" to parameter "List(Of T)", we require that Mammal->T be identity '// e.g. supplying "New List(Of Mammal)" to a parameter "List(Of T)" we require that Mammal->T be identity '// e.g. supplying "Dim ml as ICovariant(Of Mammal) = Nothing" to a parameter "*ByRef* ICovariant(Of T)" we require that Mammal->T be identity '// (but for non-ByRef covariance see "ReferenceConversion" below.) '// Note that CLR does not include lambda->delegate, and doesn't include user-defined conversions. Identity '// Any: '// This restriction requires that req->candidate be a conversion according to VB. '// e.g. supplying "New Mammal" to parameter "T", we require that Mammal->T be a VB conversion '// It includes user-defined conversions and all the VB-specific conversions. Any '// AnyReverse: '// This restriction requires that candidate->req be a conversion according to VB. '// It might hypothetically be used for "out" parameters if VB ever gets them: '// e.g. supplying "Dim m as Mammal" to parameter "Out T" we require that T->Mammal be a VB conversion. '// But the actual reason it's included now is as be a symmetric form of AnyConversion: '// this simplifies the implementation of InvertConversionRequirement and CombineConversionRequirements AnyReverse '// AnyAndReverse: '// This restriction requires that req->candidate and candidate->hint be conversions according to VB. '// e.g. supplying "Dim m as New Mammal" to "ByRef T", we require that Mammal->T be a conversion, and also T->Mammal for the copyback. '// Again, each direction includes user-defined conversions and all the VB-specific conversions. AnyAndReverse '// ArrayElement: '// This restriction requires that req->candidate be a array element conversion. '// e.g. supplying "new Mammal(){}" to "ByVal T()", we require that Mammal->T be an array-element-conversion. '// It consists of the subset of CLR-array-element-conversions that are also allowed by VB. '// Note: ArrayElementConversion gives us array covariance, and also by enum()->underlying_integral(). ArrayElement '// Reference: '// This restriction requires that req->candidate be a reference conversion. '// e.g. supplying "Dim x as ICovariant(Of Mammal)" to "ICovariant(Of T)", we require that Mammal->T be a reference conversion. '// It consists of the subset of CLR-reference-conversions that are also allowed by VB. Reference '// ReverseReference: '// This restriction requires that candidate->req be a reference conversion. '// e.g. supplying "Dim x as IContravariant(Of Animal)" to "IContravariant(Of T)", we require that T->Animal be a reference conversion. '// Note that just because T->U is a widening reference conversion, it doesn't mean that U->T is narrowing, nor vice versa. '// Again it consists of the subset of CLR-reference-conversions that are also allowed by VB. ReverseReference '// None: '// This is not a restriction. It allows for the candidate to have any relation, even be completely unrelated, '// to the hint type. It is used as a way of feeding in candidate suggestions into the algorithm, but leaving '// them purely as suggestions, without any requirement to be satisfied. (e.g. you might add the restriction '// that there be a conversion from some literal "1L", and add the type hint "Long", so that Long can be used '// as a candidate but it's not required. This is used in computing the dominant type of an array literal.) None '// These restrictions form a partial order composed of three chains: from less strict to more strict, we have: '// [reverse chain] [None] < AnyReverse < ReverseReference < Identity '// [middle chain] None < [Any,AnyReverse] < AnyConversionAndReverse < Identity '// [forward chain] [None] < Any < ArrayElement < Reference < Identity '// '// = KEY: '// / | \ = Identity '// / | \ +r Reference '// -r | +r -r ReverseReference '// | +-any | +-any AnyConversionAndReverse '// | /|\ +arr +arr ArrayElement '// | / | \ | +any Any '// -any | +any -any AnyReverse '// \ | / none None '// \ | / '// none '// '// The routine "CombineConversionRequirements" finds the least upper bound of two elements. '// The routine "StrengthenConversionRequirementToReference" walks up the current chain to a reference conversion. '// The routine "InvertConversionRequirement" switches from reverse chain to forwards chain or vice versa, '// and asserts if given ArrayElementConversion since this has no counterparts in the reverse chain. '// These three routines are called by InferTypeArgumentsFromArgumentDirectly, as it matches an '// argument type against a parameter. '// The routine "CheckHintSatisfaction" is what actually implements the satisfaction-of-restriction check. '// '// If you make any changes to this enum or the partial order, you'll have to change all the above functions. '// They do "VSASSERT(Count==8)" to help remind you to change them, should you make any additions to this enum. Count End Enum End Namespace
-1
dotnet/roslyn
55,428
Test adding nested namespaces
Fixes https://github.com/dotnet/roslyn/issues/54939 The "workaround" that's already implemented is actually the correct behavior.
tmat
2021-08-05T01:19:03Z
2021-08-11T18:38:54Z
bc874ebc5111a2a33221409f895953b1536f6612
1cbbd423e17b186a8f1de89febb4db9a386d180d
Test adding nested namespaces. Fixes https://github.com/dotnet/roslyn/issues/54939 The "workaround" that's already implemented is actually the correct behavior.
./src/Workspaces/Core/Portable/FindSymbols/FindReferences/MetadataUnifyingEquivalenceComparer.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Generic; using System.Linq; using Microsoft.CodeAnalysis.Shared.Utilities; namespace Microsoft.CodeAnalysis.FindSymbols { internal sealed class MetadataUnifyingEquivalenceComparer : IEqualityComparer<ISymbol> { public static readonly IEqualityComparer<ISymbol> Instance = new MetadataUnifyingEquivalenceComparer(); private MetadataUnifyingEquivalenceComparer() { } public bool Equals(ISymbol x, ISymbol y) { // If either symbol is from source, then we must do stricter equality. Consider this: // // S1 <-> M <-> S2 (where S# = source symbol, M = some metadata symbol) // // In this case, imagine that both the comparisons denoted by <-> were done with the // SymbolEquivalenceComparer, and returned true. If S1 and S2 were from different projects, // they would compare false but transitivity would say they must be true. Another way to think // of this is any use of a source symbol "poisons" the comparison and requires it to be stricter. if (x == null || y == null || IsInSource(x) || IsInSource(y)) { return object.Equals(x, y); } // Both of the symbols are from metadata, so defer to the equivalence comparer return SymbolEquivalenceComparer.Instance.Equals(x, y); } public int GetHashCode(ISymbol obj) { if (IsInSource(obj)) { return obj.GetHashCode(); } else { return SymbolEquivalenceComparer.Instance.GetHashCode(obj); } } private static bool IsInSource(ISymbol symbol) => symbol.Locations.Any(l => l.IsInSource); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Generic; using System.Linq; using Microsoft.CodeAnalysis.Shared.Utilities; namespace Microsoft.CodeAnalysis.FindSymbols { internal sealed class MetadataUnifyingEquivalenceComparer : IEqualityComparer<ISymbol> { public static readonly IEqualityComparer<ISymbol> Instance = new MetadataUnifyingEquivalenceComparer(); private MetadataUnifyingEquivalenceComparer() { } public bool Equals(ISymbol x, ISymbol y) { // If either symbol is from source, then we must do stricter equality. Consider this: // // S1 <-> M <-> S2 (where S# = source symbol, M = some metadata symbol) // // In this case, imagine that both the comparisons denoted by <-> were done with the // SymbolEquivalenceComparer, and returned true. If S1 and S2 were from different projects, // they would compare false but transitivity would say they must be true. Another way to think // of this is any use of a source symbol "poisons" the comparison and requires it to be stricter. if (x == null || y == null || IsInSource(x) || IsInSource(y)) { return object.Equals(x, y); } // Both of the symbols are from metadata, so defer to the equivalence comparer return SymbolEquivalenceComparer.Instance.Equals(x, y); } public int GetHashCode(ISymbol obj) { if (IsInSource(obj)) { return obj.GetHashCode(); } else { return SymbolEquivalenceComparer.Instance.GetHashCode(obj); } } private static bool IsInSource(ISymbol symbol) => symbol.Locations.Any(l => l.IsInSource); } }
-1
dotnet/roslyn
55,428
Test adding nested namespaces
Fixes https://github.com/dotnet/roslyn/issues/54939 The "workaround" that's already implemented is actually the correct behavior.
tmat
2021-08-05T01:19:03Z
2021-08-11T18:38:54Z
bc874ebc5111a2a33221409f895953b1536f6612
1cbbd423e17b186a8f1de89febb4db9a386d180d
Test adding nested namespaces. Fixes https://github.com/dotnet/roslyn/issues/54939 The "workaround" that's already implemented is actually the correct behavior.
./src/Workspaces/Core/Portable/FindSymbols/FindReferences/Finders/EventSymbolReferenceFinder.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Immutable; using System.Linq; using System.Threading; using System.Threading.Tasks; namespace Microsoft.CodeAnalysis.FindSymbols.Finders { internal class EventSymbolReferenceFinder : AbstractMethodOrPropertyOrEventSymbolReferenceFinder<IEventSymbol> { protected override bool CanFind(IEventSymbol symbol) => true; protected override Task<ImmutableArray<ISymbol>> DetermineCascadedSymbolsAsync( IEventSymbol symbol, Solution solution, FindReferencesSearchOptions options, CancellationToken cancellationToken) { var backingFields = symbol.ContainingType.GetMembers() .OfType<IFieldSymbol>() .Where(f => symbol.Equals(f.AssociatedSymbol)) .ToImmutableArray<ISymbol>(); var associatedNamedTypes = symbol.ContainingType.GetTypeMembers() .WhereAsArray(n => symbol.Equals(n.AssociatedSymbol)) .CastArray<ISymbol>(); return Task.FromResult(backingFields.Concat(associatedNamedTypes)); } protected override async Task<ImmutableArray<Document>> DetermineDocumentsToSearchAsync( IEventSymbol symbol, Project project, IImmutableSet<Document>? documents, FindReferencesSearchOptions options, CancellationToken cancellationToken) { var documentsWithName = await FindDocumentsAsync(project, documents, cancellationToken, symbol.Name).ConfigureAwait(false); var documentsWithGlobalAttributes = await FindDocumentsWithGlobalAttributesAsync(project, documents, cancellationToken).ConfigureAwait(false); return documentsWithName.Concat(documentsWithGlobalAttributes); } protected override ValueTask<ImmutableArray<FinderLocation>> FindReferencesInDocumentAsync( IEventSymbol symbol, Document document, SemanticModel semanticModel, FindReferencesSearchOptions options, CancellationToken cancellationToken) { return FindReferencesInDocumentUsingSymbolNameAsync(symbol, document, semanticModel, 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.Linq; using System.Threading; using System.Threading.Tasks; namespace Microsoft.CodeAnalysis.FindSymbols.Finders { internal class EventSymbolReferenceFinder : AbstractMethodOrPropertyOrEventSymbolReferenceFinder<IEventSymbol> { protected override bool CanFind(IEventSymbol symbol) => true; protected override Task<ImmutableArray<ISymbol>> DetermineCascadedSymbolsAsync( IEventSymbol symbol, Solution solution, FindReferencesSearchOptions options, CancellationToken cancellationToken) { var backingFields = symbol.ContainingType.GetMembers() .OfType<IFieldSymbol>() .Where(f => symbol.Equals(f.AssociatedSymbol)) .ToImmutableArray<ISymbol>(); var associatedNamedTypes = symbol.ContainingType.GetTypeMembers() .WhereAsArray(n => symbol.Equals(n.AssociatedSymbol)) .CastArray<ISymbol>(); return Task.FromResult(backingFields.Concat(associatedNamedTypes)); } protected override async Task<ImmutableArray<Document>> DetermineDocumentsToSearchAsync( IEventSymbol symbol, Project project, IImmutableSet<Document>? documents, FindReferencesSearchOptions options, CancellationToken cancellationToken) { var documentsWithName = await FindDocumentsAsync(project, documents, cancellationToken, symbol.Name).ConfigureAwait(false); var documentsWithGlobalAttributes = await FindDocumentsWithGlobalAttributesAsync(project, documents, cancellationToken).ConfigureAwait(false); return documentsWithName.Concat(documentsWithGlobalAttributes); } protected override ValueTask<ImmutableArray<FinderLocation>> FindReferencesInDocumentAsync( IEventSymbol symbol, Document document, SemanticModel semanticModel, FindReferencesSearchOptions options, CancellationToken cancellationToken) { return FindReferencesInDocumentUsingSymbolNameAsync(symbol, document, semanticModel, cancellationToken); } } }
-1
dotnet/roslyn
55,428
Test adding nested namespaces
Fixes https://github.com/dotnet/roslyn/issues/54939 The "workaround" that's already implemented is actually the correct behavior.
tmat
2021-08-05T01:19:03Z
2021-08-11T18:38:54Z
bc874ebc5111a2a33221409f895953b1536f6612
1cbbd423e17b186a8f1de89febb4db9a386d180d
Test adding nested namespaces. Fixes https://github.com/dotnet/roslyn/issues/54939 The "workaround" that's already implemented is actually the correct behavior.
./src/VisualStudio/Core/Test/ProjectSystemShim/VisualStudioProjectTests/PrimaryProjectTests.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Threading Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.VisualStudio.LanguageServices.UnitTests.ProjectSystemShim.Framework Imports Roslyn.Test.Utilities Namespace Microsoft.VisualStudio.LanguageServices.UnitTests.ProjectSystemShim <[UseExportProvider]> Public Class PrimaryProjectTests <WpfFact> Public Async Function ProjectIsPrimaryByDefault() As Task Using environment = New TestEnvironment(GetType(TestDynamicFileInfoProviderThatProducesNoFiles)) Dim project = Await environment.ProjectFactory.CreateAndAddToWorkspaceAsync( "project", LanguageNames.CSharp, CancellationToken.None) Assert.True(project.IsPrimary) End Using End Function <WpfFact> Public Async Function ChangeProjectIsPrimary() As Task Using environment = New TestEnvironment(GetType(TestDynamicFileInfoProviderThatProducesNoFiles)) Dim project = Await environment.ProjectFactory.CreateAndAddToWorkspaceAsync( "project", LanguageNames.CSharp, CancellationToken.None) project.IsPrimary = False Assert.False(project.IsPrimary) End Using End Function <WpfFact> Public Async Function ChangeProjectIsPrimaryBack() As Task Using environment = New TestEnvironment(GetType(TestDynamicFileInfoProviderThatProducesNoFiles)) Dim project = Await environment.ProjectFactory.CreateAndAddToWorkspaceAsync( "project", LanguageNames.CSharp, CancellationToken.None) project.IsPrimary = False project.IsPrimary = True Assert.True(project.IsPrimary) End Using End Function End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Threading Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.VisualStudio.LanguageServices.UnitTests.ProjectSystemShim.Framework Imports Roslyn.Test.Utilities Namespace Microsoft.VisualStudio.LanguageServices.UnitTests.ProjectSystemShim <[UseExportProvider]> Public Class PrimaryProjectTests <WpfFact> Public Async Function ProjectIsPrimaryByDefault() As Task Using environment = New TestEnvironment(GetType(TestDynamicFileInfoProviderThatProducesNoFiles)) Dim project = Await environment.ProjectFactory.CreateAndAddToWorkspaceAsync( "project", LanguageNames.CSharp, CancellationToken.None) Assert.True(project.IsPrimary) End Using End Function <WpfFact> Public Async Function ChangeProjectIsPrimary() As Task Using environment = New TestEnvironment(GetType(TestDynamicFileInfoProviderThatProducesNoFiles)) Dim project = Await environment.ProjectFactory.CreateAndAddToWorkspaceAsync( "project", LanguageNames.CSharp, CancellationToken.None) project.IsPrimary = False Assert.False(project.IsPrimary) End Using End Function <WpfFact> Public Async Function ChangeProjectIsPrimaryBack() As Task Using environment = New TestEnvironment(GetType(TestDynamicFileInfoProviderThatProducesNoFiles)) Dim project = Await environment.ProjectFactory.CreateAndAddToWorkspaceAsync( "project", LanguageNames.CSharp, CancellationToken.None) project.IsPrimary = False project.IsPrimary = True Assert.True(project.IsPrimary) End Using End Function End Class End Namespace
-1
dotnet/roslyn
55,428
Test adding nested namespaces
Fixes https://github.com/dotnet/roslyn/issues/54939 The "workaround" that's already implemented is actually the correct behavior.
tmat
2021-08-05T01:19:03Z
2021-08-11T18:38:54Z
bc874ebc5111a2a33221409f895953b1536f6612
1cbbd423e17b186a8f1de89febb4db9a386d180d
Test adding nested namespaces. Fixes https://github.com/dotnet/roslyn/issues/54939 The "workaround" that's already implemented is actually the correct behavior.
./src/Compilers/Core/Portable/Syntax/SyntaxList.cs
// Licensed to the .NET Foundation under one or more agreements. // 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 abstract partial class SyntaxList : SyntaxNode { internal SyntaxList(InternalSyntax.SyntaxList green, SyntaxNode? parent, int position) : base(green, parent, position) { } public override string Language { get { throw ExceptionUtilities.Unreachable; } } // https://github.com/dotnet/roslyn/issues/40733 protected override SyntaxTree SyntaxTreeCore => this.Parent!.SyntaxTree; protected internal override SyntaxNode ReplaceCore<TNode>(IEnumerable<TNode>? nodes = null, Func<TNode, TNode, SyntaxNode>? computeReplacementNode = null, IEnumerable<SyntaxToken>? tokens = null, Func<SyntaxToken, SyntaxToken, SyntaxToken>? computeReplacementToken = null, IEnumerable<SyntaxTrivia>? trivia = null, Func<SyntaxTrivia, SyntaxTrivia, SyntaxTrivia>? computeReplacementTrivia = null) { throw ExceptionUtilities.Unreachable; } protected internal override SyntaxNode ReplaceNodeInListCore(SyntaxNode originalNode, IEnumerable<SyntaxNode> replacementNodes) { throw ExceptionUtilities.Unreachable; } protected internal override SyntaxNode InsertNodesInListCore(SyntaxNode nodeInList, IEnumerable<SyntaxNode> nodesToInsert, bool insertBefore) { throw ExceptionUtilities.Unreachable; } protected internal override SyntaxNode ReplaceTokenInListCore(SyntaxToken originalToken, IEnumerable<SyntaxToken> newTokens) { throw ExceptionUtilities.Unreachable; } protected internal override SyntaxNode InsertTokensInListCore(SyntaxToken originalToken, IEnumerable<SyntaxToken> newTokens, bool insertBefore) { throw ExceptionUtilities.Unreachable; } protected internal override SyntaxNode ReplaceTriviaInListCore(SyntaxTrivia originalTrivia, IEnumerable<SyntaxTrivia> newTrivia) { throw ExceptionUtilities.Unreachable; } protected internal override SyntaxNode InsertTriviaInListCore(SyntaxTrivia originalTrivia, IEnumerable<SyntaxTrivia> newTrivia, bool insertBefore) { throw ExceptionUtilities.Unreachable; } protected internal override SyntaxNode RemoveNodesCore(IEnumerable<SyntaxNode> nodes, SyntaxRemoveOptions options) { throw ExceptionUtilities.Unreachable; } protected internal override SyntaxNode NormalizeWhitespaceCore(string indentation, string eol, bool elasticTrivia) { throw ExceptionUtilities.Unreachable; } protected override bool IsEquivalentToCore(SyntaxNode node, bool topLevel = false) { throw ExceptionUtilities.Unreachable; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Syntax { internal abstract partial class SyntaxList : SyntaxNode { internal SyntaxList(InternalSyntax.SyntaxList green, SyntaxNode? parent, int position) : base(green, parent, position) { } public override string Language { get { throw ExceptionUtilities.Unreachable; } } // https://github.com/dotnet/roslyn/issues/40733 protected override SyntaxTree SyntaxTreeCore => this.Parent!.SyntaxTree; protected internal override SyntaxNode ReplaceCore<TNode>(IEnumerable<TNode>? nodes = null, Func<TNode, TNode, SyntaxNode>? computeReplacementNode = null, IEnumerable<SyntaxToken>? tokens = null, Func<SyntaxToken, SyntaxToken, SyntaxToken>? computeReplacementToken = null, IEnumerable<SyntaxTrivia>? trivia = null, Func<SyntaxTrivia, SyntaxTrivia, SyntaxTrivia>? computeReplacementTrivia = null) { throw ExceptionUtilities.Unreachable; } protected internal override SyntaxNode ReplaceNodeInListCore(SyntaxNode originalNode, IEnumerable<SyntaxNode> replacementNodes) { throw ExceptionUtilities.Unreachable; } protected internal override SyntaxNode InsertNodesInListCore(SyntaxNode nodeInList, IEnumerable<SyntaxNode> nodesToInsert, bool insertBefore) { throw ExceptionUtilities.Unreachable; } protected internal override SyntaxNode ReplaceTokenInListCore(SyntaxToken originalToken, IEnumerable<SyntaxToken> newTokens) { throw ExceptionUtilities.Unreachable; } protected internal override SyntaxNode InsertTokensInListCore(SyntaxToken originalToken, IEnumerable<SyntaxToken> newTokens, bool insertBefore) { throw ExceptionUtilities.Unreachable; } protected internal override SyntaxNode ReplaceTriviaInListCore(SyntaxTrivia originalTrivia, IEnumerable<SyntaxTrivia> newTrivia) { throw ExceptionUtilities.Unreachable; } protected internal override SyntaxNode InsertTriviaInListCore(SyntaxTrivia originalTrivia, IEnumerable<SyntaxTrivia> newTrivia, bool insertBefore) { throw ExceptionUtilities.Unreachable; } protected internal override SyntaxNode RemoveNodesCore(IEnumerable<SyntaxNode> nodes, SyntaxRemoveOptions options) { throw ExceptionUtilities.Unreachable; } protected internal override SyntaxNode NormalizeWhitespaceCore(string indentation, string eol, bool elasticTrivia) { throw ExceptionUtilities.Unreachable; } protected override bool IsEquivalentToCore(SyntaxNode node, bool topLevel = false) { throw ExceptionUtilities.Unreachable; } } }
-1
dotnet/roslyn
55,428
Test adding nested namespaces
Fixes https://github.com/dotnet/roslyn/issues/54939 The "workaround" that's already implemented is actually the correct behavior.
tmat
2021-08-05T01:19:03Z
2021-08-11T18:38:54Z
bc874ebc5111a2a33221409f895953b1536f6612
1cbbd423e17b186a8f1de89febb4db9a386d180d
Test adding nested namespaces. Fixes https://github.com/dotnet/roslyn/issues/54939 The "workaround" that's already implemented is actually the correct behavior.
./src/Analyzers/Core/CodeFixes/RemoveUnnecessarySuppressions/RemoveUnnecessaryPragmaSuppressionsCodeFixProvider.cs
// Licensed to the .NET Foundation under one or more agreements. // 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.Composition; using System.Diagnostics.CodeAnalysis; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; namespace Microsoft.CodeAnalysis.RemoveUnnecessarySuppressions { #if !CODE_STYLE // Not exported in CodeStyle layer: https://github.com/dotnet/roslyn/issues/47942 [ExportCodeFixProvider(LanguageNames.CSharp, LanguageNames.VisualBasic, Name = PredefinedCodeFixProviderNames.RemoveUnnecessaryPragmaSuppressions), Shared] #endif internal sealed class RemoveUnnecessaryInlineSuppressionsCodeFixProvider : SyntaxEditorBasedCodeFixProvider { [ImportingConstructor] [SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification = "Used in test code: https://github.com/dotnet/roslyn/issues/42814")] public RemoveUnnecessaryInlineSuppressionsCodeFixProvider() { } public override ImmutableArray<string> FixableDiagnosticIds => ImmutableArray.Create(IDEDiagnosticIds.RemoveUnnecessarySuppressionDiagnosticId); internal override CodeFixCategory CodeFixCategory => CodeFixCategory.CodeQuality; public override async Task RegisterCodeFixesAsync(CodeFixContext context) { var root = await context.Document.GetRequiredSyntaxRootAsync(context.CancellationToken).ConfigureAwait(false); var syntaxFacts = context.Document.GetRequiredLanguageService<ISyntaxFactsService>(); foreach (var diagnostic in context.Diagnostics) { // Defensive check that we are operating on the diagnostic on a pragma. if (root.FindNode(diagnostic.Location.SourceSpan) is { } node && syntaxFacts.IsAttribute(node) || root.FindTrivia(diagnostic.Location.SourceSpan.Start).HasStructure) { context.RegisterCodeFix( new MyCodeAction(c => FixAsync(context.Document, diagnostic, c)), diagnostic); } } } protected override Task FixAllAsync(Document document, ImmutableArray<Diagnostic> diagnostics, SyntaxEditor editor, CancellationToken cancellationToken) { // We need to track unique set of processed nodes when removing the nodes. // This is because we generate an unnecessary pragma suppression diagnostic at both the pragma disable and matching pragma restore location // with the corresponding restore/disable location as an additional location to be removed. // Our code fix ensures that we remove both the disable and restore directives with a single code fix application. // So, we need to ensure that we do not attempt to remove the same node multiple times when performing a FixAll in document operation. using var _ = PooledHashSet<SyntaxNode>.GetInstance(out var processedNodes); var syntaxFacts = document.GetRequiredLanguageService<ISyntaxFactsService>(); foreach (var diagnostic in diagnostics) { RemoveNode(diagnostic.Location, editor, processedNodes, syntaxFacts); foreach (var location in diagnostic.AdditionalLocations) { RemoveNode(location, editor, processedNodes, syntaxFacts); } } return Task.CompletedTask; static void RemoveNode( Location location, SyntaxEditor editor, HashSet<SyntaxNode> processedNodes, ISyntaxFacts syntaxFacts) { SyntaxNode node; var options = SyntaxGenerator.DefaultRemoveOptions; if (editor.OriginalRoot.FindNode(location.SourceSpan) is { } attribute && syntaxFacts.IsAttribute(attribute)) { node = attribute; // Keep leading trivia for attributes as we don't want to remove doc comments, or anything else options |= SyntaxRemoveOptions.KeepLeadingTrivia; } else { node = editor.OriginalRoot.FindTrivia(location.SourceSpan.Start).GetStructure()!; } if (processedNodes.Add(node)) { editor.RemoveNode(node, options); } } } private class MyCodeAction : CustomCodeActions.DocumentChangeAction { public MyCodeAction(Func<CancellationToken, Task<Document>> createChangedDocument) : base(AnalyzersResources.Remove_unnecessary_suppression, createChangedDocument, nameof(RemoveUnnecessaryInlineSuppressionsCodeFixProvider)) { } } } }
// Licensed to the .NET Foundation under one or more agreements. // 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.Composition; using System.Diagnostics.CodeAnalysis; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; namespace Microsoft.CodeAnalysis.RemoveUnnecessarySuppressions { #if !CODE_STYLE // Not exported in CodeStyle layer: https://github.com/dotnet/roslyn/issues/47942 [ExportCodeFixProvider(LanguageNames.CSharp, LanguageNames.VisualBasic, Name = PredefinedCodeFixProviderNames.RemoveUnnecessaryPragmaSuppressions), Shared] #endif internal sealed class RemoveUnnecessaryInlineSuppressionsCodeFixProvider : SyntaxEditorBasedCodeFixProvider { [ImportingConstructor] [SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification = "Used in test code: https://github.com/dotnet/roslyn/issues/42814")] public RemoveUnnecessaryInlineSuppressionsCodeFixProvider() { } public override ImmutableArray<string> FixableDiagnosticIds => ImmutableArray.Create(IDEDiagnosticIds.RemoveUnnecessarySuppressionDiagnosticId); internal override CodeFixCategory CodeFixCategory => CodeFixCategory.CodeQuality; public override async Task RegisterCodeFixesAsync(CodeFixContext context) { var root = await context.Document.GetRequiredSyntaxRootAsync(context.CancellationToken).ConfigureAwait(false); var syntaxFacts = context.Document.GetRequiredLanguageService<ISyntaxFactsService>(); foreach (var diagnostic in context.Diagnostics) { // Defensive check that we are operating on the diagnostic on a pragma. if (root.FindNode(diagnostic.Location.SourceSpan) is { } node && syntaxFacts.IsAttribute(node) || root.FindTrivia(diagnostic.Location.SourceSpan.Start).HasStructure) { context.RegisterCodeFix( new MyCodeAction(c => FixAsync(context.Document, diagnostic, c)), diagnostic); } } } protected override Task FixAllAsync(Document document, ImmutableArray<Diagnostic> diagnostics, SyntaxEditor editor, CancellationToken cancellationToken) { // We need to track unique set of processed nodes when removing the nodes. // This is because we generate an unnecessary pragma suppression diagnostic at both the pragma disable and matching pragma restore location // with the corresponding restore/disable location as an additional location to be removed. // Our code fix ensures that we remove both the disable and restore directives with a single code fix application. // So, we need to ensure that we do not attempt to remove the same node multiple times when performing a FixAll in document operation. using var _ = PooledHashSet<SyntaxNode>.GetInstance(out var processedNodes); var syntaxFacts = document.GetRequiredLanguageService<ISyntaxFactsService>(); foreach (var diagnostic in diagnostics) { RemoveNode(diagnostic.Location, editor, processedNodes, syntaxFacts); foreach (var location in diagnostic.AdditionalLocations) { RemoveNode(location, editor, processedNodes, syntaxFacts); } } return Task.CompletedTask; static void RemoveNode( Location location, SyntaxEditor editor, HashSet<SyntaxNode> processedNodes, ISyntaxFacts syntaxFacts) { SyntaxNode node; var options = SyntaxGenerator.DefaultRemoveOptions; if (editor.OriginalRoot.FindNode(location.SourceSpan) is { } attribute && syntaxFacts.IsAttribute(attribute)) { node = attribute; // Keep leading trivia for attributes as we don't want to remove doc comments, or anything else options |= SyntaxRemoveOptions.KeepLeadingTrivia; } else { node = editor.OriginalRoot.FindTrivia(location.SourceSpan.Start).GetStructure()!; } if (processedNodes.Add(node)) { editor.RemoveNode(node, options); } } } private class MyCodeAction : CustomCodeActions.DocumentChangeAction { public MyCodeAction(Func<CancellationToken, Task<Document>> createChangedDocument) : base(AnalyzersResources.Remove_unnecessary_suppression, createChangedDocument, nameof(RemoveUnnecessaryInlineSuppressionsCodeFixProvider)) { } } } }
-1
dotnet/roslyn
55,428
Test adding nested namespaces
Fixes https://github.com/dotnet/roslyn/issues/54939 The "workaround" that's already implemented is actually the correct behavior.
tmat
2021-08-05T01:19:03Z
2021-08-11T18:38:54Z
bc874ebc5111a2a33221409f895953b1536f6612
1cbbd423e17b186a8f1de89febb4db9a386d180d
Test adding nested namespaces. Fixes https://github.com/dotnet/roslyn/issues/54939 The "workaround" that's already implemented is actually the correct behavior.
./src/Workspaces/Core/Portable/Options/Providers/IOptionProvider.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Immutable; namespace Microsoft.CodeAnalysis.Options.Providers { internal interface IOptionProvider { ImmutableArray<IOption> Options { 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; namespace Microsoft.CodeAnalysis.Options.Providers { internal interface IOptionProvider { ImmutableArray<IOption> Options { get; } } }
-1
dotnet/roslyn
55,428
Test adding nested namespaces
Fixes https://github.com/dotnet/roslyn/issues/54939 The "workaround" that's already implemented is actually the correct behavior.
tmat
2021-08-05T01:19:03Z
2021-08-11T18:38:54Z
bc874ebc5111a2a33221409f895953b1536f6612
1cbbd423e17b186a8f1de89febb4db9a386d180d
Test adding nested namespaces. Fixes https://github.com/dotnet/roslyn/issues/54939 The "workaround" that's already implemented is actually the correct behavior.
./src/VisualStudio/IntegrationTest/IntegrationTests/CSharp/CSharpReplIdeFeatures.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.Shared.TestHooks; using Microsoft.VisualStudio.IntegrationTest.Utilities; using Roslyn.Test.Utilities; using Xunit; using Xunit.Abstractions; namespace Roslyn.VisualStudio.IntegrationTests.CSharp { [Collection(nameof(SharedIntegrationHostFixture))] public class CSharpReplIdeFeatures : AbstractInteractiveWindowTest { public CSharpReplIdeFeatures(VisualStudioInstanceFactory instanceFactory) : base(instanceFactory) { } public override Task DisposeAsync() { VisualStudio.Editor.SetUseSuggestionMode(false); VisualStudio.InteractiveWindow.ClearReplText(); VisualStudio.InteractiveWindow.Reset(); return base.DisposeAsync(); } [WpfFact] public void VerifyDefaultUsingStatements() { VisualStudio.InteractiveWindow.SubmitText("Console.WriteLine(42);"); VisualStudio.InteractiveWindow.WaitForLastReplOutput("42"); } [WpfFact(Skip = "https://github.com/dotnet/roslyn/issues/40160")] public void VerifyCodeActionsNotAvailableInPreviousSubmission() { VisualStudio.InteractiveWindow.InsertCode("Console.WriteLine(42);"); VisualStudio.InteractiveWindow.Verify.CodeActionsNotShowing(); } [WpfFact(Skip = "https://github.com/dotnet/roslyn/issues/40160")] public void VerifyQuickInfoOnStringDocCommentsFromMetadata() { VisualStudio.InteractiveWindow.InsertCode("static void Goo(string[] args) { }"); VisualStudio.InteractiveWindow.PlaceCaret("[]", charsOffset: -2); VisualStudio.InteractiveWindow.InvokeQuickInfo(); var s = VisualStudio.InteractiveWindow.GetQuickInfo(); Assert.Equal("class System.String", s); } [WpfFact(Skip = "https://github.com/dotnet/roslyn/issues/40160")] public void International() { VisualStudio.InteractiveWindow.InsertCode(@"delegate void العربية(); العربية func = () => System.Console.WriteLine(2);"); VisualStudio.InteractiveWindow.PlaceCaret("func", charsOffset: -1); VisualStudio.InteractiveWindow.InvokeQuickInfo(); var s = VisualStudio.InteractiveWindow.GetQuickInfo(); Assert.Equal("(field) العربية func", s); } [WpfFact(Skip = "https://github.com/dotnet/roslyn/issues/40160")] public void HighlightRefsSingleSubmissionVerifyRenameTagsShowUpWhenInvokedOnUnsubmittedText() { VisualStudio.InteractiveWindow.InsertCode("int someint; someint = 22; someint = 23;"); VisualStudio.InteractiveWindow.PlaceCaret("someint = 22", charsOffset: -6); VisualStudio.Workspace.WaitForAsyncOperations(Helper.HangMitigatingTimeout, FeatureAttribute.ReferenceHighlighting); VisualStudio.InteractiveWindow.VerifyTags(WellKnownTagNames.MarkerFormatDefinition_HighlightedWrittenReference, 2); VisualStudio.InteractiveWindow.VerifyTags(WellKnownTagNames.MarkerFormatDefinition_HighlightedDefinition, 1); } [WpfFact(Skip = "https://github.com/dotnet/roslyn/issues/40160")] public void HighlightRefsSingleSubmissionVerifyRenameTagsGoAway() { VisualStudio.InteractiveWindow.InsertCode("int someint; someint = 22; someint = 23;"); VisualStudio.InteractiveWindow.PlaceCaret("someint = 22", charsOffset: -6); VisualStudio.Workspace.WaitForAsyncOperations(Helper.HangMitigatingTimeout, FeatureAttribute.ReferenceHighlighting); VisualStudio.InteractiveWindow.VerifyTags(WellKnownTagNames.MarkerFormatDefinition_HighlightedWrittenReference, 2); VisualStudio.InteractiveWindow.PlaceCaret("22"); VisualStudio.Workspace.WaitForAsyncOperations(Helper.HangMitigatingTimeout, FeatureAttribute.ReferenceHighlighting); VisualStudio.InteractiveWindow.VerifyTags(WellKnownTagNames.MarkerFormatDefinition_HighlightedDefinition, 0); VisualStudio.InteractiveWindow.VerifyTags(WellKnownTagNames.MarkerFormatDefinition_HighlightedReference, 0); VisualStudio.InteractiveWindow.VerifyTags(WellKnownTagNames.MarkerFormatDefinition_HighlightedWrittenReference, 0); } [WpfFact(Skip = "https://github.com/dotnet/roslyn/issues/46027")] public void HighlightRefsMultipleSubmisionsVerifyRenameTagsShowUpWhenInvokedOnSubmittedText() { VisualStudio.InteractiveWindow.SubmitText("class Goo { }"); VisualStudio.InteractiveWindow.SubmitText("Goo something = new Goo();"); VisualStudio.InteractiveWindow.SubmitText("something.ToString();"); VisualStudio.InteractiveWindow.PlaceCaret("someth", charsOffset: 1, occurrence: 2); VisualStudio.Workspace.WaitForAsyncOperations(Helper.HangMitigatingTimeout, FeatureAttribute.ReferenceHighlighting); VisualStudio.InteractiveWindow.VerifyTags(WellKnownTagNames.MarkerFormatDefinition_HighlightedDefinition, 1); VisualStudio.InteractiveWindow.VerifyTags(WellKnownTagNames.MarkerFormatDefinition_HighlightedReference, 1); } [WpfFact(Skip = "https://github.com/dotnet/roslyn/issues/46027")] public void HighlightRefsMultipleSubmisionsVerifyRenameTagsShowUpOnUnsubmittedText() { VisualStudio.InteractiveWindow.SubmitText("class Goo { }"); VisualStudio.InteractiveWindow.SubmitText("Goo something = new Goo();"); VisualStudio.InteractiveWindow.InsertCode("something.ToString();"); VisualStudio.InteractiveWindow.PlaceCaret("someth", charsOffset: 1, occurrence: 2); VisualStudio.Workspace.WaitForAsyncOperations(Helper.HangMitigatingTimeout, FeatureAttribute.ReferenceHighlighting); VisualStudio.InteractiveWindow.VerifyTags(WellKnownTagNames.MarkerFormatDefinition_HighlightedDefinition, 1); VisualStudio.InteractiveWindow.VerifyTags(WellKnownTagNames.MarkerFormatDefinition_HighlightedReference, 1); } [WpfFact(Skip = "https://github.com/dotnet/roslyn/issues/46027")] public void HighlightRefsMultipleSubmisionsVerifyRenameTagsShowUpOnTypesWhenInvokedOnSubmittedText() { VisualStudio.InteractiveWindow.SubmitText("class Goo { }"); VisualStudio.InteractiveWindow.SubmitText("Goo a;"); VisualStudio.InteractiveWindow.SubmitText("Goo b;"); VisualStudio.InteractiveWindow.PlaceCaret("Goo b", charsOffset: -1); VisualStudio.Workspace.WaitForAsyncOperations(Helper.HangMitigatingTimeout, FeatureAttribute.ReferenceHighlighting); VisualStudio.InteractiveWindow.VerifyTags(WellKnownTagNames.MarkerFormatDefinition_HighlightedDefinition, 1); VisualStudio.InteractiveWindow.VerifyTags(WellKnownTagNames.MarkerFormatDefinition_HighlightedReference, 2); } [WpfFact(Skip = "https://github.com/dotnet/roslyn/issues/46027")] public void HighlightRefsMultipleSubmisionsVerifyRenameTagsShowUpOnTypesWhenInvokedOnUnsubmittedText() { VisualStudio.InteractiveWindow.SubmitText("class Goo { }"); VisualStudio.InteractiveWindow.SubmitText("Goo a;"); VisualStudio.InteractiveWindow.InsertCode("Goo b;"); VisualStudio.InteractiveWindow.PlaceCaret("Goo b", charsOffset: -1); VisualStudio.Workspace.WaitForAsyncOperations(Helper.HangMitigatingTimeout, FeatureAttribute.ReferenceHighlighting); VisualStudio.InteractiveWindow.VerifyTags(WellKnownTagNames.MarkerFormatDefinition_HighlightedDefinition, 1); VisualStudio.InteractiveWindow.VerifyTags(WellKnownTagNames.MarkerFormatDefinition_HighlightedReference, 2); } [WpfFact] public void HighlightRefsMultipleSubmisionsVerifyRenameTagsGoAwayWhenInvokedOnUnsubmittedText() { VisualStudio.InteractiveWindow.SubmitText("class Goo { }"); VisualStudio.InteractiveWindow.SubmitText("Goo a;"); VisualStudio.InteractiveWindow.InsertCode("Goo b;Something();"); VisualStudio.InteractiveWindow.PlaceCaret("Something();", charsOffset: -1); VisualStudio.Workspace.WaitForAsyncOperations(Helper.HangMitigatingTimeout, FeatureAttribute.Workspace); VisualStudio.InteractiveWindow.VerifyTags(WellKnownTagNames.MarkerFormatDefinition_HighlightedDefinition, 0); VisualStudio.InteractiveWindow.VerifyTags(WellKnownTagNames.MarkerFormatDefinition_HighlightedReference, 0); } [WpfFact] public void HighlightRefsMultipleSubmisionsVerifyRenameTagsOnRedefinedVariable() { VisualStudio.InteractiveWindow.SubmitText("string abc = null;"); VisualStudio.InteractiveWindow.SubmitText("abc = string.Empty;"); VisualStudio.InteractiveWindow.InsertCode("int abc = 42;"); VisualStudio.Workspace.WaitForAsyncOperations(Helper.HangMitigatingTimeout, FeatureAttribute.Workspace); VisualStudio.InteractiveWindow.PlaceCaret("abc", occurrence: 3); VisualStudio.Workspace.WaitForAsyncOperations(Helper.HangMitigatingTimeout, FeatureAttribute.ReferenceHighlighting); VisualStudio.InteractiveWindow.VerifyTags(WellKnownTagNames.MarkerFormatDefinition_HighlightedDefinition, 1); VisualStudio.InteractiveWindow.VerifyTags(WellKnownTagNames.MarkerFormatDefinition_HighlightedReference, 0); } [WpfFact(Skip = "https://github.com/dotnet/roslyn/issues/40160")] public void DisabledCommandsPart1() { VisualStudio.InteractiveWindow.InsertCode(@"public class Class { int field; public void Method(int x) { int abc = 1 + 1; } }"); VisualStudio.InteractiveWindow.PlaceCaret("abc"); VisualStudio.Workspace.WaitForAsyncOperations(Helper.HangMitigatingTimeout, FeatureAttribute.Workspace); Assert.False(VisualStudio.IsCommandAvailable(WellKnownCommandNames.Refactor_Rename)); VisualStudio.InteractiveWindow.PlaceCaret("1 + 1"); VisualStudio.Workspace.WaitForAsyncOperations(Helper.HangMitigatingTimeout, FeatureAttribute.Workspace); Assert.False(VisualStudio.IsCommandAvailable(WellKnownCommandNames.Refactor_ExtractMethod)); VisualStudio.InteractiveWindow.PlaceCaret("Class"); VisualStudio.Workspace.WaitForAsyncOperations(Helper.HangMitigatingTimeout, FeatureAttribute.Workspace); Assert.False(VisualStudio.IsCommandAvailable(WellKnownCommandNames.Refactor_ExtractInterface)); VisualStudio.InteractiveWindow.PlaceCaret("field"); VisualStudio.Workspace.WaitForAsyncOperations(Helper.HangMitigatingTimeout, FeatureAttribute.Workspace); Assert.False(VisualStudio.IsCommandAvailable(WellKnownCommandNames.Refactor_EncapsulateField)); VisualStudio.InteractiveWindow.PlaceCaret("Method"); VisualStudio.Workspace.WaitForAsyncOperations(Helper.HangMitigatingTimeout, FeatureAttribute.Workspace); Assert.False(VisualStudio.IsCommandAvailable(WellKnownCommandNames.Refactor_RemoveParameters)); Assert.False(VisualStudio.IsCommandAvailable(WellKnownCommandNames.Refactor_ReorderParameters)); } [WpfFact(Skip = "https://github.com/dotnet/roslyn/issues/40160")] public void AddUsing() { VisualStudio.InteractiveWindow.InsertCode("typeof(ArrayList)"); VisualStudio.InteractiveWindow.PlaceCaret("ArrayList"); VisualStudio.Workspace.WaitForAsyncOperations(Helper.HangMitigatingTimeout, FeatureAttribute.Workspace); VisualStudio.InteractiveWindow.InvokeCodeActionList(); VisualStudio.InteractiveWindow.Verify.CodeActions( new string[] { "using System.Collections;", "System.Collections.ArrayList" }, "using System.Collections;"); VisualStudio.InteractiveWindow.Verify.LastReplInput(@"using System.Collections; typeof(ArrayList)"); } [WpfFact(Skip = "https://github.com/dotnet/roslyn/issues/40160")] public void QualifyName() { VisualStudio.InteractiveWindow.InsertCode("typeof(ArrayList)"); VisualStudio.Workspace.WaitForAsyncOperations(Helper.HangMitigatingTimeout, FeatureAttribute.Workspace); VisualStudio.InteractiveWindow.PlaceCaret("ArrayList"); VisualStudio.Workspace.WaitForAsyncOperations(Helper.HangMitigatingTimeout, FeatureAttribute.Workspace); VisualStudio.InteractiveWindow.Verify.CodeActions( new string[] { "using System.Collections;", "System.Collections.ArrayList" }, "System.Collections.ArrayList"); VisualStudio.InteractiveWindow.Verify.LastReplInput("typeof(System.Collections.ArrayList)"); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.Shared.TestHooks; using Microsoft.VisualStudio.IntegrationTest.Utilities; using Roslyn.Test.Utilities; using Xunit; using Xunit.Abstractions; namespace Roslyn.VisualStudio.IntegrationTests.CSharp { [Collection(nameof(SharedIntegrationHostFixture))] public class CSharpReplIdeFeatures : AbstractInteractiveWindowTest { public CSharpReplIdeFeatures(VisualStudioInstanceFactory instanceFactory) : base(instanceFactory) { } public override Task DisposeAsync() { VisualStudio.Editor.SetUseSuggestionMode(false); VisualStudio.InteractiveWindow.ClearReplText(); VisualStudio.InteractiveWindow.Reset(); return base.DisposeAsync(); } [WpfFact] public void VerifyDefaultUsingStatements() { VisualStudio.InteractiveWindow.SubmitText("Console.WriteLine(42);"); VisualStudio.InteractiveWindow.WaitForLastReplOutput("42"); } [WpfFact(Skip = "https://github.com/dotnet/roslyn/issues/40160")] public void VerifyCodeActionsNotAvailableInPreviousSubmission() { VisualStudio.InteractiveWindow.InsertCode("Console.WriteLine(42);"); VisualStudio.InteractiveWindow.Verify.CodeActionsNotShowing(); } [WpfFact(Skip = "https://github.com/dotnet/roslyn/issues/40160")] public void VerifyQuickInfoOnStringDocCommentsFromMetadata() { VisualStudio.InteractiveWindow.InsertCode("static void Goo(string[] args) { }"); VisualStudio.InteractiveWindow.PlaceCaret("[]", charsOffset: -2); VisualStudio.InteractiveWindow.InvokeQuickInfo(); var s = VisualStudio.InteractiveWindow.GetQuickInfo(); Assert.Equal("class System.String", s); } [WpfFact(Skip = "https://github.com/dotnet/roslyn/issues/40160")] public void International() { VisualStudio.InteractiveWindow.InsertCode(@"delegate void العربية(); العربية func = () => System.Console.WriteLine(2);"); VisualStudio.InteractiveWindow.PlaceCaret("func", charsOffset: -1); VisualStudio.InteractiveWindow.InvokeQuickInfo(); var s = VisualStudio.InteractiveWindow.GetQuickInfo(); Assert.Equal("(field) العربية func", s); } [WpfFact(Skip = "https://github.com/dotnet/roslyn/issues/40160")] public void HighlightRefsSingleSubmissionVerifyRenameTagsShowUpWhenInvokedOnUnsubmittedText() { VisualStudio.InteractiveWindow.InsertCode("int someint; someint = 22; someint = 23;"); VisualStudio.InteractiveWindow.PlaceCaret("someint = 22", charsOffset: -6); VisualStudio.Workspace.WaitForAsyncOperations(Helper.HangMitigatingTimeout, FeatureAttribute.ReferenceHighlighting); VisualStudio.InteractiveWindow.VerifyTags(WellKnownTagNames.MarkerFormatDefinition_HighlightedWrittenReference, 2); VisualStudio.InteractiveWindow.VerifyTags(WellKnownTagNames.MarkerFormatDefinition_HighlightedDefinition, 1); } [WpfFact(Skip = "https://github.com/dotnet/roslyn/issues/40160")] public void HighlightRefsSingleSubmissionVerifyRenameTagsGoAway() { VisualStudio.InteractiveWindow.InsertCode("int someint; someint = 22; someint = 23;"); VisualStudio.InteractiveWindow.PlaceCaret("someint = 22", charsOffset: -6); VisualStudio.Workspace.WaitForAsyncOperations(Helper.HangMitigatingTimeout, FeatureAttribute.ReferenceHighlighting); VisualStudio.InteractiveWindow.VerifyTags(WellKnownTagNames.MarkerFormatDefinition_HighlightedWrittenReference, 2); VisualStudio.InteractiveWindow.PlaceCaret("22"); VisualStudio.Workspace.WaitForAsyncOperations(Helper.HangMitigatingTimeout, FeatureAttribute.ReferenceHighlighting); VisualStudio.InteractiveWindow.VerifyTags(WellKnownTagNames.MarkerFormatDefinition_HighlightedDefinition, 0); VisualStudio.InteractiveWindow.VerifyTags(WellKnownTagNames.MarkerFormatDefinition_HighlightedReference, 0); VisualStudio.InteractiveWindow.VerifyTags(WellKnownTagNames.MarkerFormatDefinition_HighlightedWrittenReference, 0); } [WpfFact(Skip = "https://github.com/dotnet/roslyn/issues/46027")] public void HighlightRefsMultipleSubmisionsVerifyRenameTagsShowUpWhenInvokedOnSubmittedText() { VisualStudio.InteractiveWindow.SubmitText("class Goo { }"); VisualStudio.InteractiveWindow.SubmitText("Goo something = new Goo();"); VisualStudio.InteractiveWindow.SubmitText("something.ToString();"); VisualStudio.InteractiveWindow.PlaceCaret("someth", charsOffset: 1, occurrence: 2); VisualStudio.Workspace.WaitForAsyncOperations(Helper.HangMitigatingTimeout, FeatureAttribute.ReferenceHighlighting); VisualStudio.InteractiveWindow.VerifyTags(WellKnownTagNames.MarkerFormatDefinition_HighlightedDefinition, 1); VisualStudio.InteractiveWindow.VerifyTags(WellKnownTagNames.MarkerFormatDefinition_HighlightedReference, 1); } [WpfFact(Skip = "https://github.com/dotnet/roslyn/issues/46027")] public void HighlightRefsMultipleSubmisionsVerifyRenameTagsShowUpOnUnsubmittedText() { VisualStudio.InteractiveWindow.SubmitText("class Goo { }"); VisualStudio.InteractiveWindow.SubmitText("Goo something = new Goo();"); VisualStudio.InteractiveWindow.InsertCode("something.ToString();"); VisualStudio.InteractiveWindow.PlaceCaret("someth", charsOffset: 1, occurrence: 2); VisualStudio.Workspace.WaitForAsyncOperations(Helper.HangMitigatingTimeout, FeatureAttribute.ReferenceHighlighting); VisualStudio.InteractiveWindow.VerifyTags(WellKnownTagNames.MarkerFormatDefinition_HighlightedDefinition, 1); VisualStudio.InteractiveWindow.VerifyTags(WellKnownTagNames.MarkerFormatDefinition_HighlightedReference, 1); } [WpfFact(Skip = "https://github.com/dotnet/roslyn/issues/46027")] public void HighlightRefsMultipleSubmisionsVerifyRenameTagsShowUpOnTypesWhenInvokedOnSubmittedText() { VisualStudio.InteractiveWindow.SubmitText("class Goo { }"); VisualStudio.InteractiveWindow.SubmitText("Goo a;"); VisualStudio.InteractiveWindow.SubmitText("Goo b;"); VisualStudio.InteractiveWindow.PlaceCaret("Goo b", charsOffset: -1); VisualStudio.Workspace.WaitForAsyncOperations(Helper.HangMitigatingTimeout, FeatureAttribute.ReferenceHighlighting); VisualStudio.InteractiveWindow.VerifyTags(WellKnownTagNames.MarkerFormatDefinition_HighlightedDefinition, 1); VisualStudio.InteractiveWindow.VerifyTags(WellKnownTagNames.MarkerFormatDefinition_HighlightedReference, 2); } [WpfFact(Skip = "https://github.com/dotnet/roslyn/issues/46027")] public void HighlightRefsMultipleSubmisionsVerifyRenameTagsShowUpOnTypesWhenInvokedOnUnsubmittedText() { VisualStudio.InteractiveWindow.SubmitText("class Goo { }"); VisualStudio.InteractiveWindow.SubmitText("Goo a;"); VisualStudio.InteractiveWindow.InsertCode("Goo b;"); VisualStudio.InteractiveWindow.PlaceCaret("Goo b", charsOffset: -1); VisualStudio.Workspace.WaitForAsyncOperations(Helper.HangMitigatingTimeout, FeatureAttribute.ReferenceHighlighting); VisualStudio.InteractiveWindow.VerifyTags(WellKnownTagNames.MarkerFormatDefinition_HighlightedDefinition, 1); VisualStudio.InteractiveWindow.VerifyTags(WellKnownTagNames.MarkerFormatDefinition_HighlightedReference, 2); } [WpfFact] public void HighlightRefsMultipleSubmisionsVerifyRenameTagsGoAwayWhenInvokedOnUnsubmittedText() { VisualStudio.InteractiveWindow.SubmitText("class Goo { }"); VisualStudio.InteractiveWindow.SubmitText("Goo a;"); VisualStudio.InteractiveWindow.InsertCode("Goo b;Something();"); VisualStudio.InteractiveWindow.PlaceCaret("Something();", charsOffset: -1); VisualStudio.Workspace.WaitForAsyncOperations(Helper.HangMitigatingTimeout, FeatureAttribute.Workspace); VisualStudio.InteractiveWindow.VerifyTags(WellKnownTagNames.MarkerFormatDefinition_HighlightedDefinition, 0); VisualStudio.InteractiveWindow.VerifyTags(WellKnownTagNames.MarkerFormatDefinition_HighlightedReference, 0); } [WpfFact] public void HighlightRefsMultipleSubmisionsVerifyRenameTagsOnRedefinedVariable() { VisualStudio.InteractiveWindow.SubmitText("string abc = null;"); VisualStudio.InteractiveWindow.SubmitText("abc = string.Empty;"); VisualStudio.InteractiveWindow.InsertCode("int abc = 42;"); VisualStudio.Workspace.WaitForAsyncOperations(Helper.HangMitigatingTimeout, FeatureAttribute.Workspace); VisualStudio.InteractiveWindow.PlaceCaret("abc", occurrence: 3); VisualStudio.Workspace.WaitForAsyncOperations(Helper.HangMitigatingTimeout, FeatureAttribute.ReferenceHighlighting); VisualStudio.InteractiveWindow.VerifyTags(WellKnownTagNames.MarkerFormatDefinition_HighlightedDefinition, 1); VisualStudio.InteractiveWindow.VerifyTags(WellKnownTagNames.MarkerFormatDefinition_HighlightedReference, 0); } [WpfFact(Skip = "https://github.com/dotnet/roslyn/issues/40160")] public void DisabledCommandsPart1() { VisualStudio.InteractiveWindow.InsertCode(@"public class Class { int field; public void Method(int x) { int abc = 1 + 1; } }"); VisualStudio.InteractiveWindow.PlaceCaret("abc"); VisualStudio.Workspace.WaitForAsyncOperations(Helper.HangMitigatingTimeout, FeatureAttribute.Workspace); Assert.False(VisualStudio.IsCommandAvailable(WellKnownCommandNames.Refactor_Rename)); VisualStudio.InteractiveWindow.PlaceCaret("1 + 1"); VisualStudio.Workspace.WaitForAsyncOperations(Helper.HangMitigatingTimeout, FeatureAttribute.Workspace); Assert.False(VisualStudio.IsCommandAvailable(WellKnownCommandNames.Refactor_ExtractMethod)); VisualStudio.InteractiveWindow.PlaceCaret("Class"); VisualStudio.Workspace.WaitForAsyncOperations(Helper.HangMitigatingTimeout, FeatureAttribute.Workspace); Assert.False(VisualStudio.IsCommandAvailable(WellKnownCommandNames.Refactor_ExtractInterface)); VisualStudio.InteractiveWindow.PlaceCaret("field"); VisualStudio.Workspace.WaitForAsyncOperations(Helper.HangMitigatingTimeout, FeatureAttribute.Workspace); Assert.False(VisualStudio.IsCommandAvailable(WellKnownCommandNames.Refactor_EncapsulateField)); VisualStudio.InteractiveWindow.PlaceCaret("Method"); VisualStudio.Workspace.WaitForAsyncOperations(Helper.HangMitigatingTimeout, FeatureAttribute.Workspace); Assert.False(VisualStudio.IsCommandAvailable(WellKnownCommandNames.Refactor_RemoveParameters)); Assert.False(VisualStudio.IsCommandAvailable(WellKnownCommandNames.Refactor_ReorderParameters)); } [WpfFact(Skip = "https://github.com/dotnet/roslyn/issues/40160")] public void AddUsing() { VisualStudio.InteractiveWindow.InsertCode("typeof(ArrayList)"); VisualStudio.InteractiveWindow.PlaceCaret("ArrayList"); VisualStudio.Workspace.WaitForAsyncOperations(Helper.HangMitigatingTimeout, FeatureAttribute.Workspace); VisualStudio.InteractiveWindow.InvokeCodeActionList(); VisualStudio.InteractiveWindow.Verify.CodeActions( new string[] { "using System.Collections;", "System.Collections.ArrayList" }, "using System.Collections;"); VisualStudio.InteractiveWindow.Verify.LastReplInput(@"using System.Collections; typeof(ArrayList)"); } [WpfFact(Skip = "https://github.com/dotnet/roslyn/issues/40160")] public void QualifyName() { VisualStudio.InteractiveWindow.InsertCode("typeof(ArrayList)"); VisualStudio.Workspace.WaitForAsyncOperations(Helper.HangMitigatingTimeout, FeatureAttribute.Workspace); VisualStudio.InteractiveWindow.PlaceCaret("ArrayList"); VisualStudio.Workspace.WaitForAsyncOperations(Helper.HangMitigatingTimeout, FeatureAttribute.Workspace); VisualStudio.InteractiveWindow.Verify.CodeActions( new string[] { "using System.Collections;", "System.Collections.ArrayList" }, "System.Collections.ArrayList"); VisualStudio.InteractiveWindow.Verify.LastReplInput("typeof(System.Collections.ArrayList)"); } } }
-1
dotnet/roslyn
55,428
Test adding nested namespaces
Fixes https://github.com/dotnet/roslyn/issues/54939 The "workaround" that's already implemented is actually the correct behavior.
tmat
2021-08-05T01:19:03Z
2021-08-11T18:38:54Z
bc874ebc5111a2a33221409f895953b1536f6612
1cbbd423e17b186a8f1de89febb4db9a386d180d
Test adding nested namespaces. Fixes https://github.com/dotnet/roslyn/issues/54939 The "workaround" that's already implemented is actually the correct behavior.
./src/Compilers/CSharp/Test/IOperation/IOperation/IOperationTests_IThrowOperation.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET 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.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public class IOperationTests_IThrowOperation : SemanticModelTestBase { [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void ThrowFlow_01() { var source = @" class C { void F() /*<bind>*/{ throw; }/*</bind>*/ }"; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (6,9): error CS0156: A throw statement with no arguments is not allowed outside of a catch clause // throw; Diagnostic(ErrorCode.ERR_BadEmptyThrow, "throw").WithLocation(6, 9) ); string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Block[B1] - Block Predecessors: [B0] Statements (0) Next (Rethrow) Block[null] Block[B2] - Exit [UnReachable] Predecessors (0) Statements (0) "; VerifyFlowGraphForTest<BlockSyntax>(compilation, expectedGraph); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void ThrowFlow_02() { var source = @" class C { void F(int x) /*<bind>*/{ x = 1; throw; x = 2; }/*</bind>*/ }"; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (7,9): error CS0156: A throw statement with no arguments is not allowed outside of a catch clause // throw; Diagnostic(ErrorCode.ERR_BadEmptyThrow, "throw").WithLocation(7, 9), // (8,9): warning CS0162: Unreachable code detected // x = 2; Diagnostic(ErrorCode.WRN_UnreachableCode, "x").WithLocation(8, 9) ); string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Block[B1] - Block Predecessors: [B0] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'x = 1;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'x = 1') Left: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'x') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Next (Rethrow) Block[null] Block[B2] - Block [UnReachable] Predecessors (0) Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'x = 2;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'x = 2') Left: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'x') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') Next (Regular) Block[B3] Block[B3] - Exit [UnReachable] Predecessors: [B2] Statements (0) "; VerifyFlowGraphForTest<BlockSyntax>(compilation, expectedGraph); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void ThrowFlow_03() { var source = @" class C { void F(System.Exception ex) /*<bind>*/{ throw ex; }/*</bind>*/ }"; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics(); string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Block[B1] - Block Predecessors: [B0] Statements (0) Next (Throw) Block[null] IParameterReferenceOperation: ex (OperationKind.ParameterReference, Type: System.Exception) (Syntax: 'ex') Block[B2] - Exit [UnReachable] Predecessors (0) Statements (0) "; VerifyFlowGraphForTest<BlockSyntax>(compilation, expectedGraph); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void ThrowFlow_04() { var source = @" class C { void F(System.Exception ex) /*<bind>*/{ int x = 1; throw ex; x = 2; }/*</bind>*/ }"; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (8,9): warning CS0162: Unreachable code detected // x = 2; Diagnostic(ErrorCode.WRN_UnreachableCode, "x").WithLocation(8, 9), // (6,13): warning CS0219: The variable 'x' is assigned but its value is never used // int x = 1; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "x").WithArguments("x").WithLocation(6, 13) ); string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { Locals: [System.Int32 x] Block[B1] - Block Predecessors: [B0] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'x = 1') Left: ILocalReferenceOperation: x (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsImplicit) (Syntax: 'x = 1') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Next (Throw) Block[null] IParameterReferenceOperation: ex (OperationKind.ParameterReference, Type: System.Exception) (Syntax: 'ex') Block[B2] - Block [UnReachable] Predecessors (0) Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'x = 2;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'x = 2') Left: ILocalReferenceOperation: x (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'x') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') Next (Regular) Block[B3] Leaving: {R1} } Block[B3] - Exit [UnReachable] Predecessors: [B2] Statements (0) "; VerifyFlowGraphForTest<BlockSyntax>(compilation, expectedGraph); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void ThrowFlow_05() { var source = @" class C { void F(int x, System.Exception ex) /*<bind>*/{ x = throw ex + x; }/*</bind>*/ }"; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (6,13): error CS8115: A throw expression is not allowed in this context. // x = throw ex + x; Diagnostic(ErrorCode.ERR_ThrowMisplaced, "throw").WithLocation(6, 13), // (6,19): error CS0019: Operator '+' cannot be applied to operands of type 'Exception' and 'int' // x = throw ex + x; Diagnostic(ErrorCode.ERR_BadBinaryOps, "ex + x").WithArguments("+", "System.Exception", "int").WithLocation(6, 19) ); string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'x') Value: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'x') Next (Throw) Block[null] IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Exception, IsInvalid, IsImplicit) (Syntax: 'ex + x') Conversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) (NoConversion) Operand: IBinaryOperation (BinaryOperatorKind.Add) (OperationKind.Binary, Type: ?, IsInvalid) (Syntax: 'ex + x') Left: IParameterReferenceOperation: ex (OperationKind.ParameterReference, Type: System.Exception, IsInvalid) (Syntax: 'ex') Right: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Int32, IsInvalid) (Syntax: 'x') Block[B2] - Block [UnReachable] Predecessors (0) Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid) (Syntax: 'x = throw ex + x;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsInvalid) (Syntax: 'x = throw ex + x') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'x') Right: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'throw ex + x') Conversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) (NoConversion) Operand: IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid, IsImplicit) (Syntax: 'throw ex + x') Children(1): IOperation: (OperationKind.None, Type: null, IsInvalid, IsImplicit) (Syntax: 'throw ex + x') Next (Regular) Block[B3] Leaving: {R1} } Block[B3] - Exit [UnReachable] Predecessors: [B2] Statements (0) "; VerifyFlowGraphForTest<BlockSyntax>(compilation, expectedGraph); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void ThrowFlow_06() { var source = @" class C { void F(int x, System.Exception ex) /*<bind>*/{ x = (throw ex) + x; }/*</bind>*/ }"; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (6,14): error CS8115: A throw expression is not allowed in this context. // x = (throw ex) + x; Diagnostic(ErrorCode.ERR_ThrowMisplaced, "throw").WithLocation(6, 14) ); string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'x') Value: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'x') Next (Throw) Block[null] IParameterReferenceOperation: ex (OperationKind.ParameterReference, Type: System.Exception) (Syntax: 'ex') Block[B2] - Block [UnReachable] Predecessors (0) Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid) (Syntax: 'x = (throw ex) + x;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsInvalid) (Syntax: 'x = (throw ex) + x') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'x') Right: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: '(throw ex) + x') Conversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) (NoConversion) Operand: IBinaryOperation (BinaryOperatorKind.Add) (OperationKind.Binary, Type: ?, IsInvalid) (Syntax: '(throw ex) + x') Left: IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid, IsImplicit) (Syntax: 'throw ex') Children(1): IOperation: (OperationKind.None, Type: null, IsInvalid, IsImplicit) (Syntax: 'throw ex') Right: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'x') Next (Regular) Block[B3] Leaving: {R1} } Block[B3] - Exit [UnReachable] Predecessors: [B2] Statements (0) "; VerifyFlowGraphForTest<BlockSyntax>(compilation, expectedGraph); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void ThrowFlow_07() { var source = @" class C { void F(int x, System.Exception ex) /*<bind>*/{ x = x + throw ex; }/*</bind>*/ }"; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (6,17): error CS1525: Invalid expression term 'throw' // x = x + throw ex; Diagnostic(ErrorCode.ERR_InvalidExprTerm, "throw ex").WithArguments("throw").WithLocation(6, 17) ); string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] [1] Block[B1] - Block Predecessors: [B0] Statements (2) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'x') Value: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'x') IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'x') Value: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'x') Next (Throw) Block[null] IParameterReferenceOperation: ex (OperationKind.ParameterReference, Type: System.Exception, IsInvalid) (Syntax: 'ex') Block[B2] - Block [UnReachable] Predecessors (0) Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid) (Syntax: 'x = x + throw ex;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsInvalid) (Syntax: 'x = x + throw ex') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'x') Right: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'x + throw ex') Conversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) (NoConversion) Operand: IBinaryOperation (BinaryOperatorKind.Add) (OperationKind.Binary, Type: ?, IsInvalid) (Syntax: 'x + throw ex') Left: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'x') Right: IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid, IsImplicit) (Syntax: 'throw ex') Children(1): IOperation: (OperationKind.None, Type: null, IsInvalid, IsImplicit) (Syntax: 'throw ex') Next (Regular) Block[B3] Leaving: {R1} } Block[B3] - Exit [UnReachable] Predecessors: [B2] Statements (0) "; VerifyFlowGraphForTest<BlockSyntax>(compilation, expectedGraph); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void ThrowFlow_08() { var source = @" class C { void F(int x, System.Exception ex) /*<bind>*/{ x = x + (throw ex); }/*</bind>*/ }"; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (6,18): error CS8115: A throw expression is not allowed in this context. // x = x + (throw ex); Diagnostic(ErrorCode.ERR_ThrowMisplaced, "throw").WithLocation(6, 18) ); string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] [1] Block[B1] - Block Predecessors: [B0] Statements (2) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'x') Value: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'x') IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'x') Value: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'x') Next (Throw) Block[null] IParameterReferenceOperation: ex (OperationKind.ParameterReference, Type: System.Exception) (Syntax: 'ex') Block[B2] - Block [UnReachable] Predecessors (0) Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid) (Syntax: 'x = x + (throw ex);') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsInvalid) (Syntax: 'x = x + (throw ex)') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'x') Right: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'x + (throw ex)') Conversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) (NoConversion) Operand: IBinaryOperation (BinaryOperatorKind.Add) (OperationKind.Binary, Type: ?, IsInvalid) (Syntax: 'x + (throw ex)') Left: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'x') Right: IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid, IsImplicit) (Syntax: 'throw ex') Children(1): IOperation: (OperationKind.None, Type: null, IsInvalid, IsImplicit) (Syntax: 'throw ex') Next (Regular) Block[B3] Leaving: {R1} } Block[B3] - Exit [UnReachable] Predecessors: [B2] Statements (0) "; VerifyFlowGraphForTest<BlockSyntax>(compilation, expectedGraph); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void ThrowFlow_09() { var source = @" class C { void F(object x, object y, System.Exception ex) /*<bind>*/{ x = y ?? throw ex; }/*</bind>*/ }"; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics(); string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] [1] Block[B1] - Block Predecessors: [B0] Statements (2) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'x') Value: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'x') IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'y') Value: IParameterReferenceOperation: y (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'y') Jump if True (Regular) to Block[B2] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'y') Operand: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'y') Next (Regular) Block[B3] Block[B2] - Block Predecessors: [B1] Statements (0) Next (Throw) Block[null] IParameterReferenceOperation: ex (OperationKind.ParameterReference, Type: System.Exception) (Syntax: 'ex') Block[B3] - Block Predecessors: [B1] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'x = y ?? throw ex;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Object) (Syntax: 'x = y ?? throw ex') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'x') Right: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'y') Next (Regular) Block[B4] Leaving: {R1} } Block[B4] - Exit Predecessors: [B3] Statements (0) "; VerifyFlowGraphForTest<BlockSyntax>(compilation, expectedGraph); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void ThrowFlow_10() { var source = @" class C { void F(object x, object y, object z, System.Exception ex) /*<bind>*/{ M(x, y ?? throw ex, z); }/*</bind>*/ static void M(object x, object y, object z){} }"; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics(); string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] [1] Block[B1] - Block Predecessors: [B0] Statements (2) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'x') Value: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'x') IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'y') Value: IParameterReferenceOperation: y (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'y') Jump if True (Regular) to Block[B2] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'y') Operand: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'y') Next (Regular) Block[B3] Block[B2] - Block Predecessors: [B1] Statements (0) Next (Throw) Block[null] IParameterReferenceOperation: ex (OperationKind.ParameterReference, Type: System.Exception) (Syntax: 'ex') Block[B3] - Block Predecessors: [B1] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'M(x, y ?? throw ex, z);') Expression: IInvocationOperation (void C.M(System.Object x, System.Object y, System.Object z)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'M(x, y ?? throw ex, z)') Instance Receiver: null Arguments(3): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null) (Syntax: 'x') IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'x') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: y) (OperationKind.Argument, Type: null) (Syntax: 'y ?? throw ex') IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'y') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: z) (OperationKind.Argument, Type: null) (Syntax: 'z') IParameterReferenceOperation: z (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'z') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Next (Regular) Block[B4] Leaving: {R1} } Block[B4] - Exit Predecessors: [B3] Statements (0) "; VerifyFlowGraphForTest<BlockSyntax>(compilation, expectedGraph); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void ThrowFlow_11() { var source = @" class C { void F(int u) /*<bind>*/{ try { u = 1; } catch { throw; } }/*</bind>*/ static void M(object x, object y, object z){} }"; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics(); string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} .try {R1, R2} { Block[B1] - Block Predecessors: [B0] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'u = 1;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'u = 1') Left: IParameterReferenceOperation: u (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'u') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Next (Regular) Block[B3] Leaving: {R2} {R1} } .catch {R3} (System.Object) { Block[B2] - Block Predecessors (0) Statements (0) Next (Rethrow) Block[null] } Block[B3] - Exit Predecessors: [B1] Statements (0) "; VerifyFlowGraphForTest<BlockSyntax>(compilation, expectedGraph); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void ThrowFlow_12() { var source = @" class C { void F(int u) /*<bind>*/{ try { u = 1; } catch { u = 2; throw; u = 3; } }/*</bind>*/ static void M(object x, object y, object z){} }"; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (14,13): warning CS0162: Unreachable code detected // u = 3; Diagnostic(ErrorCode.WRN_UnreachableCode, "u").WithLocation(14, 13) ); string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} .try {R1, R2} { Block[B1] - Block Predecessors: [B0] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'u = 1;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'u = 1') Left: IParameterReferenceOperation: u (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'u') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Next (Regular) Block[B4] Leaving: {R2} {R1} } .catch {R3} (System.Object) { Block[B2] - Block Predecessors (0) Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'u = 2;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'u = 2') Left: IParameterReferenceOperation: u (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'u') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') Next (Rethrow) Block[null] Block[B3] - Block [UnReachable] Predecessors (0) Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'u = 3;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'u = 3') Left: IParameterReferenceOperation: u (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'u') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 3) (Syntax: '3') Next (Regular) Block[B4] Leaving: {R3} {R1} } Block[B4] - Exit Predecessors: [B1] [B3] Statements (0) "; VerifyFlowGraphForTest<BlockSyntax>(compilation, expectedGraph); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void ThrowFlow_13() { var source = @" class C { void F(object x, object y, object z, int u) /*<bind>*/{ try { u = 1; } catch { M(x, (y ?? throw), z); } }/*</bind>*/ static void M(object x, object y, object z){} } "; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (12,29): error CS1525: Invalid expression term ')' // M(x, (y ?? throw), z); Diagnostic(ErrorCode.ERR_InvalidExprTerm, ")").WithArguments(")").WithLocation(12, 29) ); string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} .try {R1, R2} { Block[B1] - Block Predecessors: [B0] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'u = 1;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'u = 1') Left: IParameterReferenceOperation: u (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'u') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Next (Regular) Block[B8] Leaving: {R2} {R1} } .catch {R3} (System.Object) { CaptureIds: [0] [2] Block[B2] - Block Predecessors (0) Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'x') Value: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'x') Next (Regular) Block[B3] Entering: {R4} .locals {R4} { CaptureIds: [1] Block[B3] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'y') Value: IParameterReferenceOperation: y (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'y') Jump if True (Regular) to Block[B5] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'y') Operand: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'y') Leaving: {R4} Next (Regular) Block[B4] Block[B4] - Block Predecessors: [B3] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'y') Value: IInvalidOperation (OperationKind.Invalid, Type: ?, IsImplicit) (Syntax: 'y') Children(1): IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'y') Next (Regular) Block[B7] Leaving: {R4} } Block[B5] - Block Predecessors: [B3] Statements (0) Next (Throw) Block[null] IInvalidOperation (OperationKind.Invalid, Type: null, IsInvalid) (Syntax: '') Children(0) Block[B6] - Block [UnReachable] Predecessors (0) Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'throw') Value: IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid, IsImplicit) (Syntax: 'throw') Children(1): IOperation: (OperationKind.None, Type: null, IsInvalid, IsImplicit) (Syntax: 'throw') Next (Regular) Block[B7] Block[B7] - Block Predecessors: [B4] [B6] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid) (Syntax: 'M(x, (y ?? throw), z);') Expression: IInvalidOperation (OperationKind.Invalid, Type: System.Void, IsInvalid) (Syntax: 'M(x, (y ?? throw), z)') Children(3): IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'x') IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: ?, IsInvalid, IsImplicit) (Syntax: 'y ?? throw') IParameterReferenceOperation: z (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'z') Next (Regular) Block[B8] Leaving: {R3} {R1} } Block[B8] - Exit Predecessors: [B1] [B7] Statements (0) "; VerifyFlowGraphForTest<BlockSyntax>(compilation, expectedGraph); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void ThrowFlow_14() { var source = @" class C { void F(System.Exception ex) /*<bind>*/{ ex = null; goto label1; label1: throw ex; }/*</bind>*/ }"; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics(); string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Block[B1] - Block Predecessors: [B0] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'ex = null;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Exception) (Syntax: 'ex = null') Left: IParameterReferenceOperation: ex (OperationKind.ParameterReference, Type: System.Exception) (Syntax: 'ex') Right: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Exception, Constant: null, IsImplicit) (Syntax: 'null') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) (ImplicitReference) Operand: ILiteralOperation (OperationKind.Literal, Type: null, Constant: null) (Syntax: 'null') Next (Throw) Block[null] IParameterReferenceOperation: ex (OperationKind.ParameterReference, Type: System.Exception) (Syntax: 'ex') Block[B2] - Exit [UnReachable] Predecessors (0) Statements (0) "; VerifyFlowGraphForTest<BlockSyntax>(compilation, expectedGraph); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void ThrowFlow_15() { var source = @" class C { void F(int x) /*<bind>*/{ try { x = 1; } catch { x = 2; goto label1; label1: throw; } }/*</bind>*/ }"; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics(); string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} .try {R1, R2} { Block[B1] - Block Predecessors: [B0] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'x = 1;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'x = 1') Left: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'x') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Next (Regular) Block[B3] Leaving: {R2} {R1} } .catch {R3} (System.Object) { Block[B2] - Block Predecessors (0) Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'x = 2;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'x = 2') Left: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'x') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') Next (Rethrow) Block[null] } Block[B3] - Exit Predecessors: [B1] Statements (0) "; VerifyFlowGraphForTest<BlockSyntax>(compilation, expectedGraph); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void ThrowFlow_16() { var source = @" class C { void F(System.Exception ex, bool a) /*<bind>*/{ if (a) goto label1; label1: throw ex; }/*</bind>*/ }"; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics(); string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Block[B1] - Block Predecessors: [B0] Statements (0) Jump if False (Regular) to Block[B2] IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'a') Next (Regular) Block[B2] Block[B2] - Block Predecessors: [B1*2] Statements (0) Next (Throw) Block[null] IParameterReferenceOperation: ex (OperationKind.ParameterReference, Type: System.Exception) (Syntax: 'ex') Block[B3] - Exit [UnReachable] Predecessors (0) Statements (0) "; VerifyFlowGraphForTest<BlockSyntax>(compilation, expectedGraph); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void ThrowFlow_17() { var source = @" class C { void F(int x, bool a) /*<bind>*/{ try { x = 1; } catch { if (a) goto label1; label1: throw; } }/*</bind>*/ }"; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics(); string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} .try {R1, R2} { Block[B1] - Block Predecessors: [B0] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'x = 1;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'x = 1') Left: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'x') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Next (Regular) Block[B3] Leaving: {R2} {R1} } .catch {R3} (System.Object) { Block[B2] - Block Predecessors (0) Statements (0) Jump if False (Rethrow) to Block[null] IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'a') Next (Rethrow) Block[null] } Block[B3] - Exit Predecessors: [B1] Statements (0) "; VerifyFlowGraphForTest<BlockSyntax>(compilation, expectedGraph); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void ThrowFlow_18() { var source = @" #pragma warning disable CS0168 #pragma warning disable CS0219 class C { void F(System.Exception ex) /*<bind>*/{ { int x = 1; } throw ex; }/*</bind>*/ }"; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics(); string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { Locals: [System.Int32 x] Block[B1] - Block Predecessors: [B0] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'x = 1') Left: ILocalReferenceOperation: x (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsImplicit) (Syntax: 'x = 1') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Next (Regular) Block[B2] Leaving: {R1} } Block[B2] - Block Predecessors: [B1] Statements (0) Next (Throw) Block[null] IParameterReferenceOperation: ex (OperationKind.ParameterReference, Type: System.Exception) (Syntax: 'ex') Block[B3] - Exit [UnReachable] Predecessors (0) Statements (0) "; VerifyFlowGraphForTest<BlockSyntax>(compilation, expectedGraph); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void ThrowFlow_19() { var source = @" #pragma warning disable CS0168 #pragma warning disable CS0219 class C { void F(int x) /*<bind>*/{ try { x = 1; } catch { { int y = 1; } throw; } }/*</bind>*/ }"; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics(); string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} .try {R1, R2} { Block[B1] - Block Predecessors: [B0] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'x = 1;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'x = 1') Left: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'x') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Next (Regular) Block[B4] Leaving: {R2} {R1} } .catch {R3} (System.Object) { .locals {R4} { Locals: [System.Int32 y] Block[B2] - Block Predecessors (0) Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'y = 1') Left: ILocalReferenceOperation: y (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsImplicit) (Syntax: 'y = 1') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Next (Regular) Block[B3] Leaving: {R4} } Block[B3] - Block Predecessors: [B2] Statements (0) Next (Rethrow) Block[null] } Block[B4] - Exit Predecessors: [B1] Statements (0) "; VerifyFlowGraphForTest<BlockSyntax>(compilation, expectedGraph); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void ThrowFlow_20() { var source = @" class C { void F(System.Exception ex, int x) /*<bind>*/{ try { x = 1; } catch { label1: throw ex; x = 2; goto label1; } }/*</bind>*/ }"; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (14,13): warning CS0162: Unreachable code detected // x = 2; Diagnostic(ErrorCode.WRN_UnreachableCode, "x").WithLocation(14, 13) ); string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} .try {R1, R2} { Block[B1] - Block Predecessors: [B0] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'x = 1;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'x = 1') Left: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'x') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Next (Regular) Block[B4] Leaving: {R2} {R1} } .catch {R3} (System.Object) { Block[B2] - Block Predecessors: [B3] Statements (0) Next (Throw) Block[null] IParameterReferenceOperation: ex (OperationKind.ParameterReference, Type: System.Exception) (Syntax: 'ex') Block[B3] - Block [UnReachable] Predecessors (0) Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'x = 2;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'x = 2') Left: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'x') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') Next (Regular) Block[B2] } Block[B4] - Exit Predecessors: [B1] Statements (0) "; VerifyFlowGraphForTest<BlockSyntax>(compilation, expectedGraph); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void ThrowFlow_21() { var source = @" class C { void F(int x) /*<bind>*/{ try { x = 1; } catch { label1: throw; x = 2; goto label1; } }/*</bind>*/ }"; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (14,13): warning CS0162: Unreachable code detected // x = 2; Diagnostic(ErrorCode.WRN_UnreachableCode, "x").WithLocation(14, 13) ); string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} .try {R1, R2} { Block[B1] - Block Predecessors: [B0] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'x = 1;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'x = 1') Left: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'x') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Next (Regular) Block[B4] Leaving: {R2} {R1} } .catch {R3} (System.Object) { Block[B2] - Block Predecessors: [B3] Statements (0) Next (Rethrow) Block[null] Block[B3] - Block [UnReachable] Predecessors (0) Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'x = 2;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'x = 2') Left: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'x') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') Next (Regular) Block[B2] } Block[B4] - Exit Predecessors: [B1] Statements (0) "; VerifyFlowGraphForTest<BlockSyntax>(compilation, expectedGraph); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void ThrowFlow_22() { var source = @" class C { int F(bool a, System.Exception ex1, System.Exception ex2) /*<bind>*/{ if (a) throw ex1; goto label1; label1: goto label2; label2: throw ex2; }/*</bind>*/ }"; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics(); string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Block[B1] - Block Predecessors: [B0] Statements (0) Jump if False (Regular) to Block[B3] IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'a') Next (Regular) Block[B2] Block[B2] - Block Predecessors: [B1] Statements (0) Next (Throw) Block[null] IParameterReferenceOperation: ex1 (OperationKind.ParameterReference, Type: System.Exception) (Syntax: 'ex1') Block[B3] - Block Predecessors: [B1] Statements (0) Next (Throw) Block[null] IParameterReferenceOperation: ex2 (OperationKind.ParameterReference, Type: System.Exception) (Syntax: 'ex2') Block[B4] - Exit [UnReachable] Predecessors (0) Statements (0) "; VerifyFlowGraphForTest<BlockSyntax>(compilation, expectedGraph); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void ThrowFlow_23() { var source = @" class C { void F(int x, System.Exception ex1, System.Exception ex2, bool a) /*<bind>*/{ x = 1; goto label2; label1: if (a) throw ex1; throw ex2; label2: goto label1; }/*</bind>*/ }"; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics(); string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Block[B1] - Block Predecessors: [B0] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'x = 1;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'x = 1') Left: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'x') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Jump if False (Regular) to Block[B3] IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'a') Next (Regular) Block[B2] Block[B2] - Block Predecessors: [B1] Statements (0) Next (Throw) Block[null] IParameterReferenceOperation: ex1 (OperationKind.ParameterReference, Type: System.Exception) (Syntax: 'ex1') Block[B3] - Block Predecessors: [B1] Statements (0) Next (Throw) Block[null] IParameterReferenceOperation: ex2 (OperationKind.ParameterReference, Type: System.Exception) (Syntax: 'ex2') Block[B4] - Exit [UnReachable] Predecessors (0) Statements (0) "; VerifyFlowGraphForTest<BlockSyntax>(compilation, expectedGraph); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void ThrowFlow_24() { var source = @" class C { void F(int x, bool a) /*<bind>*/{ try { x = 1; } catch { x = 2; goto label2; label1: if (a) throw; throw; label2: goto label1; } }/*</bind>*/ }"; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics(); string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} .try {R1, R2} { Block[B1] - Block Predecessors: [B0] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'x = 1;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'x = 1') Left: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'x') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Next (Regular) Block[B3] Leaving: {R2} {R1} } .catch {R3} (System.Object) { Block[B2] - Block Predecessors (0) Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'x = 2;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'x = 2') Left: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'x') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') Jump if False (Rethrow) to Block[null] IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'a') Next (Rethrow) Block[null] } Block[B3] - Exit Predecessors: [B1] Statements (0) "; VerifyFlowGraphForTest<BlockSyntax>(compilation, expectedGraph); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void ThrowFlow_25() { var source = @" class C { void F(int x, bool a) /*<bind>*/{ try { x = 1; } catch { x = 2; goto label2; label1: if (a) throw; return; label2: goto label1; } }/*</bind>*/ }"; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics(); string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} .try {R1, R2} { Block[B1] - Block Predecessors: [B0] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'x = 1;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'x = 1') Left: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'x') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Next (Regular) Block[B3] Leaving: {R2} {R1} } .catch {R3} (System.Object) { Block[B2] - Block Predecessors (0) Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'x = 2;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'x = 2') Left: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'x') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') Jump if False (Regular) to Block[B3] IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'a') Leaving: {R3} {R1} Next (Rethrow) Block[null] } Block[B3] - Exit Predecessors: [B1] [B2] Statements (0) "; VerifyFlowGraphForTest<BlockSyntax>(compilation, expectedGraph); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void ThrowFlow_26() { var source = @" class C { void F(int x, bool a) /*<bind>*/{ try { x = 1; } catch { x = 2; goto label2; label1: if (a) return; throw; label2: goto label1; } }/*</bind>*/ }"; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics(); string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} .try {R1, R2} { Block[B1] - Block Predecessors: [B0] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'x = 1;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'x = 1') Left: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'x') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Next (Regular) Block[B3] Leaving: {R2} {R1} } .catch {R3} (System.Object) { Block[B2] - Block Predecessors (0) Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'x = 2;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'x = 2') Left: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'x') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') Jump if False (Rethrow) to Block[null] IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'a') Next (Regular) Block[B3] Leaving: {R3} {R1} } Block[B3] - Exit Predecessors: [B1] [B2] Statements (0) "; VerifyFlowGraphForTest<BlockSyntax>(compilation, expectedGraph); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void ThrowFlow_27() { var source = @" class C { void F(int u) /*<bind>*/{ try { u = 1; } finally { throw; } }/*</bind>*/ }"; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (12,13): error CS0156: A throw statement with no arguments is not allowed outside of a catch clause // throw; Diagnostic(ErrorCode.ERR_BadEmptyThrow, "throw").WithLocation(12, 13) ); string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} .try {R1, R2} { Block[B1] - Block Predecessors: [B0] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'u = 1;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'u = 1') Left: IParameterReferenceOperation: u (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'u') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Next (Regular) Block[B3] Finalizing: {R3} Leaving: {R2} {R1} } .finally {R3} { Block[B2] - Block Predecessors (0) Statements (0) Next (Rethrow) Block[null] } Block[B3] - Exit [UnReachable] Predecessors: [B1] Statements (0) "; VerifyFlowGraphForTest<BlockSyntax>(compilation, expectedGraph); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void ThrowFlow_28() { var source = @" class C { void F(int u, System.Exception ex) /*<bind>*/{ try { u = 1; } finally { throw ex; } }/*</bind>*/ }"; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics(); string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} .try {R1, R2} { Block[B1] - Block Predecessors: [B0] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'u = 1;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'u = 1') Left: IParameterReferenceOperation: u (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'u') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Next (Regular) Block[B3] Finalizing: {R3} Leaving: {R2} {R1} } .finally {R3} { Block[B2] - Block Predecessors (0) Statements (0) Next (Throw) Block[null] IParameterReferenceOperation: ex (OperationKind.ParameterReference, Type: System.Exception) (Syntax: 'ex') } Block[B3] - Exit [UnReachable] Predecessors: [B1] Statements (0) "; VerifyFlowGraphForTest<BlockSyntax>(compilation, expectedGraph); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void ThrowFlow_29() { var source = @" class C { void F(System.Exception a, System.Exception b) /*<bind>*/{ throw a ?? b; }/*</bind>*/ }"; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics(); string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} .locals {R1} { CaptureIds: [1] .locals {R2} { CaptureIds: [0] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'a') Value: IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Exception) (Syntax: 'a') Jump if True (Regular) to Block[B3] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'a') Operand: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Exception, IsImplicit) (Syntax: 'a') Leaving: {R2} Next (Regular) Block[B2] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'a') Value: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Exception, IsImplicit) (Syntax: 'a') Next (Regular) Block[B4] Leaving: {R2} } Block[B3] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'b') Value: IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Exception) (Syntax: 'b') Next (Regular) Block[B4] Block[B4] - Block Predecessors: [B2] [B3] Statements (0) Next (Throw) Block[null] IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Exception, IsImplicit) (Syntax: 'a ?? b') } Block[B5] - Exit [UnReachable] Predecessors (0) Statements (0) "; VerifyFlowGraphForTest<BlockSyntax>(compilation, expectedGraph); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void ThrowFlow_30() { var source = @" class C { void F(bool x, bool y, bool z, System.Exception ex) /*<bind>*/{ x = y ? z : throw ex; }/*</bind>*/ }"; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics(); string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'x') Value: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'x') Jump if False (Regular) to Block[B2] IParameterReferenceOperation: y (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'y') Next (Regular) Block[B3] Block[B2] - Block Predecessors: [B1] Statements (0) Next (Throw) Block[null] IParameterReferenceOperation: ex (OperationKind.ParameterReference, Type: System.Exception) (Syntax: 'ex') Block[B3] - Block Predecessors: [B1] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'x = y ? z : throw ex;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'x = y ? z : throw ex') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Boolean, IsImplicit) (Syntax: 'x') Right: IParameterReferenceOperation: z (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'z') Next (Regular) Block[B4] Leaving: {R1} } Block[B4] - Exit Predecessors: [B3] Statements (0) "; VerifyFlowGraphForTest<BlockSyntax>(compilation, expectedGraph); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void ThrowFlow_31() { var source = @" class C { void F(bool x, bool y, bool z, System.Exception ex) /*<bind>*/{ x = y ? throw ex : z; }/*</bind>*/ }"; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics(); string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'x') Value: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'x') Jump if False (Regular) to Block[B3] IParameterReferenceOperation: y (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'y') Next (Regular) Block[B2] Block[B2] - Block Predecessors: [B1] Statements (0) Next (Throw) Block[null] IParameterReferenceOperation: ex (OperationKind.ParameterReference, Type: System.Exception) (Syntax: 'ex') Block[B3] - Block Predecessors: [B1] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'x = y ? throw ex : z;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'x = y ? throw ex : z') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Boolean, IsImplicit) (Syntax: 'x') Right: IParameterReferenceOperation: z (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'z') Next (Regular) Block[B4] Leaving: {R1} } Block[B4] - Exit Predecessors: [B3] Statements (0) "; VerifyFlowGraphForTest<BlockSyntax>(compilation, expectedGraph); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void ThrowFlow_32_Regular8() { var source = @" class C { void F(bool x, bool y, System.Exception ex1, System.Exception ex2) /*<bind>*/{ x = y ? throw ex1 : throw ex2; }/*</bind>*/ }"; var compilation = CreateCompilation(source, parseOptions: TestOptions.Regular8); compilation.VerifyDiagnostics( // (6,13): error CS8957: Conditional expression is not valid in language version 8.0 because a common type was not found between '<throw expression>' and '<throw expression>'. To use a target-typed conversion, upgrade to language version 9.0 or greater. // x = y ? throw ex1 : throw ex2; Diagnostic(ErrorCode.ERR_NoImplicitConvTargetTypedConditional, "y ? throw ex1 : throw ex2").WithArguments("8.0", "<throw expression>", "<throw expression>", "9.0").WithLocation(6, 13) ); string expectedOperationTree = @" IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsInvalid) (Syntax: '{ ... }') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid) (Syntax: 'x = y ? thr ... throw ex2;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean, IsInvalid) (Syntax: 'x = y ? thr ... : throw ex2') Left: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'x') Right: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Boolean, IsInvalid, IsImplicit) (Syntax: 'y ? throw e ... : throw ex2') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: IConditionalOperation (OperationKind.Conditional, Type: System.Boolean, IsInvalid) (Syntax: 'y ? throw e ... : throw ex2') Condition: IParameterReferenceOperation: y (OperationKind.ParameterReference, Type: System.Boolean, IsInvalid) (Syntax: 'y') WhenTrue: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Boolean, IsInvalid, IsImplicit) (Syntax: 'throw ex1') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: IThrowOperation (OperationKind.Throw, Type: null, IsInvalid) (Syntax: 'throw ex1') IParameterReferenceOperation: ex1 (OperationKind.ParameterReference, Type: System.Exception, IsInvalid) (Syntax: 'ex1') WhenFalse: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Boolean, IsInvalid, IsImplicit) (Syntax: 'throw ex2') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: IThrowOperation (OperationKind.Throw, Type: null, IsInvalid) (Syntax: 'throw ex2') IParameterReferenceOperation: ex2 (OperationKind.ParameterReference, Type: System.Exception, IsInvalid) (Syntax: 'ex2') "; VerifyOperationTreeForTest<BlockSyntax>(compilation, expectedOperationTree); string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'x') Value: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'x') Jump if False (Regular) to Block[B3] IParameterReferenceOperation: y (OperationKind.ParameterReference, Type: System.Boolean, IsInvalid) (Syntax: 'y') Next (Regular) Block[B2] Block[B2] - Block Predecessors: [B1] Statements (0) Next (Throw) Block[null] IParameterReferenceOperation: ex1 (OperationKind.ParameterReference, Type: System.Exception, IsInvalid) (Syntax: 'ex1') Block[B3] - Block Predecessors: [B1] Statements (0) Next (Throw) Block[null] IParameterReferenceOperation: ex2 (OperationKind.ParameterReference, Type: System.Exception, IsInvalid) (Syntax: 'ex2') Block[B4] - Block [UnReachable] Predecessors (0) Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid) (Syntax: 'x = y ? thr ... throw ex2;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean, IsInvalid) (Syntax: 'x = y ? thr ... : throw ex2') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Boolean, IsImplicit) (Syntax: 'x') Right: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Boolean, IsInvalid, IsImplicit) (Syntax: 'y ? throw e ... : throw ex2') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) (ConditionalExpression) Operand: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Boolean, IsInvalid, IsImplicit) (Syntax: 'throw ex2') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) (ImplicitThrow) Operand: IOperation: (OperationKind.None, Type: null, IsInvalid, IsImplicit) (Syntax: 'throw ex2') Next (Regular) Block[B5] Leaving: {R1} } Block[B5] - Exit [UnReachable] Predecessors: [B4] Statements (0) "; VerifyFlowGraphForTest<BlockSyntax>(compilation, expectedGraph); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void ThrowFlow_32_TargetTypedConditional() { var source = @" class C { void F(bool x, bool y, System.Exception ex1, System.Exception ex2) /*<bind>*/{ x = y ? throw ex1 : throw ex2; }/*</bind>*/ }"; var compilation = CreateCompilation(source, parseOptions: TestOptions.Regular.WithLanguageVersion(MessageID.IDS_FeatureTargetTypedConditional.RequiredVersion())); compilation.VerifyDiagnostics(); string expectedOperationTree = @" IBlockOperation (1 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'x = y ? thr ... throw ex2;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'x = y ? thr ... : throw ex2') Left: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'x') Right: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Boolean, IsImplicit) (Syntax: 'y ? throw e ... : throw ex2') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: IConditionalOperation (OperationKind.Conditional, Type: System.Boolean) (Syntax: 'y ? throw e ... : throw ex2') Condition: IParameterReferenceOperation: y (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'y') WhenTrue: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Boolean, IsImplicit) (Syntax: 'throw ex1') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: IThrowOperation (OperationKind.Throw, Type: null) (Syntax: 'throw ex1') IParameterReferenceOperation: ex1 (OperationKind.ParameterReference, Type: System.Exception) (Syntax: 'ex1') WhenFalse: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Boolean, IsImplicit) (Syntax: 'throw ex2') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: IThrowOperation (OperationKind.Throw, Type: null) (Syntax: 'throw ex2') IParameterReferenceOperation: ex2 (OperationKind.ParameterReference, Type: System.Exception) (Syntax: 'ex2') "; VerifyOperationTreeForTest<BlockSyntax>(compilation, expectedOperationTree); string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'x') Value: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'x') Jump if False (Regular) to Block[B3] IParameterReferenceOperation: y (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'y') Next (Regular) Block[B2] Block[B2] - Block Predecessors: [B1] Statements (0) Next (Throw) Block[null] IParameterReferenceOperation: ex1 (OperationKind.ParameterReference, Type: System.Exception) (Syntax: 'ex1') Block[B3] - Block Predecessors: [B1] Statements (0) Next (Throw) Block[null] IParameterReferenceOperation: ex2 (OperationKind.ParameterReference, Type: System.Exception) (Syntax: 'ex2') Block[B4] - Block [UnReachable] Predecessors (0) Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'x = y ? thr ... throw ex2;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'x = y ? thr ... : throw ex2') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Boolean, IsImplicit) (Syntax: 'x') Right: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Boolean, IsImplicit) (Syntax: 'y ? throw e ... : throw ex2') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) (ConditionalExpression) Operand: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Boolean, IsImplicit) (Syntax: 'throw ex2') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) (ImplicitThrow) Operand: IOperation: (OperationKind.None, Type: null, IsImplicit) (Syntax: 'throw ex2') Next (Regular) Block[B5] Leaving: {R1} } Block[B5] - Exit [UnReachable] Predecessors: [B4] Statements (0) "; VerifyFlowGraphForTest<BlockSyntax>(compilation, expectedGraph); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void ThrowFlow_33() { var source = @" class C { void F(object x, bool y, object u, object v, System.Exception ex) /*<bind>*/{ x = y ? (u ?? v) : throw ex; }/*</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: 'x') Value: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'x') Jump if False (Regular) to Block[B5] IParameterReferenceOperation: y (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'y') 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: 'u') Value: IParameterReferenceOperation: u (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'u') Jump if True (Regular) to Block[B4] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'u') Operand: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'u') Leaving: {R2} Next (Regular) Block[B3] Block[B3] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'u') Value: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'u') Next (Regular) Block[B6] Leaving: {R2} } Block[B4] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'v') Value: IParameterReferenceOperation: v (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'v') Next (Regular) Block[B6] Block[B5] - Block Predecessors: [B1] Statements (0) Next (Throw) Block[null] IParameterReferenceOperation: ex (OperationKind.ParameterReference, Type: System.Exception) (Syntax: 'ex') Block[B6] - Block Predecessors: [B3] [B4] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'x = y ? (u ... : throw ex;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Object) (Syntax: 'x = y ? (u ... : throw ex') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'x') Right: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'u ?? v') Next (Regular) Block[B7] Leaving: {R1} } Block[B7] - Exit Predecessors: [B6] Statements (0) "; VerifyFlowGraphForTest<BlockSyntax>(compilation, expectedGraph); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void ThrowFlow_34() { var source = @" class C { void F(object x, bool y, object u, object v, System.Exception ex) /*<bind>*/{ x = y ? throw ex : (u ?? v); }/*</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: 'x') Value: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'x') Jump if False (Regular) to Block[B3] IParameterReferenceOperation: y (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'y') Entering: {R2} Next (Regular) Block[B2] Block[B2] - Block Predecessors: [B1] Statements (0) Next (Throw) Block[null] IParameterReferenceOperation: ex (OperationKind.ParameterReference, Type: System.Exception) (Syntax: 'ex') .locals {R2} { CaptureIds: [1] Block[B3] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'u') Value: IParameterReferenceOperation: u (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'u') Jump if True (Regular) to Block[B5] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'u') Operand: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'u') Leaving: {R2} Next (Regular) Block[B4] Block[B4] - Block Predecessors: [B3] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'u') Value: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'u') Next (Regular) Block[B6] Leaving: {R2} } Block[B5] - Block Predecessors: [B3] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'v') Value: IParameterReferenceOperation: v (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'v') Next (Regular) Block[B6] Block[B6] - Block Predecessors: [B4] [B5] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'x = y ? thr ... : (u ?? v);') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Object) (Syntax: 'x = y ? thr ... : (u ?? v)') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'x') Right: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'u ?? v') Next (Regular) Block[B7] Leaving: {R1} } Block[B7] - Exit Predecessors: [B6] Statements (0) "; VerifyFlowGraphForTest<BlockSyntax>(compilation, expectedGraph); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET 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.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public class IOperationTests_IThrowOperation : SemanticModelTestBase { [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void ThrowFlow_01() { var source = @" class C { void F() /*<bind>*/{ throw; }/*</bind>*/ }"; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (6,9): error CS0156: A throw statement with no arguments is not allowed outside of a catch clause // throw; Diagnostic(ErrorCode.ERR_BadEmptyThrow, "throw").WithLocation(6, 9) ); string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Block[B1] - Block Predecessors: [B0] Statements (0) Next (Rethrow) Block[null] Block[B2] - Exit [UnReachable] Predecessors (0) Statements (0) "; VerifyFlowGraphForTest<BlockSyntax>(compilation, expectedGraph); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void ThrowFlow_02() { var source = @" class C { void F(int x) /*<bind>*/{ x = 1; throw; x = 2; }/*</bind>*/ }"; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (7,9): error CS0156: A throw statement with no arguments is not allowed outside of a catch clause // throw; Diagnostic(ErrorCode.ERR_BadEmptyThrow, "throw").WithLocation(7, 9), // (8,9): warning CS0162: Unreachable code detected // x = 2; Diagnostic(ErrorCode.WRN_UnreachableCode, "x").WithLocation(8, 9) ); string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Block[B1] - Block Predecessors: [B0] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'x = 1;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'x = 1') Left: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'x') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Next (Rethrow) Block[null] Block[B2] - Block [UnReachable] Predecessors (0) Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'x = 2;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'x = 2') Left: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'x') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') Next (Regular) Block[B3] Block[B3] - Exit [UnReachable] Predecessors: [B2] Statements (0) "; VerifyFlowGraphForTest<BlockSyntax>(compilation, expectedGraph); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void ThrowFlow_03() { var source = @" class C { void F(System.Exception ex) /*<bind>*/{ throw ex; }/*</bind>*/ }"; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics(); string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Block[B1] - Block Predecessors: [B0] Statements (0) Next (Throw) Block[null] IParameterReferenceOperation: ex (OperationKind.ParameterReference, Type: System.Exception) (Syntax: 'ex') Block[B2] - Exit [UnReachable] Predecessors (0) Statements (0) "; VerifyFlowGraphForTest<BlockSyntax>(compilation, expectedGraph); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void ThrowFlow_04() { var source = @" class C { void F(System.Exception ex) /*<bind>*/{ int x = 1; throw ex; x = 2; }/*</bind>*/ }"; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (8,9): warning CS0162: Unreachable code detected // x = 2; Diagnostic(ErrorCode.WRN_UnreachableCode, "x").WithLocation(8, 9), // (6,13): warning CS0219: The variable 'x' is assigned but its value is never used // int x = 1; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "x").WithArguments("x").WithLocation(6, 13) ); string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { Locals: [System.Int32 x] Block[B1] - Block Predecessors: [B0] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'x = 1') Left: ILocalReferenceOperation: x (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsImplicit) (Syntax: 'x = 1') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Next (Throw) Block[null] IParameterReferenceOperation: ex (OperationKind.ParameterReference, Type: System.Exception) (Syntax: 'ex') Block[B2] - Block [UnReachable] Predecessors (0) Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'x = 2;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'x = 2') Left: ILocalReferenceOperation: x (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'x') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') Next (Regular) Block[B3] Leaving: {R1} } Block[B3] - Exit [UnReachable] Predecessors: [B2] Statements (0) "; VerifyFlowGraphForTest<BlockSyntax>(compilation, expectedGraph); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void ThrowFlow_05() { var source = @" class C { void F(int x, System.Exception ex) /*<bind>*/{ x = throw ex + x; }/*</bind>*/ }"; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (6,13): error CS8115: A throw expression is not allowed in this context. // x = throw ex + x; Diagnostic(ErrorCode.ERR_ThrowMisplaced, "throw").WithLocation(6, 13), // (6,19): error CS0019: Operator '+' cannot be applied to operands of type 'Exception' and 'int' // x = throw ex + x; Diagnostic(ErrorCode.ERR_BadBinaryOps, "ex + x").WithArguments("+", "System.Exception", "int").WithLocation(6, 19) ); string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'x') Value: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'x') Next (Throw) Block[null] IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Exception, IsInvalid, IsImplicit) (Syntax: 'ex + x') Conversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) (NoConversion) Operand: IBinaryOperation (BinaryOperatorKind.Add) (OperationKind.Binary, Type: ?, IsInvalid) (Syntax: 'ex + x') Left: IParameterReferenceOperation: ex (OperationKind.ParameterReference, Type: System.Exception, IsInvalid) (Syntax: 'ex') Right: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Int32, IsInvalid) (Syntax: 'x') Block[B2] - Block [UnReachable] Predecessors (0) Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid) (Syntax: 'x = throw ex + x;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsInvalid) (Syntax: 'x = throw ex + x') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'x') Right: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'throw ex + x') Conversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) (NoConversion) Operand: IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid, IsImplicit) (Syntax: 'throw ex + x') Children(1): IOperation: (OperationKind.None, Type: null, IsInvalid, IsImplicit) (Syntax: 'throw ex + x') Next (Regular) Block[B3] Leaving: {R1} } Block[B3] - Exit [UnReachable] Predecessors: [B2] Statements (0) "; VerifyFlowGraphForTest<BlockSyntax>(compilation, expectedGraph); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void ThrowFlow_06() { var source = @" class C { void F(int x, System.Exception ex) /*<bind>*/{ x = (throw ex) + x; }/*</bind>*/ }"; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (6,14): error CS8115: A throw expression is not allowed in this context. // x = (throw ex) + x; Diagnostic(ErrorCode.ERR_ThrowMisplaced, "throw").WithLocation(6, 14) ); string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'x') Value: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'x') Next (Throw) Block[null] IParameterReferenceOperation: ex (OperationKind.ParameterReference, Type: System.Exception) (Syntax: 'ex') Block[B2] - Block [UnReachable] Predecessors (0) Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid) (Syntax: 'x = (throw ex) + x;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsInvalid) (Syntax: 'x = (throw ex) + x') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'x') Right: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: '(throw ex) + x') Conversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) (NoConversion) Operand: IBinaryOperation (BinaryOperatorKind.Add) (OperationKind.Binary, Type: ?, IsInvalid) (Syntax: '(throw ex) + x') Left: IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid, IsImplicit) (Syntax: 'throw ex') Children(1): IOperation: (OperationKind.None, Type: null, IsInvalid, IsImplicit) (Syntax: 'throw ex') Right: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'x') Next (Regular) Block[B3] Leaving: {R1} } Block[B3] - Exit [UnReachable] Predecessors: [B2] Statements (0) "; VerifyFlowGraphForTest<BlockSyntax>(compilation, expectedGraph); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void ThrowFlow_07() { var source = @" class C { void F(int x, System.Exception ex) /*<bind>*/{ x = x + throw ex; }/*</bind>*/ }"; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (6,17): error CS1525: Invalid expression term 'throw' // x = x + throw ex; Diagnostic(ErrorCode.ERR_InvalidExprTerm, "throw ex").WithArguments("throw").WithLocation(6, 17) ); string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] [1] Block[B1] - Block Predecessors: [B0] Statements (2) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'x') Value: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'x') IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'x') Value: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'x') Next (Throw) Block[null] IParameterReferenceOperation: ex (OperationKind.ParameterReference, Type: System.Exception, IsInvalid) (Syntax: 'ex') Block[B2] - Block [UnReachable] Predecessors (0) Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid) (Syntax: 'x = x + throw ex;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsInvalid) (Syntax: 'x = x + throw ex') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'x') Right: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'x + throw ex') Conversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) (NoConversion) Operand: IBinaryOperation (BinaryOperatorKind.Add) (OperationKind.Binary, Type: ?, IsInvalid) (Syntax: 'x + throw ex') Left: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'x') Right: IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid, IsImplicit) (Syntax: 'throw ex') Children(1): IOperation: (OperationKind.None, Type: null, IsInvalid, IsImplicit) (Syntax: 'throw ex') Next (Regular) Block[B3] Leaving: {R1} } Block[B3] - Exit [UnReachable] Predecessors: [B2] Statements (0) "; VerifyFlowGraphForTest<BlockSyntax>(compilation, expectedGraph); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void ThrowFlow_08() { var source = @" class C { void F(int x, System.Exception ex) /*<bind>*/{ x = x + (throw ex); }/*</bind>*/ }"; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (6,18): error CS8115: A throw expression is not allowed in this context. // x = x + (throw ex); Diagnostic(ErrorCode.ERR_ThrowMisplaced, "throw").WithLocation(6, 18) ); string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] [1] Block[B1] - Block Predecessors: [B0] Statements (2) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'x') Value: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'x') IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'x') Value: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'x') Next (Throw) Block[null] IParameterReferenceOperation: ex (OperationKind.ParameterReference, Type: System.Exception) (Syntax: 'ex') Block[B2] - Block [UnReachable] Predecessors (0) Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid) (Syntax: 'x = x + (throw ex);') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsInvalid) (Syntax: 'x = x + (throw ex)') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'x') Right: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'x + (throw ex)') Conversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) (NoConversion) Operand: IBinaryOperation (BinaryOperatorKind.Add) (OperationKind.Binary, Type: ?, IsInvalid) (Syntax: 'x + (throw ex)') Left: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'x') Right: IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid, IsImplicit) (Syntax: 'throw ex') Children(1): IOperation: (OperationKind.None, Type: null, IsInvalid, IsImplicit) (Syntax: 'throw ex') Next (Regular) Block[B3] Leaving: {R1} } Block[B3] - Exit [UnReachable] Predecessors: [B2] Statements (0) "; VerifyFlowGraphForTest<BlockSyntax>(compilation, expectedGraph); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void ThrowFlow_09() { var source = @" class C { void F(object x, object y, System.Exception ex) /*<bind>*/{ x = y ?? throw ex; }/*</bind>*/ }"; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics(); string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] [1] Block[B1] - Block Predecessors: [B0] Statements (2) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'x') Value: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'x') IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'y') Value: IParameterReferenceOperation: y (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'y') Jump if True (Regular) to Block[B2] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'y') Operand: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'y') Next (Regular) Block[B3] Block[B2] - Block Predecessors: [B1] Statements (0) Next (Throw) Block[null] IParameterReferenceOperation: ex (OperationKind.ParameterReference, Type: System.Exception) (Syntax: 'ex') Block[B3] - Block Predecessors: [B1] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'x = y ?? throw ex;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Object) (Syntax: 'x = y ?? throw ex') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'x') Right: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'y') Next (Regular) Block[B4] Leaving: {R1} } Block[B4] - Exit Predecessors: [B3] Statements (0) "; VerifyFlowGraphForTest<BlockSyntax>(compilation, expectedGraph); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void ThrowFlow_10() { var source = @" class C { void F(object x, object y, object z, System.Exception ex) /*<bind>*/{ M(x, y ?? throw ex, z); }/*</bind>*/ static void M(object x, object y, object z){} }"; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics(); string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] [1] Block[B1] - Block Predecessors: [B0] Statements (2) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'x') Value: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'x') IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'y') Value: IParameterReferenceOperation: y (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'y') Jump if True (Regular) to Block[B2] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'y') Operand: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'y') Next (Regular) Block[B3] Block[B2] - Block Predecessors: [B1] Statements (0) Next (Throw) Block[null] IParameterReferenceOperation: ex (OperationKind.ParameterReference, Type: System.Exception) (Syntax: 'ex') Block[B3] - Block Predecessors: [B1] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'M(x, y ?? throw ex, z);') Expression: IInvocationOperation (void C.M(System.Object x, System.Object y, System.Object z)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'M(x, y ?? throw ex, z)') Instance Receiver: null Arguments(3): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null) (Syntax: 'x') IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'x') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: y) (OperationKind.Argument, Type: null) (Syntax: 'y ?? throw ex') IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'y') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: z) (OperationKind.Argument, Type: null) (Syntax: 'z') IParameterReferenceOperation: z (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'z') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Next (Regular) Block[B4] Leaving: {R1} } Block[B4] - Exit Predecessors: [B3] Statements (0) "; VerifyFlowGraphForTest<BlockSyntax>(compilation, expectedGraph); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void ThrowFlow_11() { var source = @" class C { void F(int u) /*<bind>*/{ try { u = 1; } catch { throw; } }/*</bind>*/ static void M(object x, object y, object z){} }"; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics(); string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} .try {R1, R2} { Block[B1] - Block Predecessors: [B0] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'u = 1;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'u = 1') Left: IParameterReferenceOperation: u (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'u') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Next (Regular) Block[B3] Leaving: {R2} {R1} } .catch {R3} (System.Object) { Block[B2] - Block Predecessors (0) Statements (0) Next (Rethrow) Block[null] } Block[B3] - Exit Predecessors: [B1] Statements (0) "; VerifyFlowGraphForTest<BlockSyntax>(compilation, expectedGraph); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void ThrowFlow_12() { var source = @" class C { void F(int u) /*<bind>*/{ try { u = 1; } catch { u = 2; throw; u = 3; } }/*</bind>*/ static void M(object x, object y, object z){} }"; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (14,13): warning CS0162: Unreachable code detected // u = 3; Diagnostic(ErrorCode.WRN_UnreachableCode, "u").WithLocation(14, 13) ); string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} .try {R1, R2} { Block[B1] - Block Predecessors: [B0] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'u = 1;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'u = 1') Left: IParameterReferenceOperation: u (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'u') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Next (Regular) Block[B4] Leaving: {R2} {R1} } .catch {R3} (System.Object) { Block[B2] - Block Predecessors (0) Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'u = 2;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'u = 2') Left: IParameterReferenceOperation: u (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'u') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') Next (Rethrow) Block[null] Block[B3] - Block [UnReachable] Predecessors (0) Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'u = 3;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'u = 3') Left: IParameterReferenceOperation: u (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'u') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 3) (Syntax: '3') Next (Regular) Block[B4] Leaving: {R3} {R1} } Block[B4] - Exit Predecessors: [B1] [B3] Statements (0) "; VerifyFlowGraphForTest<BlockSyntax>(compilation, expectedGraph); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void ThrowFlow_13() { var source = @" class C { void F(object x, object y, object z, int u) /*<bind>*/{ try { u = 1; } catch { M(x, (y ?? throw), z); } }/*</bind>*/ static void M(object x, object y, object z){} } "; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (12,29): error CS1525: Invalid expression term ')' // M(x, (y ?? throw), z); Diagnostic(ErrorCode.ERR_InvalidExprTerm, ")").WithArguments(")").WithLocation(12, 29) ); string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} .try {R1, R2} { Block[B1] - Block Predecessors: [B0] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'u = 1;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'u = 1') Left: IParameterReferenceOperation: u (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'u') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Next (Regular) Block[B8] Leaving: {R2} {R1} } .catch {R3} (System.Object) { CaptureIds: [0] [2] Block[B2] - Block Predecessors (0) Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'x') Value: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'x') Next (Regular) Block[B3] Entering: {R4} .locals {R4} { CaptureIds: [1] Block[B3] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'y') Value: IParameterReferenceOperation: y (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'y') Jump if True (Regular) to Block[B5] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'y') Operand: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'y') Leaving: {R4} Next (Regular) Block[B4] Block[B4] - Block Predecessors: [B3] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'y') Value: IInvalidOperation (OperationKind.Invalid, Type: ?, IsImplicit) (Syntax: 'y') Children(1): IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'y') Next (Regular) Block[B7] Leaving: {R4} } Block[B5] - Block Predecessors: [B3] Statements (0) Next (Throw) Block[null] IInvalidOperation (OperationKind.Invalid, Type: null, IsInvalid) (Syntax: '') Children(0) Block[B6] - Block [UnReachable] Predecessors (0) Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'throw') Value: IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid, IsImplicit) (Syntax: 'throw') Children(1): IOperation: (OperationKind.None, Type: null, IsInvalid, IsImplicit) (Syntax: 'throw') Next (Regular) Block[B7] Block[B7] - Block Predecessors: [B4] [B6] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid) (Syntax: 'M(x, (y ?? throw), z);') Expression: IInvalidOperation (OperationKind.Invalid, Type: System.Void, IsInvalid) (Syntax: 'M(x, (y ?? throw), z)') Children(3): IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'x') IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: ?, IsInvalid, IsImplicit) (Syntax: 'y ?? throw') IParameterReferenceOperation: z (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'z') Next (Regular) Block[B8] Leaving: {R3} {R1} } Block[B8] - Exit Predecessors: [B1] [B7] Statements (0) "; VerifyFlowGraphForTest<BlockSyntax>(compilation, expectedGraph); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void ThrowFlow_14() { var source = @" class C { void F(System.Exception ex) /*<bind>*/{ ex = null; goto label1; label1: throw ex; }/*</bind>*/ }"; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics(); string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Block[B1] - Block Predecessors: [B0] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'ex = null;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Exception) (Syntax: 'ex = null') Left: IParameterReferenceOperation: ex (OperationKind.ParameterReference, Type: System.Exception) (Syntax: 'ex') Right: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Exception, Constant: null, IsImplicit) (Syntax: 'null') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) (ImplicitReference) Operand: ILiteralOperation (OperationKind.Literal, Type: null, Constant: null) (Syntax: 'null') Next (Throw) Block[null] IParameterReferenceOperation: ex (OperationKind.ParameterReference, Type: System.Exception) (Syntax: 'ex') Block[B2] - Exit [UnReachable] Predecessors (0) Statements (0) "; VerifyFlowGraphForTest<BlockSyntax>(compilation, expectedGraph); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void ThrowFlow_15() { var source = @" class C { void F(int x) /*<bind>*/{ try { x = 1; } catch { x = 2; goto label1; label1: throw; } }/*</bind>*/ }"; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics(); string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} .try {R1, R2} { Block[B1] - Block Predecessors: [B0] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'x = 1;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'x = 1') Left: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'x') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Next (Regular) Block[B3] Leaving: {R2} {R1} } .catch {R3} (System.Object) { Block[B2] - Block Predecessors (0) Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'x = 2;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'x = 2') Left: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'x') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') Next (Rethrow) Block[null] } Block[B3] - Exit Predecessors: [B1] Statements (0) "; VerifyFlowGraphForTest<BlockSyntax>(compilation, expectedGraph); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void ThrowFlow_16() { var source = @" class C { void F(System.Exception ex, bool a) /*<bind>*/{ if (a) goto label1; label1: throw ex; }/*</bind>*/ }"; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics(); string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Block[B1] - Block Predecessors: [B0] Statements (0) Jump if False (Regular) to Block[B2] IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'a') Next (Regular) Block[B2] Block[B2] - Block Predecessors: [B1*2] Statements (0) Next (Throw) Block[null] IParameterReferenceOperation: ex (OperationKind.ParameterReference, Type: System.Exception) (Syntax: 'ex') Block[B3] - Exit [UnReachable] Predecessors (0) Statements (0) "; VerifyFlowGraphForTest<BlockSyntax>(compilation, expectedGraph); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void ThrowFlow_17() { var source = @" class C { void F(int x, bool a) /*<bind>*/{ try { x = 1; } catch { if (a) goto label1; label1: throw; } }/*</bind>*/ }"; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics(); string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} .try {R1, R2} { Block[B1] - Block Predecessors: [B0] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'x = 1;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'x = 1') Left: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'x') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Next (Regular) Block[B3] Leaving: {R2} {R1} } .catch {R3} (System.Object) { Block[B2] - Block Predecessors (0) Statements (0) Jump if False (Rethrow) to Block[null] IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'a') Next (Rethrow) Block[null] } Block[B3] - Exit Predecessors: [B1] Statements (0) "; VerifyFlowGraphForTest<BlockSyntax>(compilation, expectedGraph); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void ThrowFlow_18() { var source = @" #pragma warning disable CS0168 #pragma warning disable CS0219 class C { void F(System.Exception ex) /*<bind>*/{ { int x = 1; } throw ex; }/*</bind>*/ }"; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics(); string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { Locals: [System.Int32 x] Block[B1] - Block Predecessors: [B0] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'x = 1') Left: ILocalReferenceOperation: x (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsImplicit) (Syntax: 'x = 1') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Next (Regular) Block[B2] Leaving: {R1} } Block[B2] - Block Predecessors: [B1] Statements (0) Next (Throw) Block[null] IParameterReferenceOperation: ex (OperationKind.ParameterReference, Type: System.Exception) (Syntax: 'ex') Block[B3] - Exit [UnReachable] Predecessors (0) Statements (0) "; VerifyFlowGraphForTest<BlockSyntax>(compilation, expectedGraph); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void ThrowFlow_19() { var source = @" #pragma warning disable CS0168 #pragma warning disable CS0219 class C { void F(int x) /*<bind>*/{ try { x = 1; } catch { { int y = 1; } throw; } }/*</bind>*/ }"; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics(); string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} .try {R1, R2} { Block[B1] - Block Predecessors: [B0] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'x = 1;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'x = 1') Left: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'x') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Next (Regular) Block[B4] Leaving: {R2} {R1} } .catch {R3} (System.Object) { .locals {R4} { Locals: [System.Int32 y] Block[B2] - Block Predecessors (0) Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'y = 1') Left: ILocalReferenceOperation: y (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsImplicit) (Syntax: 'y = 1') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Next (Regular) Block[B3] Leaving: {R4} } Block[B3] - Block Predecessors: [B2] Statements (0) Next (Rethrow) Block[null] } Block[B4] - Exit Predecessors: [B1] Statements (0) "; VerifyFlowGraphForTest<BlockSyntax>(compilation, expectedGraph); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void ThrowFlow_20() { var source = @" class C { void F(System.Exception ex, int x) /*<bind>*/{ try { x = 1; } catch { label1: throw ex; x = 2; goto label1; } }/*</bind>*/ }"; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (14,13): warning CS0162: Unreachable code detected // x = 2; Diagnostic(ErrorCode.WRN_UnreachableCode, "x").WithLocation(14, 13) ); string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} .try {R1, R2} { Block[B1] - Block Predecessors: [B0] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'x = 1;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'x = 1') Left: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'x') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Next (Regular) Block[B4] Leaving: {R2} {R1} } .catch {R3} (System.Object) { Block[B2] - Block Predecessors: [B3] Statements (0) Next (Throw) Block[null] IParameterReferenceOperation: ex (OperationKind.ParameterReference, Type: System.Exception) (Syntax: 'ex') Block[B3] - Block [UnReachable] Predecessors (0) Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'x = 2;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'x = 2') Left: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'x') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') Next (Regular) Block[B2] } Block[B4] - Exit Predecessors: [B1] Statements (0) "; VerifyFlowGraphForTest<BlockSyntax>(compilation, expectedGraph); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void ThrowFlow_21() { var source = @" class C { void F(int x) /*<bind>*/{ try { x = 1; } catch { label1: throw; x = 2; goto label1; } }/*</bind>*/ }"; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (14,13): warning CS0162: Unreachable code detected // x = 2; Diagnostic(ErrorCode.WRN_UnreachableCode, "x").WithLocation(14, 13) ); string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} .try {R1, R2} { Block[B1] - Block Predecessors: [B0] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'x = 1;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'x = 1') Left: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'x') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Next (Regular) Block[B4] Leaving: {R2} {R1} } .catch {R3} (System.Object) { Block[B2] - Block Predecessors: [B3] Statements (0) Next (Rethrow) Block[null] Block[B3] - Block [UnReachable] Predecessors (0) Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'x = 2;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'x = 2') Left: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'x') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') Next (Regular) Block[B2] } Block[B4] - Exit Predecessors: [B1] Statements (0) "; VerifyFlowGraphForTest<BlockSyntax>(compilation, expectedGraph); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void ThrowFlow_22() { var source = @" class C { int F(bool a, System.Exception ex1, System.Exception ex2) /*<bind>*/{ if (a) throw ex1; goto label1; label1: goto label2; label2: throw ex2; }/*</bind>*/ }"; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics(); string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Block[B1] - Block Predecessors: [B0] Statements (0) Jump if False (Regular) to Block[B3] IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'a') Next (Regular) Block[B2] Block[B2] - Block Predecessors: [B1] Statements (0) Next (Throw) Block[null] IParameterReferenceOperation: ex1 (OperationKind.ParameterReference, Type: System.Exception) (Syntax: 'ex1') Block[B3] - Block Predecessors: [B1] Statements (0) Next (Throw) Block[null] IParameterReferenceOperation: ex2 (OperationKind.ParameterReference, Type: System.Exception) (Syntax: 'ex2') Block[B4] - Exit [UnReachable] Predecessors (0) Statements (0) "; VerifyFlowGraphForTest<BlockSyntax>(compilation, expectedGraph); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void ThrowFlow_23() { var source = @" class C { void F(int x, System.Exception ex1, System.Exception ex2, bool a) /*<bind>*/{ x = 1; goto label2; label1: if (a) throw ex1; throw ex2; label2: goto label1; }/*</bind>*/ }"; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics(); string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Block[B1] - Block Predecessors: [B0] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'x = 1;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'x = 1') Left: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'x') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Jump if False (Regular) to Block[B3] IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'a') Next (Regular) Block[B2] Block[B2] - Block Predecessors: [B1] Statements (0) Next (Throw) Block[null] IParameterReferenceOperation: ex1 (OperationKind.ParameterReference, Type: System.Exception) (Syntax: 'ex1') Block[B3] - Block Predecessors: [B1] Statements (0) Next (Throw) Block[null] IParameterReferenceOperation: ex2 (OperationKind.ParameterReference, Type: System.Exception) (Syntax: 'ex2') Block[B4] - Exit [UnReachable] Predecessors (0) Statements (0) "; VerifyFlowGraphForTest<BlockSyntax>(compilation, expectedGraph); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void ThrowFlow_24() { var source = @" class C { void F(int x, bool a) /*<bind>*/{ try { x = 1; } catch { x = 2; goto label2; label1: if (a) throw; throw; label2: goto label1; } }/*</bind>*/ }"; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics(); string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} .try {R1, R2} { Block[B1] - Block Predecessors: [B0] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'x = 1;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'x = 1') Left: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'x') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Next (Regular) Block[B3] Leaving: {R2} {R1} } .catch {R3} (System.Object) { Block[B2] - Block Predecessors (0) Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'x = 2;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'x = 2') Left: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'x') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') Jump if False (Rethrow) to Block[null] IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'a') Next (Rethrow) Block[null] } Block[B3] - Exit Predecessors: [B1] Statements (0) "; VerifyFlowGraphForTest<BlockSyntax>(compilation, expectedGraph); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void ThrowFlow_25() { var source = @" class C { void F(int x, bool a) /*<bind>*/{ try { x = 1; } catch { x = 2; goto label2; label1: if (a) throw; return; label2: goto label1; } }/*</bind>*/ }"; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics(); string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} .try {R1, R2} { Block[B1] - Block Predecessors: [B0] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'x = 1;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'x = 1') Left: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'x') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Next (Regular) Block[B3] Leaving: {R2} {R1} } .catch {R3} (System.Object) { Block[B2] - Block Predecessors (0) Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'x = 2;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'x = 2') Left: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'x') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') Jump if False (Regular) to Block[B3] IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'a') Leaving: {R3} {R1} Next (Rethrow) Block[null] } Block[B3] - Exit Predecessors: [B1] [B2] Statements (0) "; VerifyFlowGraphForTest<BlockSyntax>(compilation, expectedGraph); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void ThrowFlow_26() { var source = @" class C { void F(int x, bool a) /*<bind>*/{ try { x = 1; } catch { x = 2; goto label2; label1: if (a) return; throw; label2: goto label1; } }/*</bind>*/ }"; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics(); string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} .try {R1, R2} { Block[B1] - Block Predecessors: [B0] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'x = 1;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'x = 1') Left: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'x') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Next (Regular) Block[B3] Leaving: {R2} {R1} } .catch {R3} (System.Object) { Block[B2] - Block Predecessors (0) Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'x = 2;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'x = 2') Left: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'x') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') Jump if False (Rethrow) to Block[null] IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'a') Next (Regular) Block[B3] Leaving: {R3} {R1} } Block[B3] - Exit Predecessors: [B1] [B2] Statements (0) "; VerifyFlowGraphForTest<BlockSyntax>(compilation, expectedGraph); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void ThrowFlow_27() { var source = @" class C { void F(int u) /*<bind>*/{ try { u = 1; } finally { throw; } }/*</bind>*/ }"; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (12,13): error CS0156: A throw statement with no arguments is not allowed outside of a catch clause // throw; Diagnostic(ErrorCode.ERR_BadEmptyThrow, "throw").WithLocation(12, 13) ); string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} .try {R1, R2} { Block[B1] - Block Predecessors: [B0] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'u = 1;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'u = 1') Left: IParameterReferenceOperation: u (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'u') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Next (Regular) Block[B3] Finalizing: {R3} Leaving: {R2} {R1} } .finally {R3} { Block[B2] - Block Predecessors (0) Statements (0) Next (Rethrow) Block[null] } Block[B3] - Exit [UnReachable] Predecessors: [B1] Statements (0) "; VerifyFlowGraphForTest<BlockSyntax>(compilation, expectedGraph); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void ThrowFlow_28() { var source = @" class C { void F(int u, System.Exception ex) /*<bind>*/{ try { u = 1; } finally { throw ex; } }/*</bind>*/ }"; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics(); string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} .try {R1, R2} { Block[B1] - Block Predecessors: [B0] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'u = 1;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'u = 1') Left: IParameterReferenceOperation: u (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'u') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Next (Regular) Block[B3] Finalizing: {R3} Leaving: {R2} {R1} } .finally {R3} { Block[B2] - Block Predecessors (0) Statements (0) Next (Throw) Block[null] IParameterReferenceOperation: ex (OperationKind.ParameterReference, Type: System.Exception) (Syntax: 'ex') } Block[B3] - Exit [UnReachable] Predecessors: [B1] Statements (0) "; VerifyFlowGraphForTest<BlockSyntax>(compilation, expectedGraph); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void ThrowFlow_29() { var source = @" class C { void F(System.Exception a, System.Exception b) /*<bind>*/{ throw a ?? b; }/*</bind>*/ }"; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics(); string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} .locals {R1} { CaptureIds: [1] .locals {R2} { CaptureIds: [0] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'a') Value: IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Exception) (Syntax: 'a') Jump if True (Regular) to Block[B3] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'a') Operand: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Exception, IsImplicit) (Syntax: 'a') Leaving: {R2} Next (Regular) Block[B2] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'a') Value: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Exception, IsImplicit) (Syntax: 'a') Next (Regular) Block[B4] Leaving: {R2} } Block[B3] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'b') Value: IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Exception) (Syntax: 'b') Next (Regular) Block[B4] Block[B4] - Block Predecessors: [B2] [B3] Statements (0) Next (Throw) Block[null] IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Exception, IsImplicit) (Syntax: 'a ?? b') } Block[B5] - Exit [UnReachable] Predecessors (0) Statements (0) "; VerifyFlowGraphForTest<BlockSyntax>(compilation, expectedGraph); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void ThrowFlow_30() { var source = @" class C { void F(bool x, bool y, bool z, System.Exception ex) /*<bind>*/{ x = y ? z : throw ex; }/*</bind>*/ }"; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics(); string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'x') Value: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'x') Jump if False (Regular) to Block[B2] IParameterReferenceOperation: y (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'y') Next (Regular) Block[B3] Block[B2] - Block Predecessors: [B1] Statements (0) Next (Throw) Block[null] IParameterReferenceOperation: ex (OperationKind.ParameterReference, Type: System.Exception) (Syntax: 'ex') Block[B3] - Block Predecessors: [B1] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'x = y ? z : throw ex;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'x = y ? z : throw ex') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Boolean, IsImplicit) (Syntax: 'x') Right: IParameterReferenceOperation: z (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'z') Next (Regular) Block[B4] Leaving: {R1} } Block[B4] - Exit Predecessors: [B3] Statements (0) "; VerifyFlowGraphForTest<BlockSyntax>(compilation, expectedGraph); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void ThrowFlow_31() { var source = @" class C { void F(bool x, bool y, bool z, System.Exception ex) /*<bind>*/{ x = y ? throw ex : z; }/*</bind>*/ }"; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics(); string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'x') Value: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'x') Jump if False (Regular) to Block[B3] IParameterReferenceOperation: y (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'y') Next (Regular) Block[B2] Block[B2] - Block Predecessors: [B1] Statements (0) Next (Throw) Block[null] IParameterReferenceOperation: ex (OperationKind.ParameterReference, Type: System.Exception) (Syntax: 'ex') Block[B3] - Block Predecessors: [B1] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'x = y ? throw ex : z;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'x = y ? throw ex : z') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Boolean, IsImplicit) (Syntax: 'x') Right: IParameterReferenceOperation: z (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'z') Next (Regular) Block[B4] Leaving: {R1} } Block[B4] - Exit Predecessors: [B3] Statements (0) "; VerifyFlowGraphForTest<BlockSyntax>(compilation, expectedGraph); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void ThrowFlow_32_Regular8() { var source = @" class C { void F(bool x, bool y, System.Exception ex1, System.Exception ex2) /*<bind>*/{ x = y ? throw ex1 : throw ex2; }/*</bind>*/ }"; var compilation = CreateCompilation(source, parseOptions: TestOptions.Regular8); compilation.VerifyDiagnostics( // (6,13): error CS8957: Conditional expression is not valid in language version 8.0 because a common type was not found between '<throw expression>' and '<throw expression>'. To use a target-typed conversion, upgrade to language version 9.0 or greater. // x = y ? throw ex1 : throw ex2; Diagnostic(ErrorCode.ERR_NoImplicitConvTargetTypedConditional, "y ? throw ex1 : throw ex2").WithArguments("8.0", "<throw expression>", "<throw expression>", "9.0").WithLocation(6, 13) ); string expectedOperationTree = @" IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsInvalid) (Syntax: '{ ... }') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid) (Syntax: 'x = y ? thr ... throw ex2;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean, IsInvalid) (Syntax: 'x = y ? thr ... : throw ex2') Left: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'x') Right: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Boolean, IsInvalid, IsImplicit) (Syntax: 'y ? throw e ... : throw ex2') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: IConditionalOperation (OperationKind.Conditional, Type: System.Boolean, IsInvalid) (Syntax: 'y ? throw e ... : throw ex2') Condition: IParameterReferenceOperation: y (OperationKind.ParameterReference, Type: System.Boolean, IsInvalid) (Syntax: 'y') WhenTrue: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Boolean, IsInvalid, IsImplicit) (Syntax: 'throw ex1') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: IThrowOperation (OperationKind.Throw, Type: null, IsInvalid) (Syntax: 'throw ex1') IParameterReferenceOperation: ex1 (OperationKind.ParameterReference, Type: System.Exception, IsInvalid) (Syntax: 'ex1') WhenFalse: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Boolean, IsInvalid, IsImplicit) (Syntax: 'throw ex2') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: IThrowOperation (OperationKind.Throw, Type: null, IsInvalid) (Syntax: 'throw ex2') IParameterReferenceOperation: ex2 (OperationKind.ParameterReference, Type: System.Exception, IsInvalid) (Syntax: 'ex2') "; VerifyOperationTreeForTest<BlockSyntax>(compilation, expectedOperationTree); string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'x') Value: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'x') Jump if False (Regular) to Block[B3] IParameterReferenceOperation: y (OperationKind.ParameterReference, Type: System.Boolean, IsInvalid) (Syntax: 'y') Next (Regular) Block[B2] Block[B2] - Block Predecessors: [B1] Statements (0) Next (Throw) Block[null] IParameterReferenceOperation: ex1 (OperationKind.ParameterReference, Type: System.Exception, IsInvalid) (Syntax: 'ex1') Block[B3] - Block Predecessors: [B1] Statements (0) Next (Throw) Block[null] IParameterReferenceOperation: ex2 (OperationKind.ParameterReference, Type: System.Exception, IsInvalid) (Syntax: 'ex2') Block[B4] - Block [UnReachable] Predecessors (0) Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid) (Syntax: 'x = y ? thr ... throw ex2;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean, IsInvalid) (Syntax: 'x = y ? thr ... : throw ex2') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Boolean, IsImplicit) (Syntax: 'x') Right: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Boolean, IsInvalid, IsImplicit) (Syntax: 'y ? throw e ... : throw ex2') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) (ConditionalExpression) Operand: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Boolean, IsInvalid, IsImplicit) (Syntax: 'throw ex2') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) (ImplicitThrow) Operand: IOperation: (OperationKind.None, Type: null, IsInvalid, IsImplicit) (Syntax: 'throw ex2') Next (Regular) Block[B5] Leaving: {R1} } Block[B5] - Exit [UnReachable] Predecessors: [B4] Statements (0) "; VerifyFlowGraphForTest<BlockSyntax>(compilation, expectedGraph); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void ThrowFlow_32_TargetTypedConditional() { var source = @" class C { void F(bool x, bool y, System.Exception ex1, System.Exception ex2) /*<bind>*/{ x = y ? throw ex1 : throw ex2; }/*</bind>*/ }"; var compilation = CreateCompilation(source, parseOptions: TestOptions.Regular.WithLanguageVersion(MessageID.IDS_FeatureTargetTypedConditional.RequiredVersion())); compilation.VerifyDiagnostics(); string expectedOperationTree = @" IBlockOperation (1 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'x = y ? thr ... throw ex2;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'x = y ? thr ... : throw ex2') Left: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'x') Right: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Boolean, IsImplicit) (Syntax: 'y ? throw e ... : throw ex2') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: IConditionalOperation (OperationKind.Conditional, Type: System.Boolean) (Syntax: 'y ? throw e ... : throw ex2') Condition: IParameterReferenceOperation: y (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'y') WhenTrue: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Boolean, IsImplicit) (Syntax: 'throw ex1') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: IThrowOperation (OperationKind.Throw, Type: null) (Syntax: 'throw ex1') IParameterReferenceOperation: ex1 (OperationKind.ParameterReference, Type: System.Exception) (Syntax: 'ex1') WhenFalse: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Boolean, IsImplicit) (Syntax: 'throw ex2') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: IThrowOperation (OperationKind.Throw, Type: null) (Syntax: 'throw ex2') IParameterReferenceOperation: ex2 (OperationKind.ParameterReference, Type: System.Exception) (Syntax: 'ex2') "; VerifyOperationTreeForTest<BlockSyntax>(compilation, expectedOperationTree); string expectedGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'x') Value: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'x') Jump if False (Regular) to Block[B3] IParameterReferenceOperation: y (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'y') Next (Regular) Block[B2] Block[B2] - Block Predecessors: [B1] Statements (0) Next (Throw) Block[null] IParameterReferenceOperation: ex1 (OperationKind.ParameterReference, Type: System.Exception) (Syntax: 'ex1') Block[B3] - Block Predecessors: [B1] Statements (0) Next (Throw) Block[null] IParameterReferenceOperation: ex2 (OperationKind.ParameterReference, Type: System.Exception) (Syntax: 'ex2') Block[B4] - Block [UnReachable] Predecessors (0) Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'x = y ? thr ... throw ex2;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'x = y ? thr ... : throw ex2') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Boolean, IsImplicit) (Syntax: 'x') Right: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Boolean, IsImplicit) (Syntax: 'y ? throw e ... : throw ex2') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) (ConditionalExpression) Operand: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Boolean, IsImplicit) (Syntax: 'throw ex2') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) (ImplicitThrow) Operand: IOperation: (OperationKind.None, Type: null, IsImplicit) (Syntax: 'throw ex2') Next (Regular) Block[B5] Leaving: {R1} } Block[B5] - Exit [UnReachable] Predecessors: [B4] Statements (0) "; VerifyFlowGraphForTest<BlockSyntax>(compilation, expectedGraph); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void ThrowFlow_33() { var source = @" class C { void F(object x, bool y, object u, object v, System.Exception ex) /*<bind>*/{ x = y ? (u ?? v) : throw ex; }/*</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: 'x') Value: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'x') Jump if False (Regular) to Block[B5] IParameterReferenceOperation: y (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'y') 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: 'u') Value: IParameterReferenceOperation: u (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'u') Jump if True (Regular) to Block[B4] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'u') Operand: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'u') Leaving: {R2} Next (Regular) Block[B3] Block[B3] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'u') Value: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'u') Next (Regular) Block[B6] Leaving: {R2} } Block[B4] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'v') Value: IParameterReferenceOperation: v (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'v') Next (Regular) Block[B6] Block[B5] - Block Predecessors: [B1] Statements (0) Next (Throw) Block[null] IParameterReferenceOperation: ex (OperationKind.ParameterReference, Type: System.Exception) (Syntax: 'ex') Block[B6] - Block Predecessors: [B3] [B4] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'x = y ? (u ... : throw ex;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Object) (Syntax: 'x = y ? (u ... : throw ex') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'x') Right: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'u ?? v') Next (Regular) Block[B7] Leaving: {R1} } Block[B7] - Exit Predecessors: [B6] Statements (0) "; VerifyFlowGraphForTest<BlockSyntax>(compilation, expectedGraph); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void ThrowFlow_34() { var source = @" class C { void F(object x, bool y, object u, object v, System.Exception ex) /*<bind>*/{ x = y ? throw ex : (u ?? v); }/*</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: 'x') Value: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'x') Jump if False (Regular) to Block[B3] IParameterReferenceOperation: y (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'y') Entering: {R2} Next (Regular) Block[B2] Block[B2] - Block Predecessors: [B1] Statements (0) Next (Throw) Block[null] IParameterReferenceOperation: ex (OperationKind.ParameterReference, Type: System.Exception) (Syntax: 'ex') .locals {R2} { CaptureIds: [1] Block[B3] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'u') Value: IParameterReferenceOperation: u (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'u') Jump if True (Regular) to Block[B5] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'u') Operand: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'u') Leaving: {R2} Next (Regular) Block[B4] Block[B4] - Block Predecessors: [B3] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'u') Value: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'u') Next (Regular) Block[B6] Leaving: {R2} } Block[B5] - Block Predecessors: [B3] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'v') Value: IParameterReferenceOperation: v (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'v') Next (Regular) Block[B6] Block[B6] - Block Predecessors: [B4] [B5] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'x = y ? thr ... : (u ?? v);') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Object) (Syntax: 'x = y ? thr ... : (u ?? v)') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'x') Right: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'u ?? v') Next (Regular) Block[B7] Leaving: {R1} } Block[B7] - Exit Predecessors: [B6] Statements (0) "; VerifyFlowGraphForTest<BlockSyntax>(compilation, expectedGraph); } } }
-1
dotnet/roslyn
55,428
Test adding nested namespaces
Fixes https://github.com/dotnet/roslyn/issues/54939 The "workaround" that's already implemented is actually the correct behavior.
tmat
2021-08-05T01:19:03Z
2021-08-11T18:38:54Z
bc874ebc5111a2a33221409f895953b1536f6612
1cbbd423e17b186a8f1de89febb4db9a386d180d
Test adding nested namespaces. Fixes https://github.com/dotnet/roslyn/issues/54939 The "workaround" that's already implemented is actually the correct behavior.
./src/Compilers/Test/Utilities/CSharp/FunctionPointerUtilities.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Linq; using Microsoft.Cci; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { internal static class FunctionPointerUtilities { internal static void CommonVerifyFunctionPointer(FunctionPointerTypeSymbol symbol) { verifyPointerType(symbol); verifySignature(symbol.Signature); foreach (var param in symbol.Signature.Parameters) { verifyParameter(param, symbol.Signature); } static void verifyPointerType(FunctionPointerTypeSymbol symbol) { Assert.Equal(SymbolKind.FunctionPointerType, symbol.Kind); Assert.Equal(TypeKind.FunctionPointer, symbol.TypeKind); Assert.False(symbol.IsReferenceType); Assert.False(symbol.IsRefLikeType); Assert.False(symbol.IsReadOnly); Assert.False(symbol.IsStatic); Assert.False(symbol.IsAbstract); Assert.False(symbol.IsSealed); Assert.False(symbol.CanBeReferencedByName); Assert.True(symbol.IsTypeOrTypeAlias()); Assert.True(symbol.IsValueType); Assert.True(symbol.CanBeAssignedNull()); Assert.Null(symbol.ContainingSymbol); Assert.Null(symbol.BaseTypeNoUseSiteDiagnostics); Assert.Null(symbol.ObsoleteAttributeData); Assert.Empty(symbol.Locations); Assert.Empty(symbol.DeclaringSyntaxReferences); Assert.Empty(symbol.GetMembers()); Assert.Empty(symbol.GetTypeMembers()); Assert.Empty(symbol.InterfacesNoUseSiteDiagnostics()); } static void verifySignature(MethodSymbol symbol) { Assert.NotNull(symbol); Assert.Equal(MethodKind.FunctionPointerSignature, symbol.MethodKind); Assert.Equal(string.Empty, symbol.Name); Assert.Equal(0, symbol.Arity); Assert.Equal(default, symbol.ImplementationAttributes); Assert.Equal(Accessibility.NotApplicable, symbol.DeclaredAccessibility); Assert.Equal(FlowAnalysisAnnotations.None, symbol.ReturnTypeFlowAnalysisAnnotations); Assert.Equal(FlowAnalysisAnnotations.None, symbol.FlowAnalysisAnnotations); Assert.False(symbol.IsExtensionMethod); Assert.False(symbol.HidesBaseMethodsByName); Assert.False(symbol.IsStatic); Assert.False(symbol.IsAsync); Assert.False(symbol.IsVirtual); Assert.False(symbol.IsOverride); Assert.False(symbol.IsAbstract); Assert.False(symbol.IsExtern); Assert.False(symbol.IsExtensionMethod); Assert.False(symbol.IsSealed); Assert.False(symbol.IsExtern); Assert.False(symbol.HasSpecialName); Assert.False(symbol.HasDeclarativeSecurity); Assert.False(symbol.RequiresSecurityObject); Assert.False(symbol.IsDeclaredReadOnly); Assert.False(symbol.IsMetadataNewSlot(true)); Assert.False(symbol.IsMetadataNewSlot(false)); Assert.False(symbol.IsMetadataVirtual(true)); Assert.False(symbol.IsMetadataVirtual(false)); Assert.Equal(symbol.IsVararg, symbol.CallingConvention.IsCallingConvention(CallingConvention.ExtraArguments)); Assert.True(symbol.IsImplicitlyDeclared); Assert.Null(symbol.ContainingSymbol); Assert.Null(symbol.AssociatedSymbol); Assert.Null(symbol.ReturnValueMarshallingInformation); Assert.Empty(symbol.TypeParameters); Assert.Empty(symbol.ExplicitInterfaceImplementations); Assert.Empty(symbol.Locations); Assert.Empty(symbol.DeclaringSyntaxReferences); Assert.Empty(symbol.TypeArgumentsWithAnnotations); Assert.Empty(symbol.GetAppliedConditionalSymbols()); Assert.Empty(symbol.ReturnNotNullIfParameterNotNull); } static void verifyParameter(ParameterSymbol symbol, MethodSymbol containing) { Assert.NotNull(symbol); Assert.Same(symbol.ContainingSymbol, containing); Assert.Equal(string.Empty, symbol.Name); Assert.Equal(FlowAnalysisAnnotations.None, symbol.FlowAnalysisAnnotations); Assert.False(symbol.IsDiscard); Assert.False(symbol.IsParams); Assert.False(symbol.IsMetadataOptional); Assert.False(symbol.IsIDispatchConstant); Assert.False(symbol.IsIUnknownConstant); Assert.False(symbol.IsCallerFilePath); Assert.False(symbol.IsCallerLineNumber); Assert.False(symbol.IsCallerFilePath); Assert.False(symbol.IsCallerMemberName); Assert.True(symbol.IsImplicitlyDeclared); Assert.Null(symbol.MarshallingInformation); Assert.Null(symbol.ExplicitDefaultConstantValue); Assert.Empty(symbol.Locations); Assert.Empty(symbol.DeclaringSyntaxReferences); Assert.Empty(symbol.NotNullIfParameterNotNull); } } public static void VerifyFunctionPointerSemanticInfo( SemanticModel model, SyntaxNode syntax, string expectedSyntax, string? expectedType, string? expectedConvertedType = null, string? expectedSymbol = null, CandidateReason expectedCandidateReason = CandidateReason.None, string[]? expectedSymbolCandidates = null) { AssertEx.Equal(expectedSyntax, syntax.ToString()); var semanticInfo = model.GetSemanticInfoSummary(syntax); ITypeSymbol? exprType; if (expectedType is null) { exprType = semanticInfo.ConvertedType; Assert.Null(semanticInfo.Type); } else { exprType = semanticInfo.Type; AssertEx.Equal(expectedType, semanticInfo.Type.ToTestDisplayString(includeNonNullable: false)); } if (expectedConvertedType is null) { Assert.Equal(semanticInfo.Type, semanticInfo.ConvertedType, SymbolEqualityComparer.IncludeNullability); } else { AssertEx.Equal(expectedConvertedType, semanticInfo.ConvertedType.ToTestDisplayString(includeNonNullable: false)); } verifySymbolInfo(expectedSymbol, expectedCandidateReason, expectedSymbolCandidates, semanticInfo); if (exprType is IFunctionPointerTypeSymbol ptrType) { CommonVerifyFunctionPointer(ptrType.GetSymbol()); } switch (syntax) { case FunctionPointerTypeSyntax { ParameterList: { Parameters: var paramSyntaxes } }: verifyNestedFunctionPointerSyntaxSemanticInfo(model, (IFunctionPointerTypeSymbol)exprType, paramSyntaxes); break; case PrefixUnaryExpressionSyntax { RawKind: (int)SyntaxKind.AddressOfExpression, Operand: var operand }: // Members should only be accessible from the underlying operand Assert.Empty(semanticInfo.MemberGroup); var expectedConversionKind = (expectedType, expectedConvertedType, expectedSymbol) switch { (null, null, _) => ConversionKind.Identity, (_, _, null) => ConversionKind.NoConversion, (_, _, _) => ConversionKind.MethodGroup, }; Assert.Equal(expectedConversionKind, semanticInfo.ImplicitConversion.Kind); semanticInfo = model.GetSemanticInfoSummary(operand); Assert.Null(semanticInfo.Type); Assert.Null(semanticInfo.ConvertedType); if (expectedSymbolCandidates != null) { AssertEx.Equal(expectedSymbolCandidates, semanticInfo.MemberGroup.Select(s => s.ToTestDisplayString(includeNonNullable: false))); } else { Assert.Contains(semanticInfo.MemberGroup, actual => actual.ToTestDisplayString(includeNonNullable: false) == expectedSymbol); } verifySymbolInfo(expectedSymbol, expectedCandidateReason, expectedSymbolCandidates, semanticInfo); break; } static void verifySymbolInfo( string? expectedSymbol, CandidateReason expectedReason, string[]? expectedSymbolCandidates, CompilationUtils.SemanticInfoSummary semanticInfo) { if (expectedSymbol is object) { Assert.Empty(semanticInfo.CandidateSymbols); AssertEx.Equal(expectedSymbol, semanticInfo.Symbol.ToTestDisplayString(includeNonNullable: false)); Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason); } else if (expectedSymbolCandidates is object) { Assert.Null(semanticInfo.Symbol); Assert.Equal(expectedReason, semanticInfo.CandidateReason); AssertEx.Equal(expectedSymbolCandidates, semanticInfo.CandidateSymbols.Select(s => s.ToTestDisplayString(includeNonNullable: false))); } else { Assert.Null(semanticInfo.Symbol); Assert.Empty(semanticInfo.CandidateSymbols); Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason); } } static void verifyNestedFunctionPointerSyntaxSemanticInfo(SemanticModel model, IFunctionPointerTypeSymbol ptrType, SeparatedSyntaxList<FunctionPointerParameterSyntax> paramSyntaxes) { // https://github.com/dotnet/roslyn/issues/43321 Nullability in type syntaxes that don't have an origin bound node // can differ. var signature = ptrType.Signature; for (int i = 0; i < paramSyntaxes.Count - 1; i++) { var paramSyntax = paramSyntaxes[i].Type!; ITypeSymbol signatureParamType = signature.Parameters[i].Type; assertEqualSemanticInformation(model, paramSyntax, signatureParamType); } var returnParam = paramSyntaxes[^1].Type; assertEqualSemanticInformation(model, returnParam!, signature.ReturnType); } static void assertEqualSemanticInformation(SemanticModel model, TypeSyntax typeSyntax, ITypeSymbol signatureType) { var semanticInfo = model.GetSemanticInfoSummary(typeSyntax); Assert.Equal<ISymbol>(signatureType, semanticInfo.Type, SymbolEqualityComparer.Default); Assert.Equal(semanticInfo.Type, semanticInfo.ConvertedType, SymbolEqualityComparer.IncludeNullability); Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason); Assert.Equal(signatureType, semanticInfo.Type, SymbolEqualityComparer.Default); Assert.Empty(semanticInfo.CandidateSymbols); if (typeSyntax is FunctionPointerTypeSyntax { ParameterList: { Parameters: var paramSyntaxes } }) { var paramPtrType = (IFunctionPointerTypeSymbol)semanticInfo.Type!; CommonVerifyFunctionPointer(paramPtrType.GetSymbol()); verifyNestedFunctionPointerSyntaxSemanticInfo(model, paramPtrType, paramSyntaxes); } } } public static void VerifyFunctionPointerSymbol(TypeSymbol type, CallingConvention expectedConvention, (RefKind RefKind, Action<TypeSymbol> TypeVerifier) returnVerifier, params (RefKind RefKind, Action<TypeSymbol> TypeVerifier)[] argumentVerifiers) { FunctionPointerTypeSymbol funcPtr = (FunctionPointerTypeSymbol)type; FunctionPointerUtilities.CommonVerifyFunctionPointer(funcPtr); var signature = funcPtr.Signature; Assert.Equal(expectedConvention, signature.CallingConvention); Assert.Equal(returnVerifier.RefKind, signature.RefKind); switch (signature.RefKind) { case RefKind.RefReadOnly: Assert.True(CustomModifierUtils.HasInAttributeModifier(signature.RefCustomModifiers)); Assert.False(CustomModifierUtils.HasOutAttributeModifier(signature.RefCustomModifiers)); break; case RefKind.None: case RefKind.Ref: Assert.False(CustomModifierUtils.HasInAttributeModifier(signature.RefCustomModifiers)); Assert.False(CustomModifierUtils.HasOutAttributeModifier(signature.RefCustomModifiers)); break; case RefKind.Out: default: Assert.True(false, $"Cannot have a return ref kind of {signature.RefKind}"); break; } returnVerifier.TypeVerifier(signature.ReturnType); Assert.Equal(argumentVerifiers.Length, signature.ParameterCount); for (int i = 0; i < argumentVerifiers.Length; i++) { var parameter = signature.Parameters[i]; Assert.Equal(argumentVerifiers[i].RefKind, parameter.RefKind); argumentVerifiers[i].TypeVerifier(parameter.Type); switch (parameter.RefKind) { case RefKind.Out: Assert.True(CustomModifierUtils.HasOutAttributeModifier(parameter.RefCustomModifiers)); Assert.False(CustomModifierUtils.HasInAttributeModifier(parameter.RefCustomModifiers)); break; case RefKind.In: Assert.True(CustomModifierUtils.HasInAttributeModifier(parameter.RefCustomModifiers)); Assert.False(CustomModifierUtils.HasOutAttributeModifier(parameter.RefCustomModifiers)); break; case RefKind.Ref: case RefKind.None: Assert.False(CustomModifierUtils.HasInAttributeModifier(parameter.RefCustomModifiers)); Assert.False(CustomModifierUtils.HasOutAttributeModifier(parameter.RefCustomModifiers)); break; default: Assert.True(false, $"Cannot have a return ref kind of {parameter.RefKind}"); break; } } } public static Action<TypeSymbol> IsVoidType() => typeSymbol => Assert.True(typeSymbol.IsVoidType()); public static Action<TypeSymbol> IsSpecialType(SpecialType specialType) => typeSymbol => Assert.Equal(specialType, typeSymbol.SpecialType); public static Action<TypeSymbol> IsTypeName(string typeName) => typeSymbol => Assert.Equal(typeName, typeSymbol.Name); public static Action<TypeSymbol> IsArrayType(Action<TypeSymbol> arrayTypeVerifier) => typeSymbol => { Assert.True(typeSymbol.IsArray()); arrayTypeVerifier(((ArrayTypeSymbol)typeSymbol).ElementType); }; public static Action<TypeSymbol> IsUnsupportedType() => typeSymbol => Assert.True(typeSymbol is UnsupportedMetadataTypeSymbol); public static Action<TypeSymbol> IsFunctionPointerTypeSymbol(CallingConvention callingConvention, (RefKind, Action<TypeSymbol>) returnVerifier, params (RefKind, Action<TypeSymbol>)[] argumentVerifiers) => typeSymbol => VerifyFunctionPointerSymbol((FunctionPointerTypeSymbol)typeSymbol, callingConvention, returnVerifier, argumentVerifiers); public static Action<TypeSymbol> IsErrorType() => typeSymbol => Assert.True(typeSymbol.IsErrorType()); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Linq; using Microsoft.Cci; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { internal static class FunctionPointerUtilities { internal static void CommonVerifyFunctionPointer(FunctionPointerTypeSymbol symbol) { verifyPointerType(symbol); verifySignature(symbol.Signature); foreach (var param in symbol.Signature.Parameters) { verifyParameter(param, symbol.Signature); } static void verifyPointerType(FunctionPointerTypeSymbol symbol) { Assert.Equal(SymbolKind.FunctionPointerType, symbol.Kind); Assert.Equal(TypeKind.FunctionPointer, symbol.TypeKind); Assert.False(symbol.IsReferenceType); Assert.False(symbol.IsRefLikeType); Assert.False(symbol.IsReadOnly); Assert.False(symbol.IsStatic); Assert.False(symbol.IsAbstract); Assert.False(symbol.IsSealed); Assert.False(symbol.CanBeReferencedByName); Assert.True(symbol.IsTypeOrTypeAlias()); Assert.True(symbol.IsValueType); Assert.True(symbol.CanBeAssignedNull()); Assert.Null(symbol.ContainingSymbol); Assert.Null(symbol.BaseTypeNoUseSiteDiagnostics); Assert.Null(symbol.ObsoleteAttributeData); Assert.Empty(symbol.Locations); Assert.Empty(symbol.DeclaringSyntaxReferences); Assert.Empty(symbol.GetMembers()); Assert.Empty(symbol.GetTypeMembers()); Assert.Empty(symbol.InterfacesNoUseSiteDiagnostics()); } static void verifySignature(MethodSymbol symbol) { Assert.NotNull(symbol); Assert.Equal(MethodKind.FunctionPointerSignature, symbol.MethodKind); Assert.Equal(string.Empty, symbol.Name); Assert.Equal(0, symbol.Arity); Assert.Equal(default, symbol.ImplementationAttributes); Assert.Equal(Accessibility.NotApplicable, symbol.DeclaredAccessibility); Assert.Equal(FlowAnalysisAnnotations.None, symbol.ReturnTypeFlowAnalysisAnnotations); Assert.Equal(FlowAnalysisAnnotations.None, symbol.FlowAnalysisAnnotations); Assert.False(symbol.IsExtensionMethod); Assert.False(symbol.HidesBaseMethodsByName); Assert.False(symbol.IsStatic); Assert.False(symbol.IsAsync); Assert.False(symbol.IsVirtual); Assert.False(symbol.IsOverride); Assert.False(symbol.IsAbstract); Assert.False(symbol.IsExtern); Assert.False(symbol.IsExtensionMethod); Assert.False(symbol.IsSealed); Assert.False(symbol.IsExtern); Assert.False(symbol.HasSpecialName); Assert.False(symbol.HasDeclarativeSecurity); Assert.False(symbol.RequiresSecurityObject); Assert.False(symbol.IsDeclaredReadOnly); Assert.False(symbol.IsMetadataNewSlot(true)); Assert.False(symbol.IsMetadataNewSlot(false)); Assert.False(symbol.IsMetadataVirtual(true)); Assert.False(symbol.IsMetadataVirtual(false)); Assert.Equal(symbol.IsVararg, symbol.CallingConvention.IsCallingConvention(CallingConvention.ExtraArguments)); Assert.True(symbol.IsImplicitlyDeclared); Assert.Null(symbol.ContainingSymbol); Assert.Null(symbol.AssociatedSymbol); Assert.Null(symbol.ReturnValueMarshallingInformation); Assert.Empty(symbol.TypeParameters); Assert.Empty(symbol.ExplicitInterfaceImplementations); Assert.Empty(symbol.Locations); Assert.Empty(symbol.DeclaringSyntaxReferences); Assert.Empty(symbol.TypeArgumentsWithAnnotations); Assert.Empty(symbol.GetAppliedConditionalSymbols()); Assert.Empty(symbol.ReturnNotNullIfParameterNotNull); } static void verifyParameter(ParameterSymbol symbol, MethodSymbol containing) { Assert.NotNull(symbol); Assert.Same(symbol.ContainingSymbol, containing); Assert.Equal(string.Empty, symbol.Name); Assert.Equal(FlowAnalysisAnnotations.None, symbol.FlowAnalysisAnnotations); Assert.False(symbol.IsDiscard); Assert.False(symbol.IsParams); Assert.False(symbol.IsMetadataOptional); Assert.False(symbol.IsIDispatchConstant); Assert.False(symbol.IsIUnknownConstant); Assert.False(symbol.IsCallerFilePath); Assert.False(symbol.IsCallerLineNumber); Assert.False(symbol.IsCallerFilePath); Assert.False(symbol.IsCallerMemberName); Assert.True(symbol.IsImplicitlyDeclared); Assert.Null(symbol.MarshallingInformation); Assert.Null(symbol.ExplicitDefaultConstantValue); Assert.Empty(symbol.Locations); Assert.Empty(symbol.DeclaringSyntaxReferences); Assert.Empty(symbol.NotNullIfParameterNotNull); } } public static void VerifyFunctionPointerSemanticInfo( SemanticModel model, SyntaxNode syntax, string expectedSyntax, string? expectedType, string? expectedConvertedType = null, string? expectedSymbol = null, CandidateReason expectedCandidateReason = CandidateReason.None, string[]? expectedSymbolCandidates = null) { AssertEx.Equal(expectedSyntax, syntax.ToString()); var semanticInfo = model.GetSemanticInfoSummary(syntax); ITypeSymbol? exprType; if (expectedType is null) { exprType = semanticInfo.ConvertedType; Assert.Null(semanticInfo.Type); } else { exprType = semanticInfo.Type; AssertEx.Equal(expectedType, semanticInfo.Type.ToTestDisplayString(includeNonNullable: false)); } if (expectedConvertedType is null) { Assert.Equal(semanticInfo.Type, semanticInfo.ConvertedType, SymbolEqualityComparer.IncludeNullability); } else { AssertEx.Equal(expectedConvertedType, semanticInfo.ConvertedType.ToTestDisplayString(includeNonNullable: false)); } verifySymbolInfo(expectedSymbol, expectedCandidateReason, expectedSymbolCandidates, semanticInfo); if (exprType is IFunctionPointerTypeSymbol ptrType) { CommonVerifyFunctionPointer(ptrType.GetSymbol()); } switch (syntax) { case FunctionPointerTypeSyntax { ParameterList: { Parameters: var paramSyntaxes } }: verifyNestedFunctionPointerSyntaxSemanticInfo(model, (IFunctionPointerTypeSymbol)exprType, paramSyntaxes); break; case PrefixUnaryExpressionSyntax { RawKind: (int)SyntaxKind.AddressOfExpression, Operand: var operand }: // Members should only be accessible from the underlying operand Assert.Empty(semanticInfo.MemberGroup); var expectedConversionKind = (expectedType, expectedConvertedType, expectedSymbol) switch { (null, null, _) => ConversionKind.Identity, (_, _, null) => ConversionKind.NoConversion, (_, _, _) => ConversionKind.MethodGroup, }; Assert.Equal(expectedConversionKind, semanticInfo.ImplicitConversion.Kind); semanticInfo = model.GetSemanticInfoSummary(operand); Assert.Null(semanticInfo.Type); Assert.Null(semanticInfo.ConvertedType); if (expectedSymbolCandidates != null) { AssertEx.Equal(expectedSymbolCandidates, semanticInfo.MemberGroup.Select(s => s.ToTestDisplayString(includeNonNullable: false))); } else { Assert.Contains(semanticInfo.MemberGroup, actual => actual.ToTestDisplayString(includeNonNullable: false) == expectedSymbol); } verifySymbolInfo(expectedSymbol, expectedCandidateReason, expectedSymbolCandidates, semanticInfo); break; } static void verifySymbolInfo( string? expectedSymbol, CandidateReason expectedReason, string[]? expectedSymbolCandidates, CompilationUtils.SemanticInfoSummary semanticInfo) { if (expectedSymbol is object) { Assert.Empty(semanticInfo.CandidateSymbols); AssertEx.Equal(expectedSymbol, semanticInfo.Symbol.ToTestDisplayString(includeNonNullable: false)); Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason); } else if (expectedSymbolCandidates is object) { Assert.Null(semanticInfo.Symbol); Assert.Equal(expectedReason, semanticInfo.CandidateReason); AssertEx.Equal(expectedSymbolCandidates, semanticInfo.CandidateSymbols.Select(s => s.ToTestDisplayString(includeNonNullable: false))); } else { Assert.Null(semanticInfo.Symbol); Assert.Empty(semanticInfo.CandidateSymbols); Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason); } } static void verifyNestedFunctionPointerSyntaxSemanticInfo(SemanticModel model, IFunctionPointerTypeSymbol ptrType, SeparatedSyntaxList<FunctionPointerParameterSyntax> paramSyntaxes) { // https://github.com/dotnet/roslyn/issues/43321 Nullability in type syntaxes that don't have an origin bound node // can differ. var signature = ptrType.Signature; for (int i = 0; i < paramSyntaxes.Count - 1; i++) { var paramSyntax = paramSyntaxes[i].Type!; ITypeSymbol signatureParamType = signature.Parameters[i].Type; assertEqualSemanticInformation(model, paramSyntax, signatureParamType); } var returnParam = paramSyntaxes[^1].Type; assertEqualSemanticInformation(model, returnParam!, signature.ReturnType); } static void assertEqualSemanticInformation(SemanticModel model, TypeSyntax typeSyntax, ITypeSymbol signatureType) { var semanticInfo = model.GetSemanticInfoSummary(typeSyntax); Assert.Equal<ISymbol>(signatureType, semanticInfo.Type, SymbolEqualityComparer.Default); Assert.Equal(semanticInfo.Type, semanticInfo.ConvertedType, SymbolEqualityComparer.IncludeNullability); Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason); Assert.Equal(signatureType, semanticInfo.Type, SymbolEqualityComparer.Default); Assert.Empty(semanticInfo.CandidateSymbols); if (typeSyntax is FunctionPointerTypeSyntax { ParameterList: { Parameters: var paramSyntaxes } }) { var paramPtrType = (IFunctionPointerTypeSymbol)semanticInfo.Type!; CommonVerifyFunctionPointer(paramPtrType.GetSymbol()); verifyNestedFunctionPointerSyntaxSemanticInfo(model, paramPtrType, paramSyntaxes); } } } public static void VerifyFunctionPointerSymbol(TypeSymbol type, CallingConvention expectedConvention, (RefKind RefKind, Action<TypeSymbol> TypeVerifier) returnVerifier, params (RefKind RefKind, Action<TypeSymbol> TypeVerifier)[] argumentVerifiers) { FunctionPointerTypeSymbol funcPtr = (FunctionPointerTypeSymbol)type; FunctionPointerUtilities.CommonVerifyFunctionPointer(funcPtr); var signature = funcPtr.Signature; Assert.Equal(expectedConvention, signature.CallingConvention); Assert.Equal(returnVerifier.RefKind, signature.RefKind); switch (signature.RefKind) { case RefKind.RefReadOnly: Assert.True(CustomModifierUtils.HasInAttributeModifier(signature.RefCustomModifiers)); Assert.False(CustomModifierUtils.HasOutAttributeModifier(signature.RefCustomModifiers)); break; case RefKind.None: case RefKind.Ref: Assert.False(CustomModifierUtils.HasInAttributeModifier(signature.RefCustomModifiers)); Assert.False(CustomModifierUtils.HasOutAttributeModifier(signature.RefCustomModifiers)); break; case RefKind.Out: default: Assert.True(false, $"Cannot have a return ref kind of {signature.RefKind}"); break; } returnVerifier.TypeVerifier(signature.ReturnType); Assert.Equal(argumentVerifiers.Length, signature.ParameterCount); for (int i = 0; i < argumentVerifiers.Length; i++) { var parameter = signature.Parameters[i]; Assert.Equal(argumentVerifiers[i].RefKind, parameter.RefKind); argumentVerifiers[i].TypeVerifier(parameter.Type); switch (parameter.RefKind) { case RefKind.Out: Assert.True(CustomModifierUtils.HasOutAttributeModifier(parameter.RefCustomModifiers)); Assert.False(CustomModifierUtils.HasInAttributeModifier(parameter.RefCustomModifiers)); break; case RefKind.In: Assert.True(CustomModifierUtils.HasInAttributeModifier(parameter.RefCustomModifiers)); Assert.False(CustomModifierUtils.HasOutAttributeModifier(parameter.RefCustomModifiers)); break; case RefKind.Ref: case RefKind.None: Assert.False(CustomModifierUtils.HasInAttributeModifier(parameter.RefCustomModifiers)); Assert.False(CustomModifierUtils.HasOutAttributeModifier(parameter.RefCustomModifiers)); break; default: Assert.True(false, $"Cannot have a return ref kind of {parameter.RefKind}"); break; } } } public static Action<TypeSymbol> IsVoidType() => typeSymbol => Assert.True(typeSymbol.IsVoidType()); public static Action<TypeSymbol> IsSpecialType(SpecialType specialType) => typeSymbol => Assert.Equal(specialType, typeSymbol.SpecialType); public static Action<TypeSymbol> IsTypeName(string typeName) => typeSymbol => Assert.Equal(typeName, typeSymbol.Name); public static Action<TypeSymbol> IsArrayType(Action<TypeSymbol> arrayTypeVerifier) => typeSymbol => { Assert.True(typeSymbol.IsArray()); arrayTypeVerifier(((ArrayTypeSymbol)typeSymbol).ElementType); }; public static Action<TypeSymbol> IsUnsupportedType() => typeSymbol => Assert.True(typeSymbol is UnsupportedMetadataTypeSymbol); public static Action<TypeSymbol> IsFunctionPointerTypeSymbol(CallingConvention callingConvention, (RefKind, Action<TypeSymbol>) returnVerifier, params (RefKind, Action<TypeSymbol>)[] argumentVerifiers) => typeSymbol => VerifyFunctionPointerSymbol((FunctionPointerTypeSymbol)typeSymbol, callingConvention, returnVerifier, argumentVerifiers); public static Action<TypeSymbol> IsErrorType() => typeSymbol => Assert.True(typeSymbol.IsErrorType()); } }
-1
dotnet/roslyn
55,428
Test adding nested namespaces
Fixes https://github.com/dotnet/roslyn/issues/54939 The "workaround" that's already implemented is actually the correct behavior.
tmat
2021-08-05T01:19:03Z
2021-08-11T18:38:54Z
bc874ebc5111a2a33221409f895953b1536f6612
1cbbd423e17b186a8f1de89febb4db9a386d180d
Test adding nested namespaces. Fixes https://github.com/dotnet/roslyn/issues/54939 The "workaround" that's already implemented is actually the correct behavior.
./src/Workspaces/SharedUtilitiesAndExtensions/Workspace/VisualBasic/LanguageServices/VisualBasicRemoveUnnecessaryImportsService.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Composition Imports System.Threading Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.Formatting Imports Microsoft.CodeAnalysis.Host.Mef Imports Microsoft.CodeAnalysis.Internal.Log Imports Microsoft.CodeAnalysis.RemoveUnnecessaryImports Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.RemoveUnnecessaryImports <ExportLanguageService(GetType(IRemoveUnnecessaryImportsService), LanguageNames.VisualBasic), [Shared]> Partial Friend NotInheritable Class VisualBasicRemoveUnnecessaryImportsService Inherits AbstractRemoveUnnecessaryImportsService(Of ImportsClauseSyntax) <ImportingConstructor> <Obsolete(MefConstruction.ImportingConstructorMessage, True)> Public Sub New() End Sub Protected Overrides ReadOnly Property UnnecessaryImportsProvider As IUnnecessaryImportsProvider Get Return VisualBasicUnnecessaryImportsProvider.Instance End Get End Property Public Overrides Async Function RemoveUnnecessaryImportsAsync( document As Document, predicate As Func(Of SyntaxNode, Boolean), cancellationToken As CancellationToken) As Task(Of Document) predicate = If(predicate, Functions(Of SyntaxNode).True) Using Logger.LogBlock(FunctionId.Refactoring_RemoveUnnecessaryImports_VisualBasic, cancellationToken) Dim unnecessaryImports = Await GetCommonUnnecessaryImportsOfAllContextAsync( document, predicate, cancellationToken).ConfigureAwait(False) If unnecessaryImports.Any(Function(import) import.OverlapsHiddenPosition(cancellationToken)) Then Return document End If Dim root = Await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(False) Dim oldRoot = DirectCast(root, CompilationUnitSyntax) Dim newRoot = New Rewriter(document, unnecessaryImports, cancellationToken).Visit(oldRoot) newRoot = newRoot.WithAdditionalAnnotations(Formatter.Annotation) cancellationToken.ThrowIfCancellationRequested() Return document.WithSyntaxRoot(newRoot) End Using End Function End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Composition Imports System.Threading Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.Formatting Imports Microsoft.CodeAnalysis.Host.Mef Imports Microsoft.CodeAnalysis.Internal.Log Imports Microsoft.CodeAnalysis.RemoveUnnecessaryImports Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.RemoveUnnecessaryImports <ExportLanguageService(GetType(IRemoveUnnecessaryImportsService), LanguageNames.VisualBasic), [Shared]> Partial Friend NotInheritable Class VisualBasicRemoveUnnecessaryImportsService Inherits AbstractRemoveUnnecessaryImportsService(Of ImportsClauseSyntax) <ImportingConstructor> <Obsolete(MefConstruction.ImportingConstructorMessage, True)> Public Sub New() End Sub Protected Overrides ReadOnly Property UnnecessaryImportsProvider As IUnnecessaryImportsProvider Get Return VisualBasicUnnecessaryImportsProvider.Instance End Get End Property Public Overrides Async Function RemoveUnnecessaryImportsAsync( document As Document, predicate As Func(Of SyntaxNode, Boolean), cancellationToken As CancellationToken) As Task(Of Document) predicate = If(predicate, Functions(Of SyntaxNode).True) Using Logger.LogBlock(FunctionId.Refactoring_RemoveUnnecessaryImports_VisualBasic, cancellationToken) Dim unnecessaryImports = Await GetCommonUnnecessaryImportsOfAllContextAsync( document, predicate, cancellationToken).ConfigureAwait(False) If unnecessaryImports.Any(Function(import) import.OverlapsHiddenPosition(cancellationToken)) Then Return document End If Dim root = Await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(False) Dim oldRoot = DirectCast(root, CompilationUnitSyntax) Dim newRoot = New Rewriter(document, unnecessaryImports, cancellationToken).Visit(oldRoot) newRoot = newRoot.WithAdditionalAnnotations(Formatter.Annotation) cancellationToken.ThrowIfCancellationRequested() Return document.WithSyntaxRoot(newRoot) End Using End Function End Class End Namespace
-1
dotnet/roslyn
55,428
Test adding nested namespaces
Fixes https://github.com/dotnet/roslyn/issues/54939 The "workaround" that's already implemented is actually the correct behavior.
tmat
2021-08-05T01:19:03Z
2021-08-11T18:38:54Z
bc874ebc5111a2a33221409f895953b1536f6612
1cbbd423e17b186a8f1de89febb4db9a386d180d
Test adding nested namespaces. Fixes https://github.com/dotnet/roslyn/issues/54939 The "workaround" that's already implemented is actually the correct behavior.
./src/EditorFeatures/VisualBasicTest/Recommendations/PreprocessorDirectives/ElseIfDirectiveKeywordRecommenderTests.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Recommendations.PreprocessorDirectives Public Class ElseIfDirectiveKeywordRecommenderTests <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub HashElseIfNotInFileTest() VerifyRecommendationsMissing(<File>|</File>, "#ElseIf") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub HashElseIfInFileAfterIfTest() VerifyRecommendationsContain(<File> #If True Then |</File>, "#ElseIf") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub HashElseIfInFileAfterElseIfTest() VerifyRecommendationsContain(<File> #If True Then #ElseIf True Then |</File>, "#ElseIf") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub HashElseIfNotInFileAfterElseIf1Test() VerifyRecommendationsMissing(<File> #If True Then #Else |</File>, "#ElseIf") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub HashElseIfNotInFileAfterElseIf2Test() VerifyRecommendationsMissing(<File> #If True Then #ElseIf True Then #Else |</File>, "#ElseIf") End Sub End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Recommendations.PreprocessorDirectives Public Class ElseIfDirectiveKeywordRecommenderTests <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub HashElseIfNotInFileTest() VerifyRecommendationsMissing(<File>|</File>, "#ElseIf") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub HashElseIfInFileAfterIfTest() VerifyRecommendationsContain(<File> #If True Then |</File>, "#ElseIf") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub HashElseIfInFileAfterElseIfTest() VerifyRecommendationsContain(<File> #If True Then #ElseIf True Then |</File>, "#ElseIf") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub HashElseIfNotInFileAfterElseIf1Test() VerifyRecommendationsMissing(<File> #If True Then #Else |</File>, "#ElseIf") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub HashElseIfNotInFileAfterElseIf2Test() VerifyRecommendationsMissing(<File> #If True Then #ElseIf True Then #Else |</File>, "#ElseIf") End Sub End Class End Namespace
-1
dotnet/roslyn
55,428
Test adding nested namespaces
Fixes https://github.com/dotnet/roslyn/issues/54939 The "workaround" that's already implemented is actually the correct behavior.
tmat
2021-08-05T01:19:03Z
2021-08-11T18:38:54Z
bc874ebc5111a2a33221409f895953b1536f6612
1cbbd423e17b186a8f1de89febb4db9a386d180d
Test adding nested namespaces. Fixes https://github.com/dotnet/roslyn/issues/54939 The "workaround" that's already implemented is actually the correct behavior.
./src/Compilers/VisualBasic/Portable/Lowering/LocalRewriter/LocalRewriter_TupleLiteralExpression.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable Imports Microsoft.CodeAnalysis.PooledObjects Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Namespace Microsoft.CodeAnalysis.VisualBasic Partial Friend NotInheritable Class LocalRewriter Public Overrides Function VisitTupleLiteral(node As BoundTupleLiteral) As BoundNode Return VisitTupleExpression(node) End Function Public Overrides Function VisitConvertedTupleLiteral(node As BoundConvertedTupleLiteral) As BoundNode Return VisitTupleExpression(node) End Function Private Function VisitTupleExpression(node As BoundTupleExpression) As BoundNode Dim rewrittenArguments As ImmutableArray(Of BoundExpression) = VisitList(node.Arguments) Return RewriteTupleCreationExpression(node, rewrittenArguments) End Function ''' <summary> ''' Converts the expression for creating a tuple instance into an expression creating a ValueTuple (if short) or nested ValueTuples (if longer). ''' ''' For instance, for a long tuple we'll generate: ''' creationExpression(ctor=largestCtor, args=firstArgs+(nested creationExpression for remainder, with smaller ctor and next few args)) ''' </summary> Private Function RewriteTupleCreationExpression(node As BoundTupleExpression, rewrittenArguments As ImmutableArray(Of BoundExpression)) As BoundExpression Return MakeTupleCreationExpression(node.Syntax, DirectCast(node.Type, NamedTypeSymbol), rewrittenArguments) End Function Private Function MakeTupleCreationExpression(syntax As SyntaxNode, type As NamedTypeSymbol, rewrittenArguments As ImmutableArray(Of BoundExpression)) As BoundExpression Dim underlyingTupleType As NamedTypeSymbol = If(type.TupleUnderlyingType, type) Debug.Assert(underlyingTupleType.IsTupleCompatible()) Dim underlyingTupleTypeChain As ArrayBuilder(Of NamedTypeSymbol) = ArrayBuilder(Of NamedTypeSymbol).GetInstance() TupleTypeSymbol.GetUnderlyingTypeChain(underlyingTupleType, underlyingTupleTypeChain) Try ' make a creation expression for the smallest type Dim smallestType As NamedTypeSymbol = underlyingTupleTypeChain.Pop() Dim smallestCtorArguments As ImmutableArray(Of BoundExpression) = ImmutableArray.Create(rewrittenArguments, underlyingTupleTypeChain.Count * (TupleTypeSymbol.RestPosition - 1), smallestType.Arity) Dim smallestCtor As MethodSymbol = DirectCast(TupleTypeSymbol.GetWellKnownMemberInType(smallestType.OriginalDefinition, TupleTypeSymbol.GetTupleCtor(smallestType.Arity), _diagnostics, syntax), MethodSymbol) If smallestCtor Is Nothing Then Return New BoundBadExpression( syntax, LookupResultKind.Empty, ImmutableArray(Of Symbol).Empty, rewrittenArguments, type, hasErrors:=True) End If Dim smallestConstructor As MethodSymbol = smallestCtor.AsMember(smallestType) Dim currentCreation As BoundObjectCreationExpression = New BoundObjectCreationExpression(syntax, smallestConstructor, smallestCtorArguments, initializerOpt:=Nothing, type:=smallestType) If underlyingTupleTypeChain.Count > 0 Then Dim tuple8Type As NamedTypeSymbol = underlyingTupleTypeChain.Peek() Dim tuple8Ctor As MethodSymbol = DirectCast(TupleTypeSymbol.GetWellKnownMemberInType(tuple8Type.OriginalDefinition, TupleTypeSymbol.GetTupleCtor(TupleTypeSymbol.RestPosition), _diagnostics, syntax), MethodSymbol) If tuple8Ctor Is Nothing Then Return New BoundBadExpression( syntax, LookupResultKind.Empty, ImmutableArray(Of Symbol).Empty, rewrittenArguments, type, hasErrors:=True) End If ' make successively larger creation expressions containing the previous one Do Dim ctorArguments As ImmutableArray(Of BoundExpression) = ImmutableArray.Create(rewrittenArguments, (underlyingTupleTypeChain.Count - 1) * (TupleTypeSymbol.RestPosition - 1), TupleTypeSymbol.RestPosition - 1).Add(currentCreation) Dim constructor As MethodSymbol = tuple8Ctor.AsMember(underlyingTupleTypeChain.Pop()) currentCreation = New BoundObjectCreationExpression(syntax, constructor, ctorArguments, initializerOpt:=Nothing, type:=constructor.ContainingType) Loop While (underlyingTupleTypeChain.Count > 0) End If currentCreation = currentCreation.Update( currentCreation.ConstructorOpt, methodGroupOpt:=Nothing, arguments:=currentCreation.Arguments, defaultArguments:=currentCreation.DefaultArguments, initializerOpt:=currentCreation.InitializerOpt, type:=type) Return currentCreation Finally underlyingTupleTypeChain.Free() End Try End Function End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable Imports Microsoft.CodeAnalysis.PooledObjects Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Namespace Microsoft.CodeAnalysis.VisualBasic Partial Friend NotInheritable Class LocalRewriter Public Overrides Function VisitTupleLiteral(node As BoundTupleLiteral) As BoundNode Return VisitTupleExpression(node) End Function Public Overrides Function VisitConvertedTupleLiteral(node As BoundConvertedTupleLiteral) As BoundNode Return VisitTupleExpression(node) End Function Private Function VisitTupleExpression(node As BoundTupleExpression) As BoundNode Dim rewrittenArguments As ImmutableArray(Of BoundExpression) = VisitList(node.Arguments) Return RewriteTupleCreationExpression(node, rewrittenArguments) End Function ''' <summary> ''' Converts the expression for creating a tuple instance into an expression creating a ValueTuple (if short) or nested ValueTuples (if longer). ''' ''' For instance, for a long tuple we'll generate: ''' creationExpression(ctor=largestCtor, args=firstArgs+(nested creationExpression for remainder, with smaller ctor and next few args)) ''' </summary> Private Function RewriteTupleCreationExpression(node As BoundTupleExpression, rewrittenArguments As ImmutableArray(Of BoundExpression)) As BoundExpression Return MakeTupleCreationExpression(node.Syntax, DirectCast(node.Type, NamedTypeSymbol), rewrittenArguments) End Function Private Function MakeTupleCreationExpression(syntax As SyntaxNode, type As NamedTypeSymbol, rewrittenArguments As ImmutableArray(Of BoundExpression)) As BoundExpression Dim underlyingTupleType As NamedTypeSymbol = If(type.TupleUnderlyingType, type) Debug.Assert(underlyingTupleType.IsTupleCompatible()) Dim underlyingTupleTypeChain As ArrayBuilder(Of NamedTypeSymbol) = ArrayBuilder(Of NamedTypeSymbol).GetInstance() TupleTypeSymbol.GetUnderlyingTypeChain(underlyingTupleType, underlyingTupleTypeChain) Try ' make a creation expression for the smallest type Dim smallestType As NamedTypeSymbol = underlyingTupleTypeChain.Pop() Dim smallestCtorArguments As ImmutableArray(Of BoundExpression) = ImmutableArray.Create(rewrittenArguments, underlyingTupleTypeChain.Count * (TupleTypeSymbol.RestPosition - 1), smallestType.Arity) Dim smallestCtor As MethodSymbol = DirectCast(TupleTypeSymbol.GetWellKnownMemberInType(smallestType.OriginalDefinition, TupleTypeSymbol.GetTupleCtor(smallestType.Arity), _diagnostics, syntax), MethodSymbol) If smallestCtor Is Nothing Then Return New BoundBadExpression( syntax, LookupResultKind.Empty, ImmutableArray(Of Symbol).Empty, rewrittenArguments, type, hasErrors:=True) End If Dim smallestConstructor As MethodSymbol = smallestCtor.AsMember(smallestType) Dim currentCreation As BoundObjectCreationExpression = New BoundObjectCreationExpression(syntax, smallestConstructor, smallestCtorArguments, initializerOpt:=Nothing, type:=smallestType) If underlyingTupleTypeChain.Count > 0 Then Dim tuple8Type As NamedTypeSymbol = underlyingTupleTypeChain.Peek() Dim tuple8Ctor As MethodSymbol = DirectCast(TupleTypeSymbol.GetWellKnownMemberInType(tuple8Type.OriginalDefinition, TupleTypeSymbol.GetTupleCtor(TupleTypeSymbol.RestPosition), _diagnostics, syntax), MethodSymbol) If tuple8Ctor Is Nothing Then Return New BoundBadExpression( syntax, LookupResultKind.Empty, ImmutableArray(Of Symbol).Empty, rewrittenArguments, type, hasErrors:=True) End If ' make successively larger creation expressions containing the previous one Do Dim ctorArguments As ImmutableArray(Of BoundExpression) = ImmutableArray.Create(rewrittenArguments, (underlyingTupleTypeChain.Count - 1) * (TupleTypeSymbol.RestPosition - 1), TupleTypeSymbol.RestPosition - 1).Add(currentCreation) Dim constructor As MethodSymbol = tuple8Ctor.AsMember(underlyingTupleTypeChain.Pop()) currentCreation = New BoundObjectCreationExpression(syntax, constructor, ctorArguments, initializerOpt:=Nothing, type:=constructor.ContainingType) Loop While (underlyingTupleTypeChain.Count > 0) End If currentCreation = currentCreation.Update( currentCreation.ConstructorOpt, methodGroupOpt:=Nothing, arguments:=currentCreation.Arguments, defaultArguments:=currentCreation.DefaultArguments, initializerOpt:=currentCreation.InitializerOpt, type:=type) Return currentCreation Finally underlyingTupleTypeChain.Free() End Try End Function End Class End Namespace
-1
dotnet/roslyn
55,428
Test adding nested namespaces
Fixes https://github.com/dotnet/roslyn/issues/54939 The "workaround" that's already implemented is actually the correct behavior.
tmat
2021-08-05T01:19:03Z
2021-08-11T18:38:54Z
bc874ebc5111a2a33221409f895953b1536f6612
1cbbd423e17b186a8f1de89febb4db9a386d180d
Test adding nested namespaces. Fixes https://github.com/dotnet/roslyn/issues/54939 The "workaround" that's already implemented is actually the correct behavior.
./src/Compilers/VisualBasic/Portable/Symbols/Source/SourceMethodSymbol.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.Reflection Imports System.Runtime.InteropServices Imports System.Threading Imports Microsoft.Cci Imports Microsoft.CodeAnalysis.PooledObjects Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports CallingConvention = Microsoft.Cci.CallingConvention ' to resolve ambiguity with System.Runtime.InteropServices.CallingConvention Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols ''' <summary> ''' Base class for method symbols that are associated with some syntax and can receive custom attributes (directly or indirectly via another source symbol). ''' </summary> Friend MustInherit Class SourceMethodSymbol Inherits MethodSymbol Implements IAttributeTargetSymbol ' Flags about the method Protected ReadOnly m_flags As SourceMemberFlags ' Containing symbol Protected ReadOnly m_containingType As NamedTypeSymbol ' Me parameter. Private _lazyMeParameter As ParameterSymbol ' TODO (tomat): should be private ' Attributes on method. Set once after construction. IsNull means not set. Protected m_lazyCustomAttributesBag As CustomAttributesBag(Of VisualBasicAttributeData) ' TODO (tomat): should be private ' Return type attributes. IsNull means not set. Protected m_lazyReturnTypeCustomAttributesBag As CustomAttributesBag(Of VisualBasicAttributeData) ' The syntax references for the primary (non-partial) declarations. ' Nothing if there are only partial declarations. Protected ReadOnly m_syntaxReferenceOpt As SyntaxReference ' Location(s) Private _lazyLocations As ImmutableArray(Of Location) Private _lazyDocComment As String Private _lazyExpandedDocComment As String 'Nothing if diags have never been computed. Initial binding diagnostics 'are stashed here to optimize API usage patterns 'where method body diagnostics are requested multiple times. Private _cachedDiagnostics As ImmutableArray(Of Diagnostic) Protected Sub New(containingType As NamedTypeSymbol, flags As SourceMemberFlags, syntaxRef As SyntaxReference, Optional locations As ImmutableArray(Of Location) = Nothing) Debug.Assert(TypeOf containingType Is SourceMemberContainerTypeSymbol OrElse TypeOf containingType Is SynthesizedEventDelegateSymbol) m_containingType = containingType m_flags = flags m_syntaxReferenceOpt = syntaxRef ' calculated lazily if not initialized _lazyLocations = locations End Sub #Region "Factories" ' Create a regular method, with the given, name, declarator, and declaration syntax. Friend Shared Function CreateRegularMethod(container As SourceMemberContainerTypeSymbol, syntax As MethodStatementSyntax, binder As Binder, diagBag As DiagnosticBag) As SourceMethodSymbol ' Flags Dim methodModifiers = DecodeMethodModifiers(syntax.Modifiers, container, binder, diagBag) Dim flags = methodModifiers.AllFlags Or SourceMemberFlags.MethodKindOrdinary If syntax.Kind = SyntaxKind.SubStatement Then flags = flags Or SourceMemberFlags.MethodIsSub End If If syntax.HandlesClause IsNot Nothing Then flags = flags Or SourceMemberFlags.MethodHandlesEvents End If 'Name Dim name As String = syntax.Identifier.ValueText Dim handledEvents As ImmutableArray(Of HandledEvent) If syntax.HandlesClause IsNot Nothing Then If container.TypeKind = TYPEKIND.Structure Then ' Structures cannot handle events binder.ReportDiagnostic(diagBag, syntax.Identifier, ERRID.ERR_StructsCannotHandleEvents) ElseIf container.IsInterface Then ' Methods in interfaces cannot have an handles clause binder.ReportDiagnostic(diagBag, syntax.HandlesClause, ERRID.ERR_BadInterfaceMethodFlags1, syntax.HandlesClause.HandlesKeyword.ToString) ElseIf GetTypeParameterListSyntax(syntax) IsNot Nothing Then ' Generic methods cannot have 'handles' clause binder.ReportDiagnostic(diagBag, syntax.Identifier, ERRID.ERR_HandlesInvalidOnGenericMethod) End If ' Operators methods cannot have Handles regardless of container. 'That error (ERR_InvalidHandles) is reported in parser. ' handled events will be lazily constructed: handledEvents = Nothing Else ' there is no handles clause, so it will be Empty anyways handledEvents = ImmutableArray(Of HandledEvent).Empty End If Dim arity = If(syntax.TypeParameterList Is Nothing, 0, syntax.TypeParameterList.Parameters.Count) Dim methodSym As New SourceMemberMethodSymbol( container, name, flags, binder, syntax, arity, handledEvents) If methodSym.IsPartial AndAlso methodSym.IsSub Then If methodSym.IsAsync Then binder.ReportDiagnostic(diagBag, syntax.Identifier, ERRID.ERR_PartialMethodsMustNotBeAsync1, name) End If ReportPartialMethodErrors(syntax.Modifiers, binder, diagBag) End If Return methodSym End Function Friend Shared Function GetTypeParameterListSyntax(methodSyntax As MethodBaseSyntax) As TypeParameterListSyntax If methodSyntax.Kind = SyntaxKind.SubStatement OrElse methodSyntax.Kind = SyntaxKind.FunctionStatement Then Return DirectCast(methodSyntax, MethodStatementSyntax).TypeParameterList End If Return Nothing End Function Private Shared Sub ReportPartialMethodErrors(modifiers As SyntaxTokenList, binder As Binder, diagBag As DiagnosticBag) ' Handle partial methods related errors Dim reportPartialMethodsMustBePrivate As Boolean = True Dim partialToken As SyntaxToken = Nothing Dim modifierList = modifiers.ToList() For index = 0 To modifierList.Count - 1 Dim token As SyntaxToken = modifierList(index) Select Case token.Kind Case SyntaxKind.PublicKeyword, SyntaxKind.MustOverrideKeyword, SyntaxKind.NotOverridableKeyword, SyntaxKind.OverridableKeyword, SyntaxKind.OverridesKeyword, SyntaxKind.MustInheritKeyword lReportErrorOnSingleToken: ' Report [Partial methods must be declared 'Private' instead of '...'] binder.ReportDiagnostic(diagBag, token, ERRID.ERR_OnlyPrivatePartialMethods1, SyntaxFacts.GetText(token.Kind)) reportPartialMethodsMustBePrivate = False Case SyntaxKind.ProtectedKeyword ' Check for 'Protected Friend' If index >= modifierList.Count - 1 OrElse modifierList(index + 1).Kind <> SyntaxKind.FriendKeyword Then GoTo lReportErrorOnSingleToken End If lReportErrorOnTwoTokens: index += 1 Dim nextToken As SyntaxToken = modifierList(index) Dim startLoc As Integer = Math.Min(token.SpanStart, nextToken.SpanStart) Dim endLoc As Integer = Math.Max(token.Span.End, nextToken.Span.End) Dim location = binder.SyntaxTree.GetLocation(New TextSpan(startLoc, endLoc - startLoc)) ' Report [Partial methods must be declared 'Private' instead of '...'] binder.ReportDiagnostic(diagBag, location, ERRID.ERR_OnlyPrivatePartialMethods1, token.Kind.GetText() & " " & nextToken.Kind.GetText()) reportPartialMethodsMustBePrivate = False Case SyntaxKind.FriendKeyword ' Check for 'Friend Protected' If index >= modifierList.Count - 1 OrElse modifierList(index + 1).Kind <> SyntaxKind.ProtectedKeyword Then GoTo lReportErrorOnSingleToken End If GoTo lReportErrorOnTwoTokens Case SyntaxKind.PartialKeyword partialToken = token Case SyntaxKind.PrivateKeyword reportPartialMethodsMustBePrivate = False End Select Next If reportPartialMethodsMustBePrivate Then ' Report [Partial methods must be declared 'Private'] Debug.Assert(partialToken.Kind = SyntaxKind.PartialKeyword) binder.ReportDiagnostic(diagBag, partialToken, ERRID.ERR_PartialMethodsMustBePrivate) End If End Sub ''' <summary> ''' Creates a method symbol for Declare Sub or Function. ''' </summary> Friend Shared Function CreateDeclareMethod(container As SourceMemberContainerTypeSymbol, syntax As DeclareStatementSyntax, binder As Binder, diagBag As DiagnosticBag) As SourceMethodSymbol Dim methodModifiers = binder.DecodeModifiers( syntax.Modifiers, SourceMemberFlags.AllAccessibilityModifiers Or SourceMemberFlags.Overloads Or SourceMemberFlags.Shadows, ERRID.ERR_BadDeclareFlags1, Accessibility.Public, diagBag) ' modifiers: Protected and Overloads in Modules and Structures: If container.TypeKind = TYPEKIND.Module Then If (methodModifiers.FoundFlags And SourceMemberFlags.Overloads) <> 0 Then Dim keyword = syntax.Modifiers.First(Function(m) m.Kind = SyntaxKind.OverloadsKeyword) diagBag.Add(ERRID.ERR_OverloadsModifierInModule, keyword.GetLocation(), keyword.ValueText) ElseIf (methodModifiers.FoundFlags And SourceMemberFlags.Protected) <> 0 Then Dim keyword = syntax.Modifiers.First(Function(m) m.Kind = SyntaxKind.ProtectedKeyword) diagBag.Add(ERRID.ERR_ModuleCantUseDLLDeclareSpecifier1, keyword.GetLocation(), keyword.ValueText) End If ElseIf container.TypeKind = TYPEKIND.Structure Then If (methodModifiers.FoundFlags And SourceMemberFlags.Protected) <> 0 Then Dim keyword = syntax.Modifiers.First(Function(m) m.Kind = SyntaxKind.ProtectedKeyword) diagBag.Add(ERRID.ERR_StructCantUseDLLDeclareSpecifier1, keyword.GetLocation(), keyword.ValueText) End If End If ' not allowed in generic context If container IsNot Nothing AndAlso container.IsGenericType Then diagBag.Add(ERRID.ERR_DeclaresCantBeInGeneric, syntax.Identifier.GetLocation()) End If Dim flags = methodModifiers.AllFlags Or SourceMemberFlags.MethodKindDeclare Or SourceMemberFlags.Shared If syntax.Kind = SyntaxKind.DeclareSubStatement Then flags = flags Or SourceMemberFlags.MethodIsSub End If Dim name As String = syntax.Identifier.ValueText ' module name Dim moduleName As String = syntax.LibraryName.Token.ValueText If String.IsNullOrEmpty(moduleName) AndAlso Not syntax.LibraryName.IsMissing Then diagBag.Add(ERRID.ERR_BadAttribute1, syntax.LibraryName.GetLocation(), name) moduleName = Nothing End If ' entry point name Dim entryPointName As String If syntax.AliasName IsNot Nothing Then entryPointName = syntax.AliasName.Token.ValueText If String.IsNullOrEmpty(entryPointName) Then diagBag.Add(ERRID.ERR_BadAttribute1, syntax.LibraryName.GetLocation(), name) entryPointName = Nothing End If Else ' If alias syntax not specified use Nothing - the emitter will fill in the metadata method name and ' the users can determine whether or not it was specified. entryPointName = Nothing End If Dim importData = New DllImportData(moduleName, entryPointName, GetPInvokeAttributes(syntax)) Return New SourceDeclareMethodSymbol(container, name, flags, binder, syntax, importData) End Function Private Shared Function GetPInvokeAttributes(syntax As DeclareStatementSyntax) As MethodImportAttributes Dim result As MethodImportAttributes Select Case syntax.CharsetKeyword.Kind Case SyntaxKind.None, SyntaxKind.AnsiKeyword result = MethodImportAttributes.CharSetAnsi Or MethodImportAttributes.ExactSpelling Case SyntaxKind.UnicodeKeyword result = MethodImportAttributes.CharSetUnicode Or MethodImportAttributes.ExactSpelling Case SyntaxKind.AutoKeyword result = MethodImportAttributes.CharSetAuto End Select Return result Or MethodImportAttributes.CallingConventionWinApi Or MethodImportAttributes.SetLastError End Function Friend Shared Function CreateOperator( container As SourceMemberContainerTypeSymbol, syntax As OperatorStatementSyntax, binder As Binder, diagBag As DiagnosticBag ) As SourceMethodSymbol ' Flags Dim methodModifiers = DecodeOperatorModifiers(syntax, binder, diagBag) Dim flags = methodModifiers.AllFlags Debug.Assert((flags And SourceMemberFlags.AccessibilityPublic) <> 0) Debug.Assert((flags And SourceMemberFlags.Shared) <> 0) 'Name Dim name As String = GetMemberNameFromSyntax(syntax) Debug.Assert(name.Equals(WellKnownMemberNames.ImplicitConversionName) = ((flags And SourceMemberFlags.Widening) <> 0)) Debug.Assert(name.Equals(WellKnownMemberNames.ExplicitConversionName) = ((flags And SourceMemberFlags.Narrowing) <> 0)) Dim paramCountMismatchERRID As ERRID Select Case syntax.OperatorToken.Kind Case SyntaxKind.NotKeyword, SyntaxKind.IsTrueKeyword, SyntaxKind.IsFalseKeyword, SyntaxKind.CTypeKeyword paramCountMismatchERRID = ERRID.ERR_OneParameterRequired1 Case SyntaxKind.PlusToken, SyntaxKind.MinusToken paramCountMismatchERRID = ERRID.ERR_OneOrTwoParametersRequired1 Case SyntaxKind.AsteriskToken, SyntaxKind.SlashToken, SyntaxKind.BackslashToken, SyntaxKind.ModKeyword, SyntaxKind.CaretToken, SyntaxKind.EqualsToken, SyntaxKind.LessThanGreaterThanToken, SyntaxKind.LessThanToken, SyntaxKind.GreaterThanToken, SyntaxKind.LessThanEqualsToken, SyntaxKind.GreaterThanEqualsToken, SyntaxKind.LikeKeyword, SyntaxKind.AmpersandToken, SyntaxKind.AndKeyword, SyntaxKind.OrKeyword, SyntaxKind.XorKeyword, SyntaxKind.LessThanLessThanToken, SyntaxKind.GreaterThanGreaterThanToken paramCountMismatchERRID = ERRID.ERR_TwoParametersRequired1 Case Else Throw ExceptionUtilities.UnexpectedValue(syntax.OperatorToken.Kind) End Select Select Case paramCountMismatchERRID Case ERRID.ERR_OneParameterRequired1 Debug.Assert(OverloadResolution.GetOperatorInfo(name).ParamCount = 1) If syntax.ParameterList.Parameters.Count = 1 Then paramCountMismatchERRID = 0 End If Case ERRID.ERR_TwoParametersRequired1 Debug.Assert(OverloadResolution.GetOperatorInfo(name).ParamCount = 2) If syntax.ParameterList.Parameters.Count = 2 Then paramCountMismatchERRID = 0 End If Case ERRID.ERR_OneOrTwoParametersRequired1 If syntax.ParameterList.Parameters.Count = 1 OrElse 2 = syntax.ParameterList.Parameters.Count Then Debug.Assert(OverloadResolution.GetOperatorInfo(name).ParamCount = syntax.ParameterList.Parameters.Count) paramCountMismatchERRID = 0 End If Case Else Throw ExceptionUtilities.UnexpectedValue(paramCountMismatchERRID) End Select If paramCountMismatchERRID <> 0 Then binder.ReportDiagnostic(diagBag, syntax.OperatorToken, paramCountMismatchERRID, SyntaxFacts.GetText(syntax.OperatorToken.Kind)) End If ' ERRID.ERR_OperatorDeclaredInModule is reported by the parser. flags = flags Or If(syntax.OperatorToken.Kind = SyntaxKind.CTypeKeyword, SourceMemberFlags.MethodKindConversion, SourceMemberFlags.MethodKindOperator) Return New SourceMemberMethodSymbol( container, name, flags, binder, syntax, arity:=0) End Function ' Create a constructor. Friend Shared Function CreateConstructor(container As SourceMemberContainerTypeSymbol, syntax As SubNewStatementSyntax, binder As Binder, diagBag As DiagnosticBag) As SourceMethodSymbol ' Flags Dim modifiers = DecodeConstructorModifiers(syntax.Modifiers, container, binder, diagBag) Dim flags = modifiers.AllFlags Or SourceMemberFlags.MethodIsSub ' Name, Kind Dim name As String If (flags And SourceMemberFlags.Shared) <> 0 Then name = WellKnownMemberNames.StaticConstructorName flags = flags Or SourceMemberFlags.MethodKindSharedConstructor If (syntax.ParameterList IsNot Nothing AndAlso syntax.ParameterList.Parameters.Count > 0) Then ' shared constructor cannot have parameters. binder.ReportDiagnostic(diagBag, syntax.ParameterList, ERRID.ERR_SharedConstructorWithParams) End If Else name = WellKnownMemberNames.InstanceConstructorName flags = flags Or SourceMemberFlags.MethodKindConstructor End If Dim methodSym As New SourceMemberMethodSymbol(container, name, flags, binder, syntax, arity:=0) If (flags And SourceMemberFlags.Shared) = 0 Then If container.TypeKind = TYPEKIND.Structure AndAlso methodSym.ParameterCount = 0 Then ' Instance constructor must have parameters. binder.ReportDiagnostic(diagBag, syntax.NewKeyword, ERRID.ERR_NewInStruct) End If End If Return methodSym End Function ' Decode the modifiers on the method, reporting errors where applicable. Private Shared Function DecodeMethodModifiers(modifiers As SyntaxTokenList, container As SourceMemberContainerTypeSymbol, binder As Binder, diagBag As DiagnosticBag) As MemberModifiers ' Decode the flags. Dim methodModifiers = binder.DecodeModifiers(modifiers, SourceMemberFlags.AllAccessibilityModifiers Or SourceMemberFlags.Overloads Or SourceMemberFlags.Partial Or SourceMemberFlags.Shadows Or SourceMemberFlags.Shared Or SourceMemberFlags.Overridable Or SourceMemberFlags.NotOverridable Or SourceMemberFlags.Overrides Or SourceMemberFlags.MustOverride Or SourceMemberFlags.Async Or SourceMemberFlags.Iterator, ERRID.ERR_BadMethodFlags1, Accessibility.Public, diagBag) methodModifiers = binder.ValidateSharedPropertyAndMethodModifiers(modifiers, methodModifiers, False, container, diagBag) Const asyncIterator As SourceMemberFlags = SourceMemberFlags.Async Or SourceMemberFlags.Iterator If (methodModifiers.FoundFlags And asyncIterator) = asyncIterator Then binder.ReportModifierError(modifiers, ERRID.ERR_InvalidAsyncIteratorModifiers, diagBag, InvalidAsyncIterator) End If Return methodModifiers End Function ''' <summary> ''' Decode the modifiers on a user-defined operator, reporting errors where applicable. ''' </summary> Private Shared Function DecodeOperatorModifiers(syntax As OperatorStatementSyntax, binder As Binder, diagBag As DiagnosticBag) As MemberModifiers ' Decode the flags. Dim allowModifiers As SourceMemberFlags = SourceMemberFlags.AllAccessibilityModifiers Or SourceMemberFlags.Shared Or SourceMemberFlags.Overloads Or SourceMemberFlags.Shadows Or SourceMemberFlags.Widening Or SourceMemberFlags.Narrowing Dim operatorModifiers = binder.DecodeModifiers(syntax.Modifiers, allowModifiers, ERRID.ERR_BadOperatorFlags1, Accessibility.Public, diagBag) Dim foundFlags As SourceMemberFlags = operatorModifiers.FoundFlags Dim computedFlags As SourceMemberFlags = operatorModifiers.ComputedFlags ' It is OK to remove/add flags from the found list once an error is reported Dim foundAccessibility = foundFlags And SourceMemberFlags.AllAccessibilityModifiers If foundAccessibility <> 0 AndAlso foundAccessibility <> SourceMemberFlags.Public Then binder.ReportModifierError(syntax.Modifiers, ERRID.ERR_OperatorMustBePublic, diagBag, SyntaxKind.PrivateKeyword, SyntaxKind.ProtectedKeyword, SyntaxKind.FriendKeyword) foundFlags = foundFlags And Not SourceMemberFlags.AllAccessibilityModifiers computedFlags = (computedFlags And Not SourceMemberFlags.AccessibilityMask) Or SourceMemberFlags.AccessibilityPublic End If If (foundFlags And SourceMemberFlags.Shared) = 0 Then binder.ReportDiagnostic(diagBag, syntax.OperatorToken, ERRID.ERR_OperatorMustBeShared) computedFlags = computedFlags Or SourceMemberFlags.Shared End If If syntax.OperatorToken.Kind = SyntaxKind.CTypeKeyword Then If (foundFlags And (SourceMemberFlags.Narrowing Or SourceMemberFlags.Widening)) = 0 Then binder.ReportDiagnostic(diagBag, syntax.OperatorToken, ERRID.ERR_ConvMustBeWideningOrNarrowing) computedFlags = computedFlags Or SourceMemberFlags.Narrowing End If ElseIf (foundFlags And (SourceMemberFlags.Narrowing Or SourceMemberFlags.Widening)) <> 0 Then binder.ReportModifierError(syntax.Modifiers, ERRID.ERR_InvalidSpecifierOnNonConversion1, diagBag, SyntaxKind.NarrowingKeyword, SyntaxKind.WideningKeyword) foundFlags = foundFlags And Not (SourceMemberFlags.Narrowing Or SourceMemberFlags.Widening) End If Return New MemberModifiers(foundFlags, computedFlags) End Function ' Decode the modifiers on a constructor, reporting errors where applicable. Constructors are more restrictive ' than regular methods, so they have more errors. Friend Shared Function DecodeConstructorModifiers(modifiers As SyntaxTokenList, container As SourceMemberContainerTypeSymbol, binder As Binder, diagBag As DiagnosticBag) As MemberModifiers Dim constructorModifiers = DecodeMethodModifiers(modifiers, container, binder, diagBag) Dim flags = constructorModifiers.FoundFlags Dim computedFlags = constructorModifiers.ComputedFlags ' It is OK to remove flags from the found list once an error is reported If (flags And (SourceMemberFlags.MustOverride Or SourceMemberFlags.Overridable Or SourceMemberFlags.NotOverridable Or SourceMemberFlags.Shadows)) <> 0 Then binder.ReportModifierError(modifiers, ERRID.ERR_BadFlagsOnNew1, diagBag, SyntaxKind.OverridableKeyword, SyntaxKind.MustOverrideKeyword, SyntaxKind.NotOverridableKeyword, SyntaxKind.ShadowsKeyword) flags = flags And Not (SourceMemberFlags.MustOverride Or SourceMemberFlags.Overridable Or SourceMemberFlags.NotOverridable Or SourceMemberFlags.Shadows) End If If (flags And SourceMemberFlags.Overrides) <> 0 Then binder.ReportModifierError(modifiers, ERRID.ERR_CantOverrideConstructor, diagBag, SyntaxKind.OverridesKeyword) flags = flags And Not SourceMemberFlags.Overrides End If If (flags And SourceMemberFlags.Partial) <> 0 Then binder.ReportModifierError(modifiers, ERRID.ERR_ConstructorCannotBeDeclaredPartial, diagBag, SyntaxKind.PartialKeyword) flags = flags And Not SourceMemberFlags.Partial End If If (flags And SourceMemberFlags.Overloads) <> 0 Then binder.ReportModifierError(modifiers, ERRID.ERR_BadFlagsOnNewOverloads, diagBag, SyntaxKind.OverloadsKeyword) flags = flags And Not SourceMemberFlags.Overloads End If If (flags And SourceMemberFlags.Async) <> 0 Then binder.ReportModifierError(modifiers, ERRID.ERR_ConstructorAsync, diagBag, SyntaxKind.AsyncKeyword) End If If ((constructorModifiers.AllFlags And SourceMemberFlags.Shared) <> 0) Then If (flags And SourceMemberFlags.AllAccessibilityModifiers) <> 0 Then ' Shared constructors can't be declared with accessibility modifiers binder.ReportModifierError(modifiers, ERRID.ERR_SharedConstructorIllegalSpec1, diagBag, SyntaxKind.PublicKeyword, SyntaxKind.PrivateKeyword, SyntaxKind.FriendKeyword, SyntaxKind.ProtectedKeyword) End If flags = (flags And Not SourceMemberFlags.AllAccessibilityModifiers) Or SourceMemberFlags.Private computedFlags = (computedFlags And Not SourceMemberFlags.AccessibilityMask) Or SourceMemberFlags.AccessibilityPrivate End If Return New MemberModifiers(flags, computedFlags) End Function #End Region Friend Overrides Sub GenerateDeclarationErrors(cancellationToken As CancellationToken) MyBase.GenerateDeclarationErrors(cancellationToken) ' Force signature in methods. Dim unusedType = Me.ReturnType Dim unusedAttributes = Me.GetReturnTypeAttributes() For Each parameter In Me.Parameters unusedAttributes = parameter.GetAttributes() If parameter.HasExplicitDefaultValue Then Dim defaultValue = parameter.ExplicitDefaultConstantValue() End If Next ' Ensure method type parameter constraints are resolved and checked. For Each typeParameter In Me.TypeParameters Dim unusedTypes = typeParameter.ConstraintTypesNoUseSiteDiagnostics Next ' Ensure Handles are resolved. Dim unusedHandles = Me.HandledEvents End Sub Friend ReadOnly Property Diagnostics As ImmutableArray(Of Diagnostic) Get Return _cachedDiagnostics End Get End Property ''' <summary> ''' Returns true if our diagnostics were used in the event that there were two threads racing. ''' </summary> Friend Function SetDiagnostics(diags As ImmutableArray(Of Diagnostic)) As Boolean Return ImmutableInterlocked.InterlockedInitialize(_cachedDiagnostics, diags) End Function Public Overrides ReadOnly Property IsImplicitlyDeclared As Boolean Get Return m_containingType.AreMembersImplicitlyDeclared End Get End Property Friend Overrides ReadOnly Property GenerateDebugInfoImpl As Boolean Get Return True End Get End Property Public NotOverridable Overrides ReadOnly Property ConstructedFrom As MethodSymbol Get Return Me End Get End Property Public NotOverridable Overrides ReadOnly Property ContainingSymbol As Symbol Get Return m_containingType End Get End Property Public Overrides ReadOnly Property ContainingType As NamedTypeSymbol Get Return m_containingType End Get End Property Public ReadOnly Property ContainingSourceModule As SourceModuleSymbol Get Return DirectCast(ContainingModule, SourceModuleSymbol) End Get End Property Public Overrides ReadOnly Property AssociatedSymbol As Symbol Get ' TODO: Associated property/event not implemented. Return Nothing End Get End Property Public Overrides ReadOnly Property ExplicitInterfaceImplementations As ImmutableArray(Of MethodSymbol) Get Return ImmutableArray(Of MethodSymbol).Empty End Get End Property #Region "Flags" Public Overrides ReadOnly Property MethodKind As MethodKind Get Return m_flags.ToMethodKind() End Get End Property Friend NotOverridable Overrides ReadOnly Property IsMethodKindBasedOnSyntax As Boolean Get Return True End Get End Property ' TODO (tomat): NotOverridable? Public Overrides ReadOnly Property DeclaredAccessibility As Accessibility Get Return CType((m_flags And SourceMemberFlags.AccessibilityMask), Accessibility) End Get End Property Public NotOverridable Overrides ReadOnly Property IsMustOverride As Boolean Get Return (m_flags And SourceMemberFlags.MustOverride) <> 0 End Get End Property Public NotOverridable Overrides ReadOnly Property IsNotOverridable As Boolean Get Return (m_flags And SourceMemberFlags.NotOverridable) <> 0 End Get End Property Public NotOverridable Overrides ReadOnly Property IsOverloads As Boolean Get If (m_flags And SourceMemberFlags.Shadows) <> 0 Then Return False ElseIf (m_flags And SourceMemberFlags.Overloads) <> 0 Then Return True Else Return (m_flags And SourceMemberFlags.Overrides) <> 0 End If End Get End Property Public NotOverridable Overrides ReadOnly Property IsOverridable As Boolean Get Return (m_flags And SourceMemberFlags.Overridable) <> 0 End Get End Property Public NotOverridable Overrides ReadOnly Property IsOverrides As Boolean Get Return (m_flags And SourceMemberFlags.Overrides) <> 0 End Get End Property Public NotOverridable Overrides ReadOnly Property IsShared As Boolean Get Return (m_flags And SourceMemberFlags.Shared) <> 0 End Get End Property Friend ReadOnly Property IsPartial As Boolean Get Return (m_flags And SourceMemberFlags.Partial) <> 0 End Get End Property ''' <summary> ''' True if 'Shadows' is explicitly specified in method's declaration. ''' </summary> Friend Overrides ReadOnly Property ShadowsExplicitly As Boolean ' TODO (tomat) : NotOverridable? Get Return (m_flags And SourceMemberFlags.Shadows) <> 0 End Get End Property ''' <summary> ''' True if 'Overloads' is explicitly specified in method's declaration. ''' </summary> Friend ReadOnly Property OverloadsExplicitly As Boolean Get Return (m_flags And SourceMemberFlags.Overloads) <> 0 End Get End Property ''' <summary> ''' True if 'Overrides' is explicitly specified in method's declaration. ''' </summary> Friend ReadOnly Property OverridesExplicitly As Boolean Get Return (m_flags And SourceMemberFlags.Overrides) <> 0 End Get End Property ''' <summary> ''' True if 'Handles' is specified in method's declaration ''' </summary> Friend ReadOnly Property HandlesEvents As Boolean Get Return (m_flags And SourceMemberFlags.MethodHandlesEvents) <> 0 End Get End Property Friend NotOverridable Overrides ReadOnly Property CallingConvention As CallingConvention Get Return If(IsShared, CallingConvention.Default, CallingConvention.HasThis) Or If(IsGenericMethod, CallingConvention.Generic, CallingConvention.Default) End Get End Property #End Region #Region "Syntax and Binding" ' Return the entire declaration block: Begin Statement + Body Statements + End Statement. Friend ReadOnly Property BlockSyntax As MethodBlockBaseSyntax Get If m_syntaxReferenceOpt Is Nothing Then Return Nothing End If Dim decl = m_syntaxReferenceOpt.GetSyntax() Return TryCast(decl.Parent, MethodBlockBaseSyntax) End Get End Property Friend Overrides ReadOnly Property Syntax As SyntaxNode Get If m_syntaxReferenceOpt Is Nothing Then Return Nothing End If ' usually the syntax of a source method symbol should be the block syntax Dim syntaxNode = Me.BlockSyntax If syntaxNode IsNot Nothing Then Return syntaxNode End If ' in case of a method in an interface there is no block. ' just return the sub/function statement in this case. Return m_syntaxReferenceOpt.GetVisualBasicSyntax() End Get End Property ' Return the syntax tree that contains the method block. Public ReadOnly Property SyntaxTree As SyntaxTree Get If m_syntaxReferenceOpt IsNot Nothing Then Return m_syntaxReferenceOpt.SyntaxTree End If Return Nothing End Get End Property Friend ReadOnly Property DeclarationSyntax As MethodBaseSyntax Get Return If(m_syntaxReferenceOpt IsNot Nothing, DirectCast(m_syntaxReferenceOpt.GetSyntax(), MethodBaseSyntax), Nothing) End Get End Property Friend Overridable ReadOnly Property HasEmptyBody As Boolean Get Dim blockSyntax = Me.BlockSyntax Return blockSyntax Is Nothing OrElse Not blockSyntax.Statements.Any End Get End Property Public Overrides ReadOnly Property DeclaringSyntaxReferences As ImmutableArray(Of SyntaxReference) Get Return GetDeclaringSyntaxReferenceHelper(m_syntaxReferenceOpt) End Get End Property Friend NotOverridable Overrides Function IsDefinedInSourceTree(tree As SyntaxTree, definedWithinSpan As TextSpan?, Optional cancellationToken As CancellationToken = Nothing) As Boolean Return IsDefinedInSourceTree(Me.Syntax, tree, definedWithinSpan, cancellationToken) End Function Public NotOverridable Overrides Function GetDocumentationCommentXml(Optional preferredCulture As CultureInfo = Nothing, Optional expandIncludes As Boolean = False, Optional cancellationToken As CancellationToken = Nothing) As String If expandIncludes Then Return GetAndCacheDocumentationComment(Me, preferredCulture, expandIncludes, _lazyExpandedDocComment, cancellationToken) Else Return GetAndCacheDocumentationComment(Me, preferredCulture, expandIncludes, _lazyDocComment, cancellationToken) End If End Function ''' <summary> ''' Return the location from syntax reference only. ''' </summary> Friend ReadOnly Property NonMergedLocation As Location Get Return If(m_syntaxReferenceOpt IsNot Nothing, GetSymbolLocation(m_syntaxReferenceOpt), Nothing) End Get End Property Friend Overrides Function GetLexicalSortKey() As LexicalSortKey ' WARNING: this should not allocate memory! Return If(m_syntaxReferenceOpt IsNot Nothing, New LexicalSortKey(m_syntaxReferenceOpt, Me.DeclaringCompilation), LexicalSortKey.NotInSource) End Function Public Overrides ReadOnly Property Locations As ImmutableArray(Of Location) Get ' NOTE: access to m_locations don't really need to be synchronized because ' it is never being modified after the method symbol is published If _lazyLocations.IsDefault Then ' This symbol location Dim location As Location = Me.NonMergedLocation ImmutableInterlocked.InterlockedCompareExchange(Me._lazyLocations, If(location Is Nothing, ImmutableArray(Of Location).Empty, ImmutableArray.Create(location)), Nothing) End If Return _lazyLocations End Get End Property ' Given a syntax ref, get the symbol location to return. We return the location of the name ' of the method. Private Function GetSymbolLocation(syntaxRef As SyntaxReference) As Location Dim syntaxNode = syntaxRef.GetVisualBasicSyntax() Dim syntaxTree = syntaxRef.SyntaxTree Return syntaxTree.GetLocation(GetMethodLocationFromSyntax(syntaxNode)) End Function ' Get the location of a method given the syntax for its declaration. We use the location of the name ' of the method, or similar keywords. Private Shared Function GetMethodLocationFromSyntax(node As VisualBasicSyntaxNode) As TextSpan Select Case node.Kind Case SyntaxKind.MultiLineFunctionLambdaExpression, SyntaxKind.MultiLineSubLambdaExpression, SyntaxKind.SingleLineFunctionLambdaExpression, SyntaxKind.SingleLineSubLambdaExpression Return DirectCast(node, LambdaExpressionSyntax).SubOrFunctionHeader.Span Case SyntaxKind.SubStatement, SyntaxKind.FunctionStatement Return DirectCast(node, MethodStatementSyntax).Identifier.Span Case SyntaxKind.DeclareSubStatement, SyntaxKind.DeclareFunctionStatement Return DirectCast(node, DeclareStatementSyntax).Identifier.Span Case SyntaxKind.SubNewStatement Return DirectCast(node, SubNewStatementSyntax).NewKeyword.Span Case SyntaxKind.OperatorStatement Return DirectCast(node, OperatorStatementSyntax).OperatorToken.Span Case Else Throw ExceptionUtilities.UnexpectedValue(node.Kind) End Select End Function ''' <summary> ''' Bind the constraint declarations for the given type parameter. ''' </summary> ''' <remarks> ''' The caller is expected to handle constraint checking and any caching of results. ''' </remarks> Friend Function BindTypeParameterConstraints(syntax As TypeParameterSyntax, diagnostics As BindingDiagnosticBag) As ImmutableArray(Of TypeParameterConstraint) Dim binder As Binder = BinderBuilder.CreateBinderForType(Me.ContainingSourceModule, Me.SyntaxTree, m_containingType) binder = BinderBuilder.CreateBinderForGenericMethodDeclaration(Me, binder) ' Handle type parameter variance. If syntax.VarianceKeyword.Kind <> SyntaxKind.None Then binder.ReportDiagnostic(diagnostics, syntax.VarianceKeyword, ERRID.ERR_VarianceDisallowedHere) End If ' Wrap constraints binder in a location-specific binder to ' avoid checking constraints when binding type names. binder = New LocationSpecificBinder(BindingLocation.GenericConstraintsClause, Me, binder) Return binder.BindTypeParameterConstraintClause(Me, syntax.TypeParameterConstraintClause, diagnostics) End Function ' Get the symbol name that would be used for this method base syntax. Friend Shared Function GetMemberNameFromSyntax(node As MethodBaseSyntax) As String Select Case node.Kind Case SyntaxKind.SubStatement, SyntaxKind.FunctionStatement Return DirectCast(node, MethodStatementSyntax).Identifier.ValueText Case SyntaxKind.PropertyStatement Return DirectCast(node, PropertyStatementSyntax).Identifier.ValueText Case SyntaxKind.DeclareSubStatement, SyntaxKind.DeclareFunctionStatement Return DirectCast(node, DeclareStatementSyntax).Identifier.ValueText Case SyntaxKind.OperatorStatement Dim operatorStatement = DirectCast(node, OperatorStatementSyntax) Select Case operatorStatement.OperatorToken.Kind Case SyntaxKind.NotKeyword Return WellKnownMemberNames.OnesComplementOperatorName Case SyntaxKind.IsTrueKeyword Return WellKnownMemberNames.TrueOperatorName Case SyntaxKind.IsFalseKeyword Return WellKnownMemberNames.FalseOperatorName Case SyntaxKind.PlusToken If operatorStatement.ParameterList.Parameters.Count <= 1 Then Return WellKnownMemberNames.UnaryPlusOperatorName Else Return WellKnownMemberNames.AdditionOperatorName End If Case SyntaxKind.MinusToken If operatorStatement.ParameterList.Parameters.Count <= 1 Then Return WellKnownMemberNames.UnaryNegationOperatorName Else Return WellKnownMemberNames.SubtractionOperatorName End If Case SyntaxKind.AsteriskToken Return WellKnownMemberNames.MultiplyOperatorName Case SyntaxKind.SlashToken Return WellKnownMemberNames.DivisionOperatorName Case SyntaxKind.BackslashToken Return WellKnownMemberNames.IntegerDivisionOperatorName Case SyntaxKind.ModKeyword Return WellKnownMemberNames.ModulusOperatorName Case SyntaxKind.CaretToken Return WellKnownMemberNames.ExponentOperatorName Case SyntaxKind.EqualsToken Return WellKnownMemberNames.EqualityOperatorName Case SyntaxKind.LessThanGreaterThanToken Return WellKnownMemberNames.InequalityOperatorName Case SyntaxKind.LessThanToken Return WellKnownMemberNames.LessThanOperatorName Case SyntaxKind.GreaterThanToken Return WellKnownMemberNames.GreaterThanOperatorName Case SyntaxKind.LessThanEqualsToken Return WellKnownMemberNames.LessThanOrEqualOperatorName Case SyntaxKind.GreaterThanEqualsToken Return WellKnownMemberNames.GreaterThanOrEqualOperatorName Case SyntaxKind.LikeKeyword Return WellKnownMemberNames.LikeOperatorName Case SyntaxKind.AmpersandToken Return WellKnownMemberNames.ConcatenateOperatorName Case SyntaxKind.AndKeyword Return WellKnownMemberNames.BitwiseAndOperatorName Case SyntaxKind.OrKeyword Return WellKnownMemberNames.BitwiseOrOperatorName Case SyntaxKind.XorKeyword Return WellKnownMemberNames.ExclusiveOrOperatorName Case SyntaxKind.LessThanLessThanToken Return WellKnownMemberNames.LeftShiftOperatorName Case SyntaxKind.GreaterThanGreaterThanToken Return WellKnownMemberNames.RightShiftOperatorName Case SyntaxKind.CTypeKeyword For Each keywordSyntax In operatorStatement.Modifiers Dim currentModifier As SourceMemberFlags = Binder.MapKeywordToFlag(keywordSyntax) If currentModifier = SourceMemberFlags.Widening Then Return WellKnownMemberNames.ImplicitConversionName ElseIf currentModifier = SourceMemberFlags.Narrowing Then Return WellKnownMemberNames.ExplicitConversionName End If Next Return WellKnownMemberNames.ExplicitConversionName Case Else Throw ExceptionUtilities.UnexpectedValue(operatorStatement.OperatorToken.Kind) End Select Case SyntaxKind.SubNewStatement ' Symbol name of a constructor depends on if it is shared. We ideally we like to just call ' DecodeConstructorModifiers here, but we don't have a binder or container to pass. So we have ' to duplicate some of the logic just to determine if it is shared. Dim isShared As Boolean = False For Each tok In node.Modifiers If tok.Kind = SyntaxKind.SharedKeyword Then isShared = True End If Next ' inside a module are implicitly shared. If node.Parent IsNot Nothing Then If node.Parent.Kind = SyntaxKind.ModuleBlock OrElse (node.Parent.Parent IsNot Nothing AndAlso node.Parent.Parent.Kind = SyntaxKind.ModuleBlock) Then isShared = True End If End If Return If(isShared, WellKnownMemberNames.StaticConstructorName, WellKnownMemberNames.InstanceConstructorName) Case Else Throw ExceptionUtilities.UnexpectedValue(node.Kind) End Select End Function ' Given the syntax declaration, and a container, get the source method symbol declared from that syntax. ' This is done by lookup up the name from the declaration in the container, handling duplicates and ' so forth correctly. Friend Shared Function FindSymbolFromSyntax(syntax As MethodBaseSyntax, tree As SyntaxTree, container As NamedTypeSymbol) As Symbol Select Case syntax.Kind Case SyntaxKind.GetAccessorStatement, SyntaxKind.SetAccessorStatement Dim propertySyntax = TryCast(syntax.Parent.Parent, PropertyBlockSyntax) If propertySyntax IsNot Nothing Then Dim propertyIdentifier = propertySyntax.PropertyStatement.Identifier Dim propertySymbol = DirectCast( container.FindMember(propertyIdentifier.ValueText, SymbolKind.Property, propertyIdentifier.Span, tree), PropertySymbol) ' in case of ill formed syntax it can happen that the ContainingType of the actual binder does not directly contain ' this property symbol. One example is e.g. a namespace nested in a class. Instead of a namespace binder, the containing ' binder will be used in this error case and then member lookups will fail because the symbol of the containing binder does ' not contain these members. If propertySymbol Is Nothing Then Return Nothing End If Dim accessor = If(syntax.Kind = SyntaxKind.GetAccessorStatement, propertySymbol.GetMethod, propertySymbol.SetMethod) ' symbol must have same syntax as the accessor's block If accessor.Syntax Is syntax.Parent Then Return accessor Else ' This can happen if property has multiple accessors. ' Parser allows multiple accessors, but binder will accept only one of a kind Return Nothing End If Else ' Did not find a property block. Can happen if syntax was ill-formed. Return Nothing End If Case SyntaxKind.AddHandlerAccessorStatement, SyntaxKind.RemoveHandlerAccessorStatement, SyntaxKind.RaiseEventAccessorStatement Dim eventBlockSyntax = TryCast(syntax.Parent.Parent, EventBlockSyntax) If eventBlockSyntax IsNot Nothing Then Dim eventIdentifier = eventBlockSyntax.EventStatement.Identifier Dim eventSymbol = DirectCast( container.FindMember(eventIdentifier.ValueText, SymbolKind.Event, eventIdentifier.Span, tree), EventSymbol) ' in case of ill formed syntax it can happen that the ContainingType of the actual binder does not directly contain ' this event symbol. One example is e.g. a namespace nested in a class. Instead of a namespace binder, the containing ' binder will be used in this error case and then member lookups will fail because the symbol of the containing binder does ' not contain these members. If eventSymbol Is Nothing Then Return Nothing End If Dim accessor As MethodSymbol = Nothing Select Case syntax.Kind Case SyntaxKind.AddHandlerAccessorStatement accessor = eventSymbol.AddMethod Case SyntaxKind.RemoveHandlerAccessorStatement accessor = eventSymbol.RemoveMethod Case SyntaxKind.RaiseEventAccessorStatement accessor = eventSymbol.RaiseMethod End Select ' symbol must have same syntax as the accessor's block If accessor IsNot Nothing AndAlso accessor.Syntax Is syntax.Parent Then Return accessor Else ' This can happen if event has multiple accessors. ' Parser allows multiple accessors, but binder will accept only one of a kind Return Nothing End If Else ' Did not find an event block. Can happen if syntax was ill-formed. Return Nothing End If Case SyntaxKind.PropertyStatement Dim propertyIdentifier = DirectCast(syntax, PropertyStatementSyntax).Identifier Return container.FindMember(propertyIdentifier.ValueText, SymbolKind.Property, propertyIdentifier.Span, tree) Case SyntaxKind.EventStatement Dim eventIdentifier = DirectCast(syntax, EventStatementSyntax).Identifier Return container.FindMember(eventIdentifier.ValueText, SymbolKind.Event, eventIdentifier.Span, tree) Case SyntaxKind.DelegateFunctionStatement, SyntaxKind.DelegateSubStatement Dim delegateIdentifier = DirectCast(syntax, DelegateStatementSyntax).Identifier Return container.FindMember(delegateIdentifier.ValueText, SymbolKind.NamedType, delegateIdentifier.Span, tree) Case Else Dim methodSymbol = DirectCast(container.FindMember(GetMemberNameFromSyntax(syntax), SymbolKind.Method, GetMethodLocationFromSyntax(syntax), tree), MethodSymbol) ' Substitute with partial method implementation? If methodSymbol IsNot Nothing Then Dim partialImpl = methodSymbol.PartialImplementationPart If partialImpl IsNot Nothing AndAlso partialImpl.Syntax Is syntax.Parent Then methodSymbol = partialImpl End If End If Return methodSymbol End Select End Function ' Get the location of the implements name for an explicit implemented method, for later error reporting. Friend Function GetImplementingLocation(implementedMethod As MethodSymbol) As Location Debug.Assert(ExplicitInterfaceImplementations.Contains(implementedMethod)) Dim methodSyntax As MethodStatementSyntax = Nothing Dim syntaxTree As SyntaxTree = Nothing Dim containingSourceType = TryCast(m_containingType, SourceMemberContainerTypeSymbol) If m_syntaxReferenceOpt IsNot Nothing Then methodSyntax = TryCast(m_syntaxReferenceOpt.GetSyntax(), MethodStatementSyntax) syntaxTree = m_syntaxReferenceOpt.SyntaxTree End If If methodSyntax IsNot Nothing AndAlso methodSyntax.ImplementsClause IsNot Nothing AndAlso containingSourceType IsNot Nothing Then Dim binder As Binder = BinderBuilder.CreateBinderForType(containingSourceType.ContainingSourceModule, syntaxTree, containingSourceType) Dim implementingSyntax = FindImplementingSyntax(methodSyntax.ImplementsClause, Me, implementedMethod, containingSourceType, binder) Return implementingSyntax.GetLocation() End If Return If(Locations.FirstOrDefault(), NoLocation.Singleton) End Function Friend Overrides Function GetBoundMethodBody(compilationState As TypeCompilationState, diagnostics As BindingDiagnosticBag, Optional ByRef methodBodyBinder As Binder = Nothing) As BoundBlock Dim syntaxTree As SyntaxTree = Me.SyntaxTree ' All source method symbols must have block syntax. Dim methodBlock As MethodBlockBaseSyntax = Me.BlockSyntax Debug.Assert(methodBlock IsNot Nothing) ' Bind the method block methodBodyBinder = BinderBuilder.CreateBinderForMethodBody(ContainingSourceModule, syntaxTree, Me) #If DEBUG Then ' Enable DEBUG check for ordering of simple name binding. methodBodyBinder.EnableSimpleNameBindingOrderChecks(True) #End If Dim boundStatement = methodBodyBinder.BindStatement(methodBlock, diagnostics) #If DEBUG Then methodBodyBinder.EnableSimpleNameBindingOrderChecks(False) #End If If boundStatement.Kind = BoundKind.Block Then Return DirectCast(boundStatement, BoundBlock) End If Return New BoundBlock(methodBlock, methodBlock.Statements, ImmutableArray(Of LocalSymbol).Empty, ImmutableArray.Create(boundStatement)) End Function Friend NotOverridable Overrides Function CalculateLocalSyntaxOffset(localPosition As Integer, localTree As SyntaxTree) As Integer Dim span As TextSpan Dim block = BlockSyntax If block IsNot Nothing AndAlso localTree Is block.SyntaxTree Then ' Assign all variables that are associated with the header -1. ' We can't assign >=0 since user-defined variables defined in the first statement of the body have 0 ' and user-defined variables need to have a unique syntax offset. If localPosition = block.BlockStatement.SpanStart Then Return -1 End If span = block.Statements.Span If span.Contains(localPosition) Then Return localPosition - span.Start End If End If ' Calculates a syntax offset of a syntax position which must be either a property or field initializer. Dim syntaxOffset As Integer Dim containingType = DirectCast(Me.ContainingType, SourceNamedTypeSymbol) If containingType.TryCalculateSyntaxOffsetOfPositionInInitializer(localPosition, localTree, Me.IsShared, syntaxOffset) Then Return syntaxOffset End If Throw ExceptionUtilities.Unreachable End Function #End Region #Region "Signature" Public NotOverridable Overrides ReadOnly Property IsVararg As Boolean Get Return False End Get End Property Public NotOverridable Overrides ReadOnly Property IsGenericMethod As Boolean Get Return Arity <> 0 End Get End Property Public NotOverridable Overrides ReadOnly Property TypeArguments As ImmutableArray(Of TypeSymbol) Get Debug.Assert(Not TypeParameters.IsDefault) Return StaticCast(Of TypeSymbol).From(TypeParameters) End Get End Property Public Overrides ReadOnly Property Arity As Integer Get Return TypeParameters.Length End Get End Property Public NotOverridable Overrides ReadOnly Property ReturnsByRef As Boolean Get ' It is not possible to define ref-returning methods in source. Return False End Get End Property Public NotOverridable Overrides ReadOnly Property RefCustomModifiers As ImmutableArray(Of CustomModifier) Get Return ImmutableArray(Of CustomModifier).Empty End Get End Property Public Overrides ReadOnly Property IsSub As Boolean Get Debug.Assert(Me.MethodKind <> MethodKind.EventAdd, "Can't trust the flag for event adders, because their signatures are different under WinRT") Return (m_flags And SourceMemberFlags.MethodIsSub) <> 0 End Get End Property Public NotOverridable Overrides ReadOnly Property IsAsync As Boolean Get Return (m_flags And SourceMemberFlags.Async) <> 0 End Get End Property Public NotOverridable Overrides ReadOnly Property IsIterator As Boolean Get Return (m_flags And SourceMemberFlags.Iterator) <> 0 End Get End Property Public NotOverridable Overrides ReadOnly Property IsInitOnly As Boolean Get Return False End Get End Property Friend NotOverridable Overrides Function TryGetMeParameter(<Out> ByRef meParameter As ParameterSymbol) As Boolean If IsShared Then meParameter = Nothing Else If _lazyMeParameter Is Nothing Then Interlocked.CompareExchange(_lazyMeParameter, New MeParameterSymbol(Me), Nothing) End If meParameter = _lazyMeParameter End If Return True End Function Public Overrides ReadOnly Property ReturnTypeCustomModifiers As ImmutableArray(Of CustomModifier) Get Dim overridden = Me.OverriddenMethod If overridden Is Nothing Then Return ImmutableArray(Of CustomModifier).Empty Else Return overridden.ConstructIfGeneric(TypeArguments).ReturnTypeCustomModifiers End If End Get End Property #End Region #Region "Attributes" ''' <summary> ''' Symbol to copy bound attributes from, or null if the attributes are not shared among multiple source method symbols. ''' </summary> ''' <remarks> ''' Used for example for event accessors. The "remove" method delegates attribute binding to the "add" method. ''' The bound attribute data are then applied to both accessors. ''' </remarks> Protected Overridable ReadOnly Property BoundAttributesSource As SourceMethodSymbol Get Return Nothing End Get End Property ''' <summary> ''' Symbol to copy bound return type attributes from, or null if the attributes are not shared among multiple source symbols. ''' </summary> ''' <remarks> ''' Used for property accessors. Getter copies its return type attributes from the property return type attributes. ''' ''' So far we only need to return <see cref="SourcePropertySymbol"/>. If we ever needed to return a <see cref="SourceMethodSymbol"/> ''' we could implement an interface on those two types. ''' </remarks> Protected Overridable ReadOnly Property BoundReturnTypeAttributesSource As SourcePropertySymbol Get Return Nothing End Get End Property Protected ReadOnly Property AttributeDeclarationSyntaxList As SyntaxList(Of AttributeListSyntax) Get Return If(m_syntaxReferenceOpt IsNot Nothing, DeclarationSyntax.AttributeLists, Nothing) End Get End Property Protected ReadOnly Property ReturnTypeAttributeDeclarationSyntaxList As SyntaxList(Of AttributeListSyntax) Get Dim syntax = DeclarationSyntax If syntax IsNot Nothing Then Dim asClauseOpt = syntax.AsClauseInternal If asClauseOpt IsNot Nothing Then Return asClauseOpt.Attributes End If End If Return Nothing End Get End Property Protected Overridable Function GetAttributeDeclarations() As OneOrMany(Of SyntaxList(Of AttributeListSyntax)) Return OneOrMany.Create(AttributeDeclarationSyntaxList) End Function Protected Overridable Function GetReturnTypeAttributeDeclarations() As OneOrMany(Of SyntaxList(Of AttributeListSyntax)) Return OneOrMany.Create(ReturnTypeAttributeDeclarationSyntaxList) End Function Public ReadOnly Property DefaultAttributeLocation As AttributeLocation Implements IAttributeTargetSymbol.DefaultAttributeLocation Get Return AttributeLocation.Method End Get End Property Private Function GetAttributesBag() As CustomAttributesBag(Of VisualBasicAttributeData) Return GetAttributesBag(m_lazyCustomAttributesBag, forReturnType:=False) End Function Private Function GetReturnTypeAttributesBag() As CustomAttributesBag(Of VisualBasicAttributeData) Return GetAttributesBag(m_lazyReturnTypeCustomAttributesBag, forReturnType:=True) End Function Private Function GetAttributesBag(ByRef lazyCustomAttributesBag As CustomAttributesBag(Of VisualBasicAttributeData), forReturnType As Boolean) As CustomAttributesBag(Of VisualBasicAttributeData) If lazyCustomAttributesBag Is Nothing OrElse Not lazyCustomAttributesBag.IsSealed Then If forReturnType Then Dim copyFrom = Me.BoundReturnTypeAttributesSource ' prevent infinite recursion: Debug.Assert(copyFrom IsNot Me) If copyFrom IsNot Nothing Then Dim attributesBag = copyFrom.GetReturnTypeAttributesBag() Interlocked.CompareExchange(lazyCustomAttributesBag, attributesBag, Nothing) Else LoadAndValidateAttributes(Me.GetReturnTypeAttributeDeclarations(), lazyCustomAttributesBag, symbolPart:=AttributeLocation.Return) End If Else Dim copyFrom = Me.BoundAttributesSource ' prevent infinite recursion: Debug.Assert(copyFrom IsNot Me) If copyFrom IsNot Nothing Then Dim attributesBag = copyFrom.GetAttributesBag() Interlocked.CompareExchange(lazyCustomAttributesBag, attributesBag, Nothing) Else LoadAndValidateAttributes(Me.GetAttributeDeclarations(), lazyCustomAttributesBag) End If End If End If Return lazyCustomAttributesBag End Function ''' <summary> ''' Gets the attributes applied on this symbol. ''' Returns an empty array if there are no attributes. ''' </summary> Public NotOverridable Overrides Function GetAttributes() As ImmutableArray(Of VisualBasicAttributeData) Return Me.GetAttributesBag().Attributes End Function Friend Overrides Sub AddSynthesizedAttributes(compilationState As ModuleCompilationState, ByRef attributes As ArrayBuilder(Of SynthesizedAttributeData)) MyBase.AddSynthesizedAttributes(compilationState, attributes) ' Emit synthesized STAThreadAttribute for this method if both the following requirements are met: ' (a) This is the entry point method. ' (b) There is no applied STAThread or MTAThread attribute on this method. Dim compilation = Me.DeclaringCompilation Dim entryPointMethod As MethodSymbol = compilation.GetEntryPoint(CancellationToken.None) If Me Is entryPointMethod Then If Not Me.HasSTAThreadOrMTAThreadAttribute Then ' UNDONE: UV Support: Do not emit if using the starlite libraries. AddSynthesizedAttribute(attributes, compilation.TrySynthesizeAttribute( WellKnownMember.System_STAThreadAttribute__ctor)) End If End If End Sub Friend Overrides Sub AddSynthesizedReturnTypeAttributes(ByRef attributes As ArrayBuilder(Of SynthesizedAttributeData)) MyBase.AddSynthesizedReturnTypeAttributes(attributes) If Me.ReturnType.ContainsTupleNames() Then AddSynthesizedAttribute(attributes, DeclaringCompilation.SynthesizeTupleNamesAttribute(Me.ReturnType)) End If End Sub Protected Function GetDecodedWellKnownAttributeData() As MethodWellKnownAttributeData Dim attributesBag As CustomAttributesBag(Of VisualBasicAttributeData) = Me.m_lazyCustomAttributesBag If attributesBag Is Nothing OrElse Not attributesBag.IsDecodedWellKnownAttributeDataComputed Then attributesBag = Me.GetAttributesBag() End If Return DirectCast(attributesBag.DecodedWellKnownAttributeData, MethodWellKnownAttributeData) End Function ''' <summary> ''' Returns the list of attributes, if any, associated with the return type. ''' </summary> Public NotOverridable Overrides Function GetReturnTypeAttributes() As ImmutableArray(Of VisualBasicAttributeData) Return Me.GetReturnTypeAttributesBag().Attributes End Function Private Function GetDecodedReturnTypeWellKnownAttributeData() As CommonReturnTypeWellKnownAttributeData Dim attributesBag As CustomAttributesBag(Of VisualBasicAttributeData) = Me.m_lazyReturnTypeCustomAttributesBag If attributesBag Is Nothing OrElse Not attributesBag.IsDecodedWellKnownAttributeDataComputed Then attributesBag = Me.GetReturnTypeAttributesBag() End If Return DirectCast(attributesBag.DecodedWellKnownAttributeData, CommonReturnTypeWellKnownAttributeData) End Function Friend Overrides Function EarlyDecodeWellKnownAttribute(ByRef arguments As EarlyDecodeWellKnownAttributeArguments(Of EarlyWellKnownAttributeBinder, NamedTypeSymbol, AttributeSyntax, AttributeLocation)) As VisualBasicAttributeData Debug.Assert(arguments.AttributeType IsNot Nothing) Debug.Assert(Not arguments.AttributeType.IsErrorType()) Dim hasAnyDiagnostics As Boolean = False If arguments.SymbolPart <> AttributeLocation.Return Then If VisualBasicAttributeData.IsTargetEarlyAttribute(arguments.AttributeType, arguments.AttributeSyntax, AttributeDescription.CaseInsensitiveExtensionAttribute) Then Dim isExtensionMethod As Boolean = False If Not (Me.MethodKind <> MethodKind.Ordinary AndAlso Me.MethodKind <> MethodKind.DeclareMethod) AndAlso m_containingType.AllowsExtensionMethods() AndAlso Me.ParameterCount <> 0 Then Debug.Assert(Me.IsShared) Dim firstParam As ParameterSymbol = Me.Parameters(0) If Not firstParam.IsOptional AndAlso Not firstParam.IsParamArray AndAlso ValidateGenericConstraintsOnExtensionMethodDefinition() Then isExtensionMethod = m_containingType.MightContainExtensionMethods End If End If If isExtensionMethod Then Dim attrdata = arguments.Binder.GetAttribute(arguments.AttributeSyntax, arguments.AttributeType, hasAnyDiagnostics) If Not attrdata.HasErrors Then arguments.GetOrCreateData(Of MethodEarlyWellKnownAttributeData)().IsExtensionMethod = True Return If(Not hasAnyDiagnostics, attrdata, Nothing) End If End If Return Nothing ElseIf VisualBasicAttributeData.IsTargetEarlyAttribute(arguments.AttributeType, arguments.AttributeSyntax, AttributeDescription.ConditionalAttribute) Then Dim attrdata = arguments.Binder.GetAttribute(arguments.AttributeSyntax, arguments.AttributeType, hasAnyDiagnostics) If Not attrdata.HasErrors Then Dim conditionalSymbol As String = attrdata.GetConstructorArgument(Of String)(0, SpecialType.System_String) arguments.GetOrCreateData(Of MethodEarlyWellKnownAttributeData)().AddConditionalSymbol(conditionalSymbol) Return If(Not hasAnyDiagnostics, attrdata, Nothing) Else Return Nothing End If Else Dim BoundAttribute As VisualBasicAttributeData = Nothing Dim obsoleteData As ObsoleteAttributeData = Nothing If EarlyDecodeDeprecatedOrExperimentalOrObsoleteAttribute(arguments, BoundAttribute, obsoleteData) Then If obsoleteData IsNot Nothing Then arguments.GetOrCreateData(Of MethodEarlyWellKnownAttributeData)().ObsoleteAttributeData = obsoleteData End If Return BoundAttribute End If End If End If Return MyBase.EarlyDecodeWellKnownAttribute(arguments) End Function ''' <summary> ''' Returns data decoded from early bound well-known attributes applied to the symbol or null if there are no applied attributes. ''' </summary> ''' <remarks> ''' Forces binding and decoding of attributes. ''' </remarks> Private Function GetEarlyDecodedWellKnownAttributeData() As MethodEarlyWellKnownAttributeData Dim attributesBag As CustomAttributesBag(Of VisualBasicAttributeData) = Me.m_lazyCustomAttributesBag If attributesBag Is Nothing OrElse Not attributesBag.IsEarlyDecodedWellKnownAttributeDataComputed Then attributesBag = Me.GetAttributesBag() End If Return DirectCast(attributesBag.EarlyDecodedWellKnownAttributeData, MethodEarlyWellKnownAttributeData) End Function Friend Overrides Function GetAppliedConditionalSymbols() As ImmutableArray(Of String) Dim data As MethodEarlyWellKnownAttributeData = Me.GetEarlyDecodedWellKnownAttributeData() Return If(data IsNot Nothing, data.ConditionalSymbols, ImmutableArray(Of String).Empty) End Function Friend Overrides Sub DecodeWellKnownAttribute(ByRef arguments As DecodeWellKnownAttributeArguments(Of AttributeSyntax, VisualBasicAttributeData, AttributeLocation)) Dim attrData = arguments.Attribute Debug.Assert(Not attrData.HasErrors) If attrData.IsTargetAttribute(Me, AttributeDescription.TupleElementNamesAttribute) Then DirectCast(arguments.Diagnostics, BindingDiagnosticBag).Add(ERRID.ERR_ExplicitTupleElementNamesAttribute, arguments.AttributeSyntaxOpt.Location) ElseIf attrData.IsTargetAttribute(Me, AttributeDescription.UnmanagedCallersOnlyAttribute) Then ' VB does not support UnmanagedCallersOnly attributes on methods at all DirectCast(arguments.Diagnostics, BindingDiagnosticBag).Add(ERRID.ERR_UnmanagedCallersOnlyNotSupported, arguments.AttributeSyntaxOpt.Location) End If If arguments.SymbolPart = AttributeLocation.Return Then ' Decode well-known attributes applied to return value DecodeWellKnownAttributeAppliedToReturnValue(arguments) Else Debug.Assert(arguments.SymbolPart = AttributeLocation.None) DecodeWellKnownAttributeAppliedToMethod(arguments) End If MyBase.DecodeWellKnownAttribute(arguments) End Sub Private Sub DecodeWellKnownAttributeAppliedToMethod(ByRef arguments As DecodeWellKnownAttributeArguments(Of AttributeSyntax, VisualBasicAttributeData, AttributeLocation)) Debug.Assert(arguments.AttributeSyntaxOpt IsNot Nothing) Dim diagnostics = DirectCast(arguments.Diagnostics, BindingDiagnosticBag) ' Decode well-known attributes applied to method Dim attrData = arguments.Attribute If attrData.IsTargetAttribute(Me, AttributeDescription.CaseInsensitiveExtensionAttribute) Then ' Just report errors here. The extension attribute is decoded early. If Me.MethodKind <> MethodKind.Ordinary AndAlso Me.MethodKind <> MethodKind.DeclareMethod Then diagnostics.Add(ERRID.ERR_ExtensionOnlyAllowedOnModuleSubOrFunction, arguments.AttributeSyntaxOpt.GetLocation()) ElseIf Not m_containingType.AllowsExtensionMethods() Then diagnostics.Add(ERRID.ERR_ExtensionMethodNotInModule, arguments.AttributeSyntaxOpt.GetLocation()) ElseIf Me.ParameterCount = 0 Then diagnostics.Add(ERRID.ERR_ExtensionMethodNoParams, Me.Locations(0)) Else Debug.Assert(Me.IsShared) Dim firstParam As ParameterSymbol = Me.Parameters(0) If firstParam.IsOptional Then diagnostics.Add(ErrorFactory.ErrorInfo(ERRID.ERR_ExtensionMethodOptionalFirstArg), firstParam.Locations(0)) ElseIf firstParam.IsParamArray Then diagnostics.Add(ErrorFactory.ErrorInfo(ERRID.ERR_ExtensionMethodParamArrayFirstArg), firstParam.Locations(0)) ElseIf Not Me.ValidateGenericConstraintsOnExtensionMethodDefinition() Then diagnostics.Add(ErrorFactory.ErrorInfo(ERRID.ERR_ExtensionMethodUncallable1, Me.Name), Me.Locations(0)) End If End If ElseIf attrData.IsTargetAttribute(Me, AttributeDescription.WebMethodAttribute) Then ' Check for optional parameters For Each parameter In Me.Parameters If parameter.IsOptional Then diagnostics.Add(ErrorFactory.ErrorInfo(ERRID.ERR_InvalidOptionalParameterUsage1, "WebMethod"), Me.Locations(0)) End If Next ElseIf attrData.IsTargetAttribute(Me, AttributeDescription.PreserveSigAttribute) Then arguments.GetOrCreateData(Of MethodWellKnownAttributeData)().SetPreserveSignature(arguments.Index) ElseIf attrData.IsTargetAttribute(Me, AttributeDescription.MethodImplAttribute) Then AttributeData.DecodeMethodImplAttribute(Of MethodWellKnownAttributeData, AttributeSyntax, VisualBasicAttributeData, AttributeLocation)(arguments, MessageProvider.Instance) ElseIf attrData.IsTargetAttribute(Me, AttributeDescription.DllImportAttribute) Then If Not IsDllImportAttributeAllowed(arguments.AttributeSyntaxOpt, diagnostics) Then Return End If Dim moduleName As String = TryCast(attrData.CommonConstructorArguments(0).ValueInternal, String) If Not MetadataHelpers.IsValidMetadataIdentifier(moduleName) Then diagnostics.Add(ERRID.ERR_BadAttribute1, arguments.AttributeSyntaxOpt.ArgumentList.Arguments(0).GetLocation(), attrData.AttributeClass) End If ' Default value of charset is inherited from the module (only if specified). ' This might be different from ContainingType.DefaultMarshallingCharSet. If the charset is not specified on module ' ContainingType.DefaultMarshallingCharSet would be Ansi (the class is emitted with "Ansi" charset metadata flag) ' while the charset in P/Invoke metadata should be "None". Dim charSet As CharSet = If(Me.EffectiveDefaultMarshallingCharSet, Microsoft.Cci.Constants.CharSet_None) Dim importName As String = Nothing Dim preserveSig As Boolean = True Dim callingConvention As System.Runtime.InteropServices.CallingConvention = System.Runtime.InteropServices.CallingConvention.Winapi Dim setLastError As Boolean = False Dim exactSpelling As Boolean = False Dim bestFitMapping As Boolean? = Nothing Dim throwOnUnmappable As Boolean? = Nothing Dim position As Integer = 1 For Each namedArg In attrData.CommonNamedArguments Select Case namedArg.Key Case "EntryPoint" importName = TryCast(namedArg.Value.ValueInternal, String) If Not MetadataHelpers.IsValidMetadataIdentifier(importName) Then diagnostics.Add(ERRID.ERR_BadAttribute1, arguments.AttributeSyntaxOpt.ArgumentList.Arguments(position).GetLocation(), attrData.AttributeClass) Return End If Case "CharSet" charSet = namedArg.Value.DecodeValue(Of CharSet)(SpecialType.System_Enum) Case "SetLastError" setLastError = namedArg.Value.DecodeValue(Of Boolean)(SpecialType.System_Boolean) Case "ExactSpelling" exactSpelling = namedArg.Value.DecodeValue(Of Boolean)(SpecialType.System_Boolean) Case "PreserveSig" preserveSig = namedArg.Value.DecodeValue(Of Boolean)(SpecialType.System_Boolean) Case "CallingConvention" callingConvention = namedArg.Value.DecodeValue(Of System.Runtime.InteropServices.CallingConvention)(SpecialType.System_Enum) Case "BestFitMapping" bestFitMapping = namedArg.Value.DecodeValue(Of Boolean)(SpecialType.System_Boolean) Case "ThrowOnUnmappableChar" throwOnUnmappable = namedArg.Value.DecodeValue(Of Boolean)(SpecialType.System_Boolean) End Select position = position + 1 Next Dim data = arguments.GetOrCreateData(Of MethodWellKnownAttributeData)() data.SetDllImport( arguments.Index, moduleName, importName, DllImportData.MakeFlags(exactSpelling, charSet, setLastError, callingConvention, bestFitMapping, throwOnUnmappable), preserveSig) ElseIf attrData.IsTargetAttribute(Me, AttributeDescription.SpecialNameAttribute) Then arguments.GetOrCreateData(Of MethodWellKnownAttributeData)().HasSpecialNameAttribute = True ElseIf attrData.IsTargetAttribute(Me, AttributeDescription.ExcludeFromCodeCoverageAttribute) Then arguments.GetOrCreateData(Of MethodWellKnownAttributeData)().HasExcludeFromCodeCoverageAttribute = True ElseIf attrData.IsTargetAttribute(Me, AttributeDescription.SuppressUnmanagedCodeSecurityAttribute) Then arguments.GetOrCreateData(Of MethodWellKnownAttributeData)().HasSuppressUnmanagedCodeSecurityAttribute = True ElseIf attrData.IsSecurityAttribute(Me.DeclaringCompilation) Then attrData.DecodeSecurityAttribute(Of MethodWellKnownAttributeData)(Me, Me.DeclaringCompilation, arguments) ElseIf attrData.IsTargetAttribute(Me, AttributeDescription.STAThreadAttribute) Then arguments.GetOrCreateData(Of MethodWellKnownAttributeData)().HasSTAThreadAttribute = True ElseIf attrData.IsTargetAttribute(Me, AttributeDescription.MTAThreadAttribute) Then arguments.GetOrCreateData(Of MethodWellKnownAttributeData)().HasMTAThreadAttribute = True ElseIf attrData.IsTargetAttribute(Me, AttributeDescription.ConditionalAttribute) Then If Not Me.IsSub Then ' BC41007: Attribute 'Conditional' is only valid on 'Sub' declarations. diagnostics.Add(ERRID.WRN_ConditionalNotValidOnFunction, Me.Locations(0)) End If ElseIf VerifyObsoleteAttributeAppliedToMethod(arguments, AttributeDescription.ObsoleteAttribute) Then ElseIf VerifyObsoleteAttributeAppliedToMethod(arguments, AttributeDescription.DeprecatedAttribute) Then ElseIf arguments.Attribute.IsTargetAttribute(Me, AttributeDescription.ModuleInitializerAttribute) Then diagnostics.Add(ERRID.WRN_AttributeNotSupportedInVB, arguments.AttributeSyntaxOpt.Location, AttributeDescription.ModuleInitializerAttribute.FullName) Else Dim methodImpl As MethodSymbol = If(Me.IsPartial, PartialImplementationPart, Me) If methodImpl IsNot Nothing AndAlso (methodImpl.IsAsync OrElse methodImpl.IsIterator) AndAlso Not methodImpl.ContainingType.IsInterfaceType() Then If attrData.IsTargetAttribute(Me, AttributeDescription.SecurityCriticalAttribute) Then Binder.ReportDiagnostic(diagnostics, arguments.AttributeSyntaxOpt.GetLocation(), ERRID.ERR_SecurityCriticalAsync, "SecurityCritical") Return ElseIf attrData.IsTargetAttribute(Me, AttributeDescription.SecuritySafeCriticalAttribute) Then Binder.ReportDiagnostic(diagnostics, arguments.AttributeSyntaxOpt.GetLocation(), ERRID.ERR_SecurityCriticalAsync, "SecuritySafeCritical") Return End If End If End If End Sub Private Function VerifyObsoleteAttributeAppliedToMethod( ByRef arguments As DecodeWellKnownAttributeArguments(Of AttributeSyntax, VisualBasicAttributeData, AttributeLocation), description As AttributeDescription ) As Boolean If arguments.Attribute.IsTargetAttribute(Me, description) Then ' Obsolete Attribute is not allowed on event accessors. If Me.IsAccessor() AndAlso Me.AssociatedSymbol.Kind = SymbolKind.Event Then DirectCast(arguments.Diagnostics, BindingDiagnosticBag).Add(ERRID.ERR_ObsoleteInvalidOnEventMember, Me.Locations(0), description.FullName) End If Return True End If Return False End Function Private Sub DecodeWellKnownAttributeAppliedToReturnValue(ByRef arguments As DecodeWellKnownAttributeArguments(Of AttributeSyntax, VisualBasicAttributeData, AttributeLocation)) ' Decode well-known attributes applied to return value Dim attrData = arguments.Attribute Debug.Assert(Not attrData.HasErrors) If attrData.IsTargetAttribute(Me, AttributeDescription.MarshalAsAttribute) Then MarshalAsAttributeDecoder(Of CommonReturnTypeWellKnownAttributeData, AttributeSyntax, VisualBasicAttributeData, AttributeLocation).Decode(arguments, AttributeTargets.ReturnValue, MessageProvider.Instance) End If End Sub Private Function IsDllImportAttributeAllowed(syntax As AttributeSyntax, diagnostics As BindingDiagnosticBag) As Boolean Select Case Me.MethodKind Case MethodKind.DeclareMethod diagnostics.Add(ERRID.ERR_DllImportNotLegalOnDeclare, syntax.Name.GetLocation()) Return False Case MethodKind.PropertyGet, MethodKind.PropertySet diagnostics.Add(ERRID.ERR_DllImportNotLegalOnGetOrSet, syntax.Name.GetLocation()) Return False Case MethodKind.EventAdd, MethodKind.EventRaise, MethodKind.EventRemove diagnostics.Add(ERRID.ERR_DllImportNotLegalOnEventMethod, syntax.Name.GetLocation()) Return False End Select If Me.ContainingType IsNot Nothing AndAlso Me.ContainingType.IsInterface Then diagnostics.Add(ERRID.ERR_DllImportOnInterfaceMethod, syntax.Name.GetLocation()) Return False End If If Me.IsGenericMethod OrElse (Me.ContainingType IsNot Nothing AndAlso Me.ContainingType.IsGenericType) Then diagnostics.Add(ERRID.ERR_DllImportOnGenericSubOrFunction, syntax.Name.GetLocation()) Return False End If If Not Me.IsShared Then diagnostics.Add(ERRID.ERR_DllImportOnInstanceMethod, syntax.Name.GetLocation()) Return False End If Dim methodImpl As SourceMethodSymbol = TryCast(If(Me.IsPartial, PartialImplementationPart, Me), SourceMethodSymbol) If methodImpl IsNot Nothing AndAlso (methodImpl.IsAsync OrElse methodImpl.IsIterator) AndAlso Not methodImpl.ContainingType.IsInterfaceType() Then Dim location As Location = methodImpl.NonMergedLocation If location IsNot Nothing Then Binder.ReportDiagnostic(diagnostics, location, ERRID.ERR_DllImportOnResumableMethod) Return False End If End If If Not HasEmptyBody Then diagnostics.Add(ERRID.ERR_DllImportOnNonEmptySubOrFunction, syntax.Name.GetLocation()) Return False End If Return True End Function Friend Overrides Sub PostDecodeWellKnownAttributes( boundAttributes As ImmutableArray(Of VisualBasicAttributeData), allAttributeSyntaxNodes As ImmutableArray(Of AttributeSyntax), diagnostics As BindingDiagnosticBag, symbolPart As AttributeLocation, decodedData As WellKnownAttributeData) Debug.Assert(Not boundAttributes.IsDefault) Debug.Assert(Not allAttributeSyntaxNodes.IsDefault) Debug.Assert(boundAttributes.Length = allAttributeSyntaxNodes.Length) Debug.Assert(symbolPart = AttributeLocation.Return OrElse symbolPart = AttributeLocation.None) If symbolPart <> AttributeLocation.Return Then Dim methodData = DirectCast(decodedData, MethodWellKnownAttributeData) If methodData IsNot Nothing AndAlso methodData.HasSTAThreadAttribute AndAlso methodData.HasMTAThreadAttribute Then Debug.Assert(Me.NonMergedLocation IsNot Nothing) ' BC31512: 'System.STAThreadAttribute' and 'System.MTAThreadAttribute' cannot both be applied to the same method. diagnostics.Add(ERRID.ERR_STAThreadAndMTAThread0, Me.NonMergedLocation) End If End If MyBase.PostDecodeWellKnownAttributes(boundAttributes, allAttributeSyntaxNodes, diagnostics, symbolPart, decodedData) End Sub Public Overrides ReadOnly Property IsExtensionMethod As Boolean Get Dim data As MethodEarlyWellKnownAttributeData = Me.GetEarlyDecodedWellKnownAttributeData() Return data IsNot Nothing AndAlso data.IsExtensionMethod End Get End Property ' Force derived types to override this. Friend MustOverride Overrides ReadOnly Property MayBeReducibleExtensionMethod As Boolean Public Overrides ReadOnly Property IsExternalMethod As Boolean Get ' External methods are: ' 1) Declare Subs and Declare Functions: IsExternalMethod overridden in SourceDeclareMethodSymbol ' 2) methods marked by DllImportAttribute ' 3) methods marked by MethodImplAttribute: Runtime and InternalCall methods should not have a body emitted Debug.Assert(MethodKind <> MethodKind.DeclareMethod) Dim data As MethodWellKnownAttributeData = GetDecodedWellKnownAttributeData() If data Is Nothing Then Return False End If ' p/invoke If data.DllImportPlatformInvokeData IsNot Nothing Then Return True End If ' internal call If (data.MethodImplAttributes And Reflection.MethodImplAttributes.InternalCall) <> 0 Then Return True End If ' runtime If (data.MethodImplAttributes And Reflection.MethodImplAttributes.CodeTypeMask) = Reflection.MethodImplAttributes.Runtime Then Return True End If Return False End Get End Property Public Overrides Function GetDllImportData() As DllImportData Dim attributeData = GetDecodedWellKnownAttributeData() Return If(attributeData IsNot Nothing, attributeData.DllImportPlatformInvokeData, Nothing) End Function Friend NotOverridable Overrides ReadOnly Property ReturnTypeMarshallingInformation As MarshalPseudoCustomAttributeData Get Dim attributeData = GetDecodedReturnTypeWellKnownAttributeData() Return If(attributeData IsNot Nothing, attributeData.MarshallingInformation, Nothing) End Get End Property Friend Overrides ReadOnly Property ImplementationAttributes As Reflection.MethodImplAttributes Get ' Methods of ComImport types are marked as Runtime implemented and InternalCall If ContainingType.IsComImport AndAlso Not ContainingType.IsInterface Then Return System.Reflection.MethodImplAttributes.Runtime Or Reflection.MethodImplAttributes.InternalCall End If Dim attributeData = GetDecodedWellKnownAttributeData() Return If(attributeData IsNot Nothing, attributeData.MethodImplAttributes, Nothing) End Get End Property Friend NotOverridable Overrides ReadOnly Property HasDeclarativeSecurity As Boolean Get Dim attributeData = GetDecodedWellKnownAttributeData() Return attributeData IsNot Nothing AndAlso attributeData.HasDeclarativeSecurity End Get End Property Friend NotOverridable Overrides Function GetSecurityInformation() As IEnumerable(Of SecurityAttribute) Dim attributesBag As CustomAttributesBag(Of VisualBasicAttributeData) = Me.GetAttributesBag() Dim wellKnownAttributeData = DirectCast(attributesBag.DecodedWellKnownAttributeData, MethodWellKnownAttributeData) If wellKnownAttributeData IsNot Nothing Then Dim securityData As SecurityWellKnownAttributeData = wellKnownAttributeData.SecurityInformation If securityData IsNot Nothing Then Return securityData.GetSecurityAttributes(attributesBag.Attributes) End If End If Return SpecializedCollections.EmptyEnumerable(Of SecurityAttribute)() End Function Friend NotOverridable Overrides ReadOnly Property IsDirectlyExcludedFromCodeCoverage As Boolean Get Dim data = GetDecodedWellKnownAttributeData() Return data IsNot Nothing AndAlso data.HasExcludeFromCodeCoverageAttribute End Get End Property Friend Overrides ReadOnly Property HasRuntimeSpecialName As Boolean Get Return MyBase.HasRuntimeSpecialName OrElse IsVtableGapInterfaceMethod() End Get End Property Private Function IsVtableGapInterfaceMethod() As Boolean Return Me.ContainingType.IsInterface AndAlso ModuleExtensions.GetVTableGapSize(Me.MetadataName) > 0 End Function Friend Overrides ReadOnly Property HasSpecialName As Boolean Get Select Case Me.MethodKind Case MethodKind.Constructor, MethodKind.SharedConstructor, MethodKind.PropertyGet, MethodKind.PropertySet, MethodKind.EventAdd, MethodKind.EventRemove, MethodKind.EventRaise, MethodKind.Conversion, MethodKind.UserDefinedOperator Return True End Select If IsVtableGapInterfaceMethod() Then Return True End If Dim attributeData = GetDecodedWellKnownAttributeData() Return attributeData IsNot Nothing AndAlso attributeData.HasSpecialNameAttribute End Get End Property Private ReadOnly Property HasSTAThreadOrMTAThreadAttribute As Boolean Get ' This property is only accessed during Emit, we must have already bound the attributes. Debug.Assert(m_lazyCustomAttributesBag IsNot Nothing AndAlso m_lazyCustomAttributesBag.IsSealed) Dim decodedData As MethodWellKnownAttributeData = Me.GetDecodedWellKnownAttributeData() Return decodedData IsNot Nothing AndAlso (decodedData.HasSTAThreadAttribute OrElse decodedData.HasMTAThreadAttribute) End Get End Property Friend Overrides ReadOnly Property ObsoleteAttributeData As ObsoleteAttributeData Get ' If there are no attributes then this symbol is not Obsolete. Dim container = TryCast(Me.m_containingType, SourceMemberContainerTypeSymbol) If container Is Nothing OrElse Not container.AnyMemberHasAttributes Then Return Nothing End If Dim lazyCustomAttributesBag = Me.m_lazyCustomAttributesBag If (lazyCustomAttributesBag IsNot Nothing AndAlso lazyCustomAttributesBag.IsEarlyDecodedWellKnownAttributeDataComputed) Then Dim data = DirectCast(m_lazyCustomAttributesBag.EarlyDecodedWellKnownAttributeData, MethodEarlyWellKnownAttributeData) Return If(data IsNot Nothing, data.ObsoleteAttributeData, Nothing) End If Dim reference = Me.DeclaringSyntaxReferences If (reference.IsEmpty) Then ' no references -> no attributes Return Nothing End If Return ObsoleteAttributeData.Uninitialized End Get End Property #End Region Public MustOverride Overrides ReadOnly Property ReturnType As TypeSymbol Public MustOverride Overrides ReadOnly Property Parameters As ImmutableArray(Of ParameterSymbol) Friend MustOverride Overrides ReadOnly Property OverriddenMembers As OverriddenMembersResult(Of MethodSymbol) End Class Friend MustInherit Class SourceNonPropertyAccessorMethodSymbol Inherits SourceMethodSymbol ' Parameters. Private _lazyParameters As ImmutableArray(Of ParameterSymbol) ' Return type. Void for a Sub. Private _lazyReturnType As TypeSymbol ' The overridden or hidden methods. Private _lazyOverriddenMethods As OverriddenMembersResult(Of MethodSymbol) Protected Sub New(containingType As NamedTypeSymbol, flags As SourceMemberFlags, syntaxRef As SyntaxReference, Optional locations As ImmutableArray(Of Location) = Nothing) MyBase.New(containingType, flags, syntaxRef, locations) End Sub Friend NotOverridable Overrides ReadOnly Property ParameterCount As Integer Get If Not Me._lazyParameters.IsDefault Then Return Me._lazyParameters.Length End If Dim decl = Me.DeclarationSyntax Dim paramListOpt As ParameterListSyntax Select Case decl.Kind Case SyntaxKind.SubNewStatement Dim methodStatement = DirectCast(decl, SubNewStatementSyntax) paramListOpt = methodStatement.ParameterList Case SyntaxKind.SubStatement, SyntaxKind.FunctionStatement Dim methodStatement = DirectCast(decl, MethodStatementSyntax) paramListOpt = methodStatement.ParameterList Case Else Return MyBase.ParameterCount End Select Return If(paramListOpt Is Nothing, 0, paramListOpt.Parameters.Count) End Get End Property Public NotOverridable Overrides ReadOnly Property Parameters As ImmutableArray(Of ParameterSymbol) Get EnsureSignature() Return _lazyParameters End Get End Property Private Sub EnsureSignature() If _lazyParameters.IsDefault Then Dim diagBag = BindingDiagnosticBag.GetInstance() Dim sourceModule = ContainingSourceModule Dim params As ImmutableArray(Of ParameterSymbol) = GetParameters(sourceModule, diagBag) Dim errorLocation As SyntaxNodeOrToken = Nothing Dim retType As TypeSymbol = GetReturnType(sourceModule, errorLocation, diagBag) Debug.Assert(Me.IsAccessor OrElse retType.GetArity() = 0 OrElse Not (errorLocation.IsKind(SyntaxKind.None))) ' if we could have constraint errors, the location better exist. ' For an overriding method, we need to copy custom modifiers from the method we override. Dim overriddenMembers As OverriddenMembersResult(Of MethodSymbol) ' Do not support custom modifiers for properties at the moment. If Not Me.IsOverrides OrElse Not OverrideHidingHelper.CanOverrideOrHide(Me) Then overriddenMembers = OverriddenMembersResult(Of MethodSymbol).Empty Else ' Since we cannot expose parameters and return type to the outside world yet, ' let's create a fake symbol to use for overriding resolution Dim fakeTypeParameters As ImmutableArray(Of TypeParameterSymbol) Dim replaceMethodTypeParametersWithFakeTypeParameters As TypeSubstitution If Me.Arity > 0 Then fakeTypeParameters = IndexedTypeParameterSymbol.Take(Me.Arity) replaceMethodTypeParametersWithFakeTypeParameters = TypeSubstitution.Create(Me, Me.TypeParameters, StaticCast(Of TypeSymbol).From(fakeTypeParameters)) Else fakeTypeParameters = ImmutableArray(Of TypeParameterSymbol).Empty replaceMethodTypeParametersWithFakeTypeParameters = Nothing End If Dim fakeParamsBuilder = ArrayBuilder(Of ParameterSymbol).GetInstance(params.Length) For Each param As ParameterSymbol In params fakeParamsBuilder.Add(New SignatureOnlyParameterSymbol( param.Type.InternalSubstituteTypeParameters(replaceMethodTypeParametersWithFakeTypeParameters).AsTypeSymbolOnly(), ImmutableArray(Of CustomModifier).Empty, ImmutableArray(Of CustomModifier).Empty, defaultConstantValue:=Nothing, isParamArray:=False, isByRef:=param.IsByRef, isOut:=False, isOptional:=param.IsOptional)) Next overriddenMembers = OverrideHidingHelper(Of MethodSymbol). MakeOverriddenMembers(New SignatureOnlyMethodSymbol(Me.Name, m_containingType, Me.MethodKind, Me.CallingConvention, fakeTypeParameters, fakeParamsBuilder.ToImmutableAndFree(), returnsByRef:=False, returnType:=retType.InternalSubstituteTypeParameters(replaceMethodTypeParametersWithFakeTypeParameters).AsTypeSymbolOnly(), returnTypeCustomModifiers:=ImmutableArray(Of CustomModifier).Empty, refCustomModifiers:=ImmutableArray(Of CustomModifier).Empty, explicitInterfaceImplementations:=ImmutableArray(Of MethodSymbol).Empty, isOverrides:=True)) End If Debug.Assert(IsDefinition) Dim overridden = overriddenMembers.OverriddenMember If overridden IsNot Nothing Then CustomModifierUtils.CopyMethodCustomModifiers(overridden, Me.TypeArguments, retType, params) End If ' Unlike MethodSymbol, in SourceMethodSymbol we cache the result of MakeOverriddenOfHiddenMembers, because we use ' it heavily while validating methods and emitting. Interlocked.CompareExchange(_lazyOverriddenMethods, overriddenMembers, Nothing) Interlocked.CompareExchange(_lazyReturnType, retType, Nothing) retType = _lazyReturnType For Each param In params ' TODO: The check for Locations is to rule out cases such as implicit parameters ' from property accessors but it allows explicit accessor parameters. Is that correct? If param.Locations.Length > 0 Then ' Note: Errors are reported on the parameter name. Ideally, we should ' match Dev10 and report errors on the parameter type syntax instead. param.Type.CheckAllConstraints(param.Locations(0), diagBag, template:=New CompoundUseSiteInfo(Of AssemblySymbol)(diagBag, sourceModule.ContainingAssembly)) End If Next If Not errorLocation.IsKind(SyntaxKind.None) Then Dim diagnosticsBuilder = ArrayBuilder(Of TypeParameterDiagnosticInfo).GetInstance() Dim useSiteDiagnosticsBuilder As ArrayBuilder(Of TypeParameterDiagnosticInfo) = Nothing retType.CheckAllConstraints(diagnosticsBuilder, useSiteDiagnosticsBuilder, template:=New CompoundUseSiteInfo(Of AssemblySymbol)(diagBag, sourceModule.ContainingAssembly)) If useSiteDiagnosticsBuilder IsNot Nothing Then diagnosticsBuilder.AddRange(useSiteDiagnosticsBuilder) End If For Each diag In diagnosticsBuilder diagBag.Add(diag.UseSiteInfo, errorLocation.GetLocation()) Next diagnosticsBuilder.Free() End If sourceModule.AtomicStoreArrayAndDiagnostics( _lazyParameters, params, diagBag) diagBag.Free() End If End Sub Private Function CreateBinderForMethodDeclaration(sourceModule As SourceModuleSymbol) As Binder Dim binder As Binder = BinderBuilder.CreateBinderForMethodDeclaration(sourceModule, Me.SyntaxTree, Me) ' Constraint checking for parameter and return types must be delayed ' until the parameter and return type fields have been set since ' evaluating constraints may require comparing this method signature ' (to find the implemented method for instance). Return New LocationSpecificBinder(BindingLocation.MethodSignature, Me, binder) End Function Protected Overridable Function GetParameters(sourceModule As SourceModuleSymbol, diagBag As BindingDiagnosticBag) As ImmutableArray(Of ParameterSymbol) Dim decl = Me.DeclarationSyntax Dim binder As Binder = CreateBinderForMethodDeclaration(sourceModule) Dim paramList As ParameterListSyntax Select Case decl.Kind Case SyntaxKind.SubNewStatement paramList = DirectCast(decl, SubNewStatementSyntax).ParameterList Case SyntaxKind.OperatorStatement paramList = DirectCast(decl, OperatorStatementSyntax).ParameterList Case SyntaxKind.SubStatement, SyntaxKind.FunctionStatement paramList = DirectCast(decl, MethodStatementSyntax).ParameterList Case SyntaxKind.DeclareSubStatement, SyntaxKind.DeclareFunctionStatement paramList = DirectCast(decl, DeclareStatementSyntax).ParameterList Case Else Throw ExceptionUtilities.UnexpectedValue(decl.Kind) End Select Return binder.DecodeParameterList(Me, False, m_flags, paramList, diagBag) End Function Public NotOverridable Overrides ReadOnly Property ReturnType As TypeSymbol Get EnsureSignature() Return _lazyReturnType End Get End Property Private Shared Function GetNameToken(methodStatement As MethodBaseSyntax) As SyntaxToken Select Case methodStatement.Kind Case SyntaxKind.OperatorStatement Return DirectCast(methodStatement, OperatorStatementSyntax).OperatorToken Case SyntaxKind.SubStatement, SyntaxKind.FunctionStatement Return DirectCast(methodStatement, MethodStatementSyntax).Identifier Case SyntaxKind.DeclareSubStatement, SyntaxKind.DeclareFunctionStatement Return DirectCast(methodStatement, DeclareStatementSyntax).Identifier Case Else Throw ExceptionUtilities.UnexpectedValue(methodStatement.Kind) End Select End Function Private Function GetReturnType(sourceModule As SourceModuleSymbol, ByRef errorLocation As SyntaxNodeOrToken, diagBag As BindingDiagnosticBag) As TypeSymbol Dim binder As Binder = CreateBinderForMethodDeclaration(sourceModule) Select Case MethodKind Case MethodKind.Constructor, MethodKind.SharedConstructor, MethodKind.EventRemove, MethodKind.EventRaise Debug.Assert(Me.IsSub) Return binder.GetSpecialType(SpecialType.System_Void, Syntax, diagBag) Case MethodKind.EventAdd Dim isWindowsRuntimeEvent As Boolean = DirectCast(Me.AssociatedSymbol, EventSymbol).IsWindowsRuntimeEvent Return If(isWindowsRuntimeEvent, binder.GetWellKnownType(WellKnownType.System_Runtime_InteropServices_WindowsRuntime_EventRegistrationToken, Syntax, diagBag), binder.GetSpecialType(SpecialType.System_Void, Syntax, diagBag)) Case MethodKind.PropertyGet, MethodKind.PropertySet Throw ExceptionUtilities.Unreachable Case Else Dim methodStatement As MethodBaseSyntax = Me.DeclarationSyntax Dim retType As TypeSymbol Select Case methodStatement.Kind Case SyntaxKind.SubStatement, SyntaxKind.DeclareSubStatement Debug.Assert(Me.IsSub) binder.DisallowTypeCharacter(GetNameToken(methodStatement), diagBag, ERRID.ERR_TypeCharOnSub) retType = binder.GetSpecialType(SpecialType.System_Void, Syntax, diagBag) errorLocation = methodStatement.DeclarationKeyword Case Else Dim getErrorInfo As Func(Of DiagnosticInfo) = Nothing If binder.OptionStrict = OptionStrict.On Then getErrorInfo = ErrorFactory.GetErrorInfo_ERR_StrictDisallowsImplicitProc ElseIf binder.OptionStrict = OptionStrict.Custom Then If Me.MethodKind = MethodKind.UserDefinedOperator Then getErrorInfo = ErrorFactory.GetErrorInfo_WRN_ObjectAssumed1_WRN_MissingAsClauseinOperator Else getErrorInfo = ErrorFactory.GetErrorInfo_WRN_ObjectAssumed1_WRN_MissingAsClauseinFunction End If End If Dim asClause As AsClauseSyntax = methodStatement.AsClauseInternal retType = binder.DecodeIdentifierType(GetNameToken(methodStatement), asClause, getErrorInfo, diagBag) If asClause IsNot Nothing Then errorLocation = asClause.Type Else errorLocation = methodStatement.DeclarationKeyword End If End Select If Not retType.IsErrorType() Then AccessCheck.VerifyAccessExposureForMemberType(Me, errorLocation, retType, diagBag) Dim restrictedType As TypeSymbol = Nothing If retType.IsRestrictedArrayType(restrictedType) Then binder.ReportDiagnostic(diagBag, errorLocation, ERRID.ERR_RestrictedType1, restrictedType) End If If Not (Me.IsAsync AndAlso Me.IsIterator) Then If Me.IsSub Then If Me.IsIterator Then binder.ReportDiagnostic(diagBag, errorLocation, ERRID.ERR_BadIteratorReturn) End If Else If Me.IsAsync Then Dim compilation = Me.DeclaringCompilation If Not retType.OriginalDefinition.Equals(compilation.GetWellKnownType(WellKnownType.System_Threading_Tasks_Task_T)) AndAlso Not retType.Equals(compilation.GetWellKnownType(WellKnownType.System_Threading_Tasks_Task)) Then binder.ReportDiagnostic(diagBag, errorLocation, ERRID.ERR_BadAsyncReturn) End If End If If Me.IsIterator Then Dim originalRetTypeDef = retType.OriginalDefinition If originalRetTypeDef.SpecialType <> SpecialType.System_Collections_Generic_IEnumerable_T AndAlso originalRetTypeDef.SpecialType <> SpecialType.System_Collections_Generic_IEnumerator_T AndAlso retType.SpecialType <> SpecialType.System_Collections_IEnumerable AndAlso retType.SpecialType <> SpecialType.System_Collections_IEnumerator Then binder.ReportDiagnostic(diagBag, errorLocation, ERRID.ERR_BadIteratorReturn) End If End If End If End If End If Return retType End Select End Function Friend NotOverridable Overrides ReadOnly Property OverriddenMembers As OverriddenMembersResult(Of MethodSymbol) Get EnsureSignature() Return Me._lazyOverriddenMethods End Get End Property End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable Imports System.Globalization Imports System.Reflection Imports System.Runtime.InteropServices Imports System.Threading Imports Microsoft.Cci Imports Microsoft.CodeAnalysis.PooledObjects Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports CallingConvention = Microsoft.Cci.CallingConvention ' to resolve ambiguity with System.Runtime.InteropServices.CallingConvention Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols ''' <summary> ''' Base class for method symbols that are associated with some syntax and can receive custom attributes (directly or indirectly via another source symbol). ''' </summary> Friend MustInherit Class SourceMethodSymbol Inherits MethodSymbol Implements IAttributeTargetSymbol ' Flags about the method Protected ReadOnly m_flags As SourceMemberFlags ' Containing symbol Protected ReadOnly m_containingType As NamedTypeSymbol ' Me parameter. Private _lazyMeParameter As ParameterSymbol ' TODO (tomat): should be private ' Attributes on method. Set once after construction. IsNull means not set. Protected m_lazyCustomAttributesBag As CustomAttributesBag(Of VisualBasicAttributeData) ' TODO (tomat): should be private ' Return type attributes. IsNull means not set. Protected m_lazyReturnTypeCustomAttributesBag As CustomAttributesBag(Of VisualBasicAttributeData) ' The syntax references for the primary (non-partial) declarations. ' Nothing if there are only partial declarations. Protected ReadOnly m_syntaxReferenceOpt As SyntaxReference ' Location(s) Private _lazyLocations As ImmutableArray(Of Location) Private _lazyDocComment As String Private _lazyExpandedDocComment As String 'Nothing if diags have never been computed. Initial binding diagnostics 'are stashed here to optimize API usage patterns 'where method body diagnostics are requested multiple times. Private _cachedDiagnostics As ImmutableArray(Of Diagnostic) Protected Sub New(containingType As NamedTypeSymbol, flags As SourceMemberFlags, syntaxRef As SyntaxReference, Optional locations As ImmutableArray(Of Location) = Nothing) Debug.Assert(TypeOf containingType Is SourceMemberContainerTypeSymbol OrElse TypeOf containingType Is SynthesizedEventDelegateSymbol) m_containingType = containingType m_flags = flags m_syntaxReferenceOpt = syntaxRef ' calculated lazily if not initialized _lazyLocations = locations End Sub #Region "Factories" ' Create a regular method, with the given, name, declarator, and declaration syntax. Friend Shared Function CreateRegularMethod(container As SourceMemberContainerTypeSymbol, syntax As MethodStatementSyntax, binder As Binder, diagBag As DiagnosticBag) As SourceMethodSymbol ' Flags Dim methodModifiers = DecodeMethodModifiers(syntax.Modifiers, container, binder, diagBag) Dim flags = methodModifiers.AllFlags Or SourceMemberFlags.MethodKindOrdinary If syntax.Kind = SyntaxKind.SubStatement Then flags = flags Or SourceMemberFlags.MethodIsSub End If If syntax.HandlesClause IsNot Nothing Then flags = flags Or SourceMemberFlags.MethodHandlesEvents End If 'Name Dim name As String = syntax.Identifier.ValueText Dim handledEvents As ImmutableArray(Of HandledEvent) If syntax.HandlesClause IsNot Nothing Then If container.TypeKind = TYPEKIND.Structure Then ' Structures cannot handle events binder.ReportDiagnostic(diagBag, syntax.Identifier, ERRID.ERR_StructsCannotHandleEvents) ElseIf container.IsInterface Then ' Methods in interfaces cannot have an handles clause binder.ReportDiagnostic(diagBag, syntax.HandlesClause, ERRID.ERR_BadInterfaceMethodFlags1, syntax.HandlesClause.HandlesKeyword.ToString) ElseIf GetTypeParameterListSyntax(syntax) IsNot Nothing Then ' Generic methods cannot have 'handles' clause binder.ReportDiagnostic(diagBag, syntax.Identifier, ERRID.ERR_HandlesInvalidOnGenericMethod) End If ' Operators methods cannot have Handles regardless of container. 'That error (ERR_InvalidHandles) is reported in parser. ' handled events will be lazily constructed: handledEvents = Nothing Else ' there is no handles clause, so it will be Empty anyways handledEvents = ImmutableArray(Of HandledEvent).Empty End If Dim arity = If(syntax.TypeParameterList Is Nothing, 0, syntax.TypeParameterList.Parameters.Count) Dim methodSym As New SourceMemberMethodSymbol( container, name, flags, binder, syntax, arity, handledEvents) If methodSym.IsPartial AndAlso methodSym.IsSub Then If methodSym.IsAsync Then binder.ReportDiagnostic(diagBag, syntax.Identifier, ERRID.ERR_PartialMethodsMustNotBeAsync1, name) End If ReportPartialMethodErrors(syntax.Modifiers, binder, diagBag) End If Return methodSym End Function Friend Shared Function GetTypeParameterListSyntax(methodSyntax As MethodBaseSyntax) As TypeParameterListSyntax If methodSyntax.Kind = SyntaxKind.SubStatement OrElse methodSyntax.Kind = SyntaxKind.FunctionStatement Then Return DirectCast(methodSyntax, MethodStatementSyntax).TypeParameterList End If Return Nothing End Function Private Shared Sub ReportPartialMethodErrors(modifiers As SyntaxTokenList, binder As Binder, diagBag As DiagnosticBag) ' Handle partial methods related errors Dim reportPartialMethodsMustBePrivate As Boolean = True Dim partialToken As SyntaxToken = Nothing Dim modifierList = modifiers.ToList() For index = 0 To modifierList.Count - 1 Dim token As SyntaxToken = modifierList(index) Select Case token.Kind Case SyntaxKind.PublicKeyword, SyntaxKind.MustOverrideKeyword, SyntaxKind.NotOverridableKeyword, SyntaxKind.OverridableKeyword, SyntaxKind.OverridesKeyword, SyntaxKind.MustInheritKeyword lReportErrorOnSingleToken: ' Report [Partial methods must be declared 'Private' instead of '...'] binder.ReportDiagnostic(diagBag, token, ERRID.ERR_OnlyPrivatePartialMethods1, SyntaxFacts.GetText(token.Kind)) reportPartialMethodsMustBePrivate = False Case SyntaxKind.ProtectedKeyword ' Check for 'Protected Friend' If index >= modifierList.Count - 1 OrElse modifierList(index + 1).Kind <> SyntaxKind.FriendKeyword Then GoTo lReportErrorOnSingleToken End If lReportErrorOnTwoTokens: index += 1 Dim nextToken As SyntaxToken = modifierList(index) Dim startLoc As Integer = Math.Min(token.SpanStart, nextToken.SpanStart) Dim endLoc As Integer = Math.Max(token.Span.End, nextToken.Span.End) Dim location = binder.SyntaxTree.GetLocation(New TextSpan(startLoc, endLoc - startLoc)) ' Report [Partial methods must be declared 'Private' instead of '...'] binder.ReportDiagnostic(diagBag, location, ERRID.ERR_OnlyPrivatePartialMethods1, token.Kind.GetText() & " " & nextToken.Kind.GetText()) reportPartialMethodsMustBePrivate = False Case SyntaxKind.FriendKeyword ' Check for 'Friend Protected' If index >= modifierList.Count - 1 OrElse modifierList(index + 1).Kind <> SyntaxKind.ProtectedKeyword Then GoTo lReportErrorOnSingleToken End If GoTo lReportErrorOnTwoTokens Case SyntaxKind.PartialKeyword partialToken = token Case SyntaxKind.PrivateKeyword reportPartialMethodsMustBePrivate = False End Select Next If reportPartialMethodsMustBePrivate Then ' Report [Partial methods must be declared 'Private'] Debug.Assert(partialToken.Kind = SyntaxKind.PartialKeyword) binder.ReportDiagnostic(diagBag, partialToken, ERRID.ERR_PartialMethodsMustBePrivate) End If End Sub ''' <summary> ''' Creates a method symbol for Declare Sub or Function. ''' </summary> Friend Shared Function CreateDeclareMethod(container As SourceMemberContainerTypeSymbol, syntax As DeclareStatementSyntax, binder As Binder, diagBag As DiagnosticBag) As SourceMethodSymbol Dim methodModifiers = binder.DecodeModifiers( syntax.Modifiers, SourceMemberFlags.AllAccessibilityModifiers Or SourceMemberFlags.Overloads Or SourceMemberFlags.Shadows, ERRID.ERR_BadDeclareFlags1, Accessibility.Public, diagBag) ' modifiers: Protected and Overloads in Modules and Structures: If container.TypeKind = TYPEKIND.Module Then If (methodModifiers.FoundFlags And SourceMemberFlags.Overloads) <> 0 Then Dim keyword = syntax.Modifiers.First(Function(m) m.Kind = SyntaxKind.OverloadsKeyword) diagBag.Add(ERRID.ERR_OverloadsModifierInModule, keyword.GetLocation(), keyword.ValueText) ElseIf (methodModifiers.FoundFlags And SourceMemberFlags.Protected) <> 0 Then Dim keyword = syntax.Modifiers.First(Function(m) m.Kind = SyntaxKind.ProtectedKeyword) diagBag.Add(ERRID.ERR_ModuleCantUseDLLDeclareSpecifier1, keyword.GetLocation(), keyword.ValueText) End If ElseIf container.TypeKind = TYPEKIND.Structure Then If (methodModifiers.FoundFlags And SourceMemberFlags.Protected) <> 0 Then Dim keyword = syntax.Modifiers.First(Function(m) m.Kind = SyntaxKind.ProtectedKeyword) diagBag.Add(ERRID.ERR_StructCantUseDLLDeclareSpecifier1, keyword.GetLocation(), keyword.ValueText) End If End If ' not allowed in generic context If container IsNot Nothing AndAlso container.IsGenericType Then diagBag.Add(ERRID.ERR_DeclaresCantBeInGeneric, syntax.Identifier.GetLocation()) End If Dim flags = methodModifiers.AllFlags Or SourceMemberFlags.MethodKindDeclare Or SourceMemberFlags.Shared If syntax.Kind = SyntaxKind.DeclareSubStatement Then flags = flags Or SourceMemberFlags.MethodIsSub End If Dim name As String = syntax.Identifier.ValueText ' module name Dim moduleName As String = syntax.LibraryName.Token.ValueText If String.IsNullOrEmpty(moduleName) AndAlso Not syntax.LibraryName.IsMissing Then diagBag.Add(ERRID.ERR_BadAttribute1, syntax.LibraryName.GetLocation(), name) moduleName = Nothing End If ' entry point name Dim entryPointName As String If syntax.AliasName IsNot Nothing Then entryPointName = syntax.AliasName.Token.ValueText If String.IsNullOrEmpty(entryPointName) Then diagBag.Add(ERRID.ERR_BadAttribute1, syntax.LibraryName.GetLocation(), name) entryPointName = Nothing End If Else ' If alias syntax not specified use Nothing - the emitter will fill in the metadata method name and ' the users can determine whether or not it was specified. entryPointName = Nothing End If Dim importData = New DllImportData(moduleName, entryPointName, GetPInvokeAttributes(syntax)) Return New SourceDeclareMethodSymbol(container, name, flags, binder, syntax, importData) End Function Private Shared Function GetPInvokeAttributes(syntax As DeclareStatementSyntax) As MethodImportAttributes Dim result As MethodImportAttributes Select Case syntax.CharsetKeyword.Kind Case SyntaxKind.None, SyntaxKind.AnsiKeyword result = MethodImportAttributes.CharSetAnsi Or MethodImportAttributes.ExactSpelling Case SyntaxKind.UnicodeKeyword result = MethodImportAttributes.CharSetUnicode Or MethodImportAttributes.ExactSpelling Case SyntaxKind.AutoKeyword result = MethodImportAttributes.CharSetAuto End Select Return result Or MethodImportAttributes.CallingConventionWinApi Or MethodImportAttributes.SetLastError End Function Friend Shared Function CreateOperator( container As SourceMemberContainerTypeSymbol, syntax As OperatorStatementSyntax, binder As Binder, diagBag As DiagnosticBag ) As SourceMethodSymbol ' Flags Dim methodModifiers = DecodeOperatorModifiers(syntax, binder, diagBag) Dim flags = methodModifiers.AllFlags Debug.Assert((flags And SourceMemberFlags.AccessibilityPublic) <> 0) Debug.Assert((flags And SourceMemberFlags.Shared) <> 0) 'Name Dim name As String = GetMemberNameFromSyntax(syntax) Debug.Assert(name.Equals(WellKnownMemberNames.ImplicitConversionName) = ((flags And SourceMemberFlags.Widening) <> 0)) Debug.Assert(name.Equals(WellKnownMemberNames.ExplicitConversionName) = ((flags And SourceMemberFlags.Narrowing) <> 0)) Dim paramCountMismatchERRID As ERRID Select Case syntax.OperatorToken.Kind Case SyntaxKind.NotKeyword, SyntaxKind.IsTrueKeyword, SyntaxKind.IsFalseKeyword, SyntaxKind.CTypeKeyword paramCountMismatchERRID = ERRID.ERR_OneParameterRequired1 Case SyntaxKind.PlusToken, SyntaxKind.MinusToken paramCountMismatchERRID = ERRID.ERR_OneOrTwoParametersRequired1 Case SyntaxKind.AsteriskToken, SyntaxKind.SlashToken, SyntaxKind.BackslashToken, SyntaxKind.ModKeyword, SyntaxKind.CaretToken, SyntaxKind.EqualsToken, SyntaxKind.LessThanGreaterThanToken, SyntaxKind.LessThanToken, SyntaxKind.GreaterThanToken, SyntaxKind.LessThanEqualsToken, SyntaxKind.GreaterThanEqualsToken, SyntaxKind.LikeKeyword, SyntaxKind.AmpersandToken, SyntaxKind.AndKeyword, SyntaxKind.OrKeyword, SyntaxKind.XorKeyword, SyntaxKind.LessThanLessThanToken, SyntaxKind.GreaterThanGreaterThanToken paramCountMismatchERRID = ERRID.ERR_TwoParametersRequired1 Case Else Throw ExceptionUtilities.UnexpectedValue(syntax.OperatorToken.Kind) End Select Select Case paramCountMismatchERRID Case ERRID.ERR_OneParameterRequired1 Debug.Assert(OverloadResolution.GetOperatorInfo(name).ParamCount = 1) If syntax.ParameterList.Parameters.Count = 1 Then paramCountMismatchERRID = 0 End If Case ERRID.ERR_TwoParametersRequired1 Debug.Assert(OverloadResolution.GetOperatorInfo(name).ParamCount = 2) If syntax.ParameterList.Parameters.Count = 2 Then paramCountMismatchERRID = 0 End If Case ERRID.ERR_OneOrTwoParametersRequired1 If syntax.ParameterList.Parameters.Count = 1 OrElse 2 = syntax.ParameterList.Parameters.Count Then Debug.Assert(OverloadResolution.GetOperatorInfo(name).ParamCount = syntax.ParameterList.Parameters.Count) paramCountMismatchERRID = 0 End If Case Else Throw ExceptionUtilities.UnexpectedValue(paramCountMismatchERRID) End Select If paramCountMismatchERRID <> 0 Then binder.ReportDiagnostic(diagBag, syntax.OperatorToken, paramCountMismatchERRID, SyntaxFacts.GetText(syntax.OperatorToken.Kind)) End If ' ERRID.ERR_OperatorDeclaredInModule is reported by the parser. flags = flags Or If(syntax.OperatorToken.Kind = SyntaxKind.CTypeKeyword, SourceMemberFlags.MethodKindConversion, SourceMemberFlags.MethodKindOperator) Return New SourceMemberMethodSymbol( container, name, flags, binder, syntax, arity:=0) End Function ' Create a constructor. Friend Shared Function CreateConstructor(container As SourceMemberContainerTypeSymbol, syntax As SubNewStatementSyntax, binder As Binder, diagBag As DiagnosticBag) As SourceMethodSymbol ' Flags Dim modifiers = DecodeConstructorModifiers(syntax.Modifiers, container, binder, diagBag) Dim flags = modifiers.AllFlags Or SourceMemberFlags.MethodIsSub ' Name, Kind Dim name As String If (flags And SourceMemberFlags.Shared) <> 0 Then name = WellKnownMemberNames.StaticConstructorName flags = flags Or SourceMemberFlags.MethodKindSharedConstructor If (syntax.ParameterList IsNot Nothing AndAlso syntax.ParameterList.Parameters.Count > 0) Then ' shared constructor cannot have parameters. binder.ReportDiagnostic(diagBag, syntax.ParameterList, ERRID.ERR_SharedConstructorWithParams) End If Else name = WellKnownMemberNames.InstanceConstructorName flags = flags Or SourceMemberFlags.MethodKindConstructor End If Dim methodSym As New SourceMemberMethodSymbol(container, name, flags, binder, syntax, arity:=0) If (flags And SourceMemberFlags.Shared) = 0 Then If container.TypeKind = TYPEKIND.Structure AndAlso methodSym.ParameterCount = 0 Then ' Instance constructor must have parameters. binder.ReportDiagnostic(diagBag, syntax.NewKeyword, ERRID.ERR_NewInStruct) End If End If Return methodSym End Function ' Decode the modifiers on the method, reporting errors where applicable. Private Shared Function DecodeMethodModifiers(modifiers As SyntaxTokenList, container As SourceMemberContainerTypeSymbol, binder As Binder, diagBag As DiagnosticBag) As MemberModifiers ' Decode the flags. Dim methodModifiers = binder.DecodeModifiers(modifiers, SourceMemberFlags.AllAccessibilityModifiers Or SourceMemberFlags.Overloads Or SourceMemberFlags.Partial Or SourceMemberFlags.Shadows Or SourceMemberFlags.Shared Or SourceMemberFlags.Overridable Or SourceMemberFlags.NotOverridable Or SourceMemberFlags.Overrides Or SourceMemberFlags.MustOverride Or SourceMemberFlags.Async Or SourceMemberFlags.Iterator, ERRID.ERR_BadMethodFlags1, Accessibility.Public, diagBag) methodModifiers = binder.ValidateSharedPropertyAndMethodModifiers(modifiers, methodModifiers, False, container, diagBag) Const asyncIterator As SourceMemberFlags = SourceMemberFlags.Async Or SourceMemberFlags.Iterator If (methodModifiers.FoundFlags And asyncIterator) = asyncIterator Then binder.ReportModifierError(modifiers, ERRID.ERR_InvalidAsyncIteratorModifiers, diagBag, InvalidAsyncIterator) End If Return methodModifiers End Function ''' <summary> ''' Decode the modifiers on a user-defined operator, reporting errors where applicable. ''' </summary> Private Shared Function DecodeOperatorModifiers(syntax As OperatorStatementSyntax, binder As Binder, diagBag As DiagnosticBag) As MemberModifiers ' Decode the flags. Dim allowModifiers As SourceMemberFlags = SourceMemberFlags.AllAccessibilityModifiers Or SourceMemberFlags.Shared Or SourceMemberFlags.Overloads Or SourceMemberFlags.Shadows Or SourceMemberFlags.Widening Or SourceMemberFlags.Narrowing Dim operatorModifiers = binder.DecodeModifiers(syntax.Modifiers, allowModifiers, ERRID.ERR_BadOperatorFlags1, Accessibility.Public, diagBag) Dim foundFlags As SourceMemberFlags = operatorModifiers.FoundFlags Dim computedFlags As SourceMemberFlags = operatorModifiers.ComputedFlags ' It is OK to remove/add flags from the found list once an error is reported Dim foundAccessibility = foundFlags And SourceMemberFlags.AllAccessibilityModifiers If foundAccessibility <> 0 AndAlso foundAccessibility <> SourceMemberFlags.Public Then binder.ReportModifierError(syntax.Modifiers, ERRID.ERR_OperatorMustBePublic, diagBag, SyntaxKind.PrivateKeyword, SyntaxKind.ProtectedKeyword, SyntaxKind.FriendKeyword) foundFlags = foundFlags And Not SourceMemberFlags.AllAccessibilityModifiers computedFlags = (computedFlags And Not SourceMemberFlags.AccessibilityMask) Or SourceMemberFlags.AccessibilityPublic End If If (foundFlags And SourceMemberFlags.Shared) = 0 Then binder.ReportDiagnostic(diagBag, syntax.OperatorToken, ERRID.ERR_OperatorMustBeShared) computedFlags = computedFlags Or SourceMemberFlags.Shared End If If syntax.OperatorToken.Kind = SyntaxKind.CTypeKeyword Then If (foundFlags And (SourceMemberFlags.Narrowing Or SourceMemberFlags.Widening)) = 0 Then binder.ReportDiagnostic(diagBag, syntax.OperatorToken, ERRID.ERR_ConvMustBeWideningOrNarrowing) computedFlags = computedFlags Or SourceMemberFlags.Narrowing End If ElseIf (foundFlags And (SourceMemberFlags.Narrowing Or SourceMemberFlags.Widening)) <> 0 Then binder.ReportModifierError(syntax.Modifiers, ERRID.ERR_InvalidSpecifierOnNonConversion1, diagBag, SyntaxKind.NarrowingKeyword, SyntaxKind.WideningKeyword) foundFlags = foundFlags And Not (SourceMemberFlags.Narrowing Or SourceMemberFlags.Widening) End If Return New MemberModifiers(foundFlags, computedFlags) End Function ' Decode the modifiers on a constructor, reporting errors where applicable. Constructors are more restrictive ' than regular methods, so they have more errors. Friend Shared Function DecodeConstructorModifiers(modifiers As SyntaxTokenList, container As SourceMemberContainerTypeSymbol, binder As Binder, diagBag As DiagnosticBag) As MemberModifiers Dim constructorModifiers = DecodeMethodModifiers(modifiers, container, binder, diagBag) Dim flags = constructorModifiers.FoundFlags Dim computedFlags = constructorModifiers.ComputedFlags ' It is OK to remove flags from the found list once an error is reported If (flags And (SourceMemberFlags.MustOverride Or SourceMemberFlags.Overridable Or SourceMemberFlags.NotOverridable Or SourceMemberFlags.Shadows)) <> 0 Then binder.ReportModifierError(modifiers, ERRID.ERR_BadFlagsOnNew1, diagBag, SyntaxKind.OverridableKeyword, SyntaxKind.MustOverrideKeyword, SyntaxKind.NotOverridableKeyword, SyntaxKind.ShadowsKeyword) flags = flags And Not (SourceMemberFlags.MustOverride Or SourceMemberFlags.Overridable Or SourceMemberFlags.NotOverridable Or SourceMemberFlags.Shadows) End If If (flags And SourceMemberFlags.Overrides) <> 0 Then binder.ReportModifierError(modifiers, ERRID.ERR_CantOverrideConstructor, diagBag, SyntaxKind.OverridesKeyword) flags = flags And Not SourceMemberFlags.Overrides End If If (flags And SourceMemberFlags.Partial) <> 0 Then binder.ReportModifierError(modifiers, ERRID.ERR_ConstructorCannotBeDeclaredPartial, diagBag, SyntaxKind.PartialKeyword) flags = flags And Not SourceMemberFlags.Partial End If If (flags And SourceMemberFlags.Overloads) <> 0 Then binder.ReportModifierError(modifiers, ERRID.ERR_BadFlagsOnNewOverloads, diagBag, SyntaxKind.OverloadsKeyword) flags = flags And Not SourceMemberFlags.Overloads End If If (flags And SourceMemberFlags.Async) <> 0 Then binder.ReportModifierError(modifiers, ERRID.ERR_ConstructorAsync, diagBag, SyntaxKind.AsyncKeyword) End If If ((constructorModifiers.AllFlags And SourceMemberFlags.Shared) <> 0) Then If (flags And SourceMemberFlags.AllAccessibilityModifiers) <> 0 Then ' Shared constructors can't be declared with accessibility modifiers binder.ReportModifierError(modifiers, ERRID.ERR_SharedConstructorIllegalSpec1, diagBag, SyntaxKind.PublicKeyword, SyntaxKind.PrivateKeyword, SyntaxKind.FriendKeyword, SyntaxKind.ProtectedKeyword) End If flags = (flags And Not SourceMemberFlags.AllAccessibilityModifiers) Or SourceMemberFlags.Private computedFlags = (computedFlags And Not SourceMemberFlags.AccessibilityMask) Or SourceMemberFlags.AccessibilityPrivate End If Return New MemberModifiers(flags, computedFlags) End Function #End Region Friend Overrides Sub GenerateDeclarationErrors(cancellationToken As CancellationToken) MyBase.GenerateDeclarationErrors(cancellationToken) ' Force signature in methods. Dim unusedType = Me.ReturnType Dim unusedAttributes = Me.GetReturnTypeAttributes() For Each parameter In Me.Parameters unusedAttributes = parameter.GetAttributes() If parameter.HasExplicitDefaultValue Then Dim defaultValue = parameter.ExplicitDefaultConstantValue() End If Next ' Ensure method type parameter constraints are resolved and checked. For Each typeParameter In Me.TypeParameters Dim unusedTypes = typeParameter.ConstraintTypesNoUseSiteDiagnostics Next ' Ensure Handles are resolved. Dim unusedHandles = Me.HandledEvents End Sub Friend ReadOnly Property Diagnostics As ImmutableArray(Of Diagnostic) Get Return _cachedDiagnostics End Get End Property ''' <summary> ''' Returns true if our diagnostics were used in the event that there were two threads racing. ''' </summary> Friend Function SetDiagnostics(diags As ImmutableArray(Of Diagnostic)) As Boolean Return ImmutableInterlocked.InterlockedInitialize(_cachedDiagnostics, diags) End Function Public Overrides ReadOnly Property IsImplicitlyDeclared As Boolean Get Return m_containingType.AreMembersImplicitlyDeclared End Get End Property Friend Overrides ReadOnly Property GenerateDebugInfoImpl As Boolean Get Return True End Get End Property Public NotOverridable Overrides ReadOnly Property ConstructedFrom As MethodSymbol Get Return Me End Get End Property Public NotOverridable Overrides ReadOnly Property ContainingSymbol As Symbol Get Return m_containingType End Get End Property Public Overrides ReadOnly Property ContainingType As NamedTypeSymbol Get Return m_containingType End Get End Property Public ReadOnly Property ContainingSourceModule As SourceModuleSymbol Get Return DirectCast(ContainingModule, SourceModuleSymbol) End Get End Property Public Overrides ReadOnly Property AssociatedSymbol As Symbol Get ' TODO: Associated property/event not implemented. Return Nothing End Get End Property Public Overrides ReadOnly Property ExplicitInterfaceImplementations As ImmutableArray(Of MethodSymbol) Get Return ImmutableArray(Of MethodSymbol).Empty End Get End Property #Region "Flags" Public Overrides ReadOnly Property MethodKind As MethodKind Get Return m_flags.ToMethodKind() End Get End Property Friend NotOverridable Overrides ReadOnly Property IsMethodKindBasedOnSyntax As Boolean Get Return True End Get End Property ' TODO (tomat): NotOverridable? Public Overrides ReadOnly Property DeclaredAccessibility As Accessibility Get Return CType((m_flags And SourceMemberFlags.AccessibilityMask), Accessibility) End Get End Property Public NotOverridable Overrides ReadOnly Property IsMustOverride As Boolean Get Return (m_flags And SourceMemberFlags.MustOverride) <> 0 End Get End Property Public NotOverridable Overrides ReadOnly Property IsNotOverridable As Boolean Get Return (m_flags And SourceMemberFlags.NotOverridable) <> 0 End Get End Property Public NotOverridable Overrides ReadOnly Property IsOverloads As Boolean Get If (m_flags And SourceMemberFlags.Shadows) <> 0 Then Return False ElseIf (m_flags And SourceMemberFlags.Overloads) <> 0 Then Return True Else Return (m_flags And SourceMemberFlags.Overrides) <> 0 End If End Get End Property Public NotOverridable Overrides ReadOnly Property IsOverridable As Boolean Get Return (m_flags And SourceMemberFlags.Overridable) <> 0 End Get End Property Public NotOverridable Overrides ReadOnly Property IsOverrides As Boolean Get Return (m_flags And SourceMemberFlags.Overrides) <> 0 End Get End Property Public NotOverridable Overrides ReadOnly Property IsShared As Boolean Get Return (m_flags And SourceMemberFlags.Shared) <> 0 End Get End Property Friend ReadOnly Property IsPartial As Boolean Get Return (m_flags And SourceMemberFlags.Partial) <> 0 End Get End Property ''' <summary> ''' True if 'Shadows' is explicitly specified in method's declaration. ''' </summary> Friend Overrides ReadOnly Property ShadowsExplicitly As Boolean ' TODO (tomat) : NotOverridable? Get Return (m_flags And SourceMemberFlags.Shadows) <> 0 End Get End Property ''' <summary> ''' True if 'Overloads' is explicitly specified in method's declaration. ''' </summary> Friend ReadOnly Property OverloadsExplicitly As Boolean Get Return (m_flags And SourceMemberFlags.Overloads) <> 0 End Get End Property ''' <summary> ''' True if 'Overrides' is explicitly specified in method's declaration. ''' </summary> Friend ReadOnly Property OverridesExplicitly As Boolean Get Return (m_flags And SourceMemberFlags.Overrides) <> 0 End Get End Property ''' <summary> ''' True if 'Handles' is specified in method's declaration ''' </summary> Friend ReadOnly Property HandlesEvents As Boolean Get Return (m_flags And SourceMemberFlags.MethodHandlesEvents) <> 0 End Get End Property Friend NotOverridable Overrides ReadOnly Property CallingConvention As CallingConvention Get Return If(IsShared, CallingConvention.Default, CallingConvention.HasThis) Or If(IsGenericMethod, CallingConvention.Generic, CallingConvention.Default) End Get End Property #End Region #Region "Syntax and Binding" ' Return the entire declaration block: Begin Statement + Body Statements + End Statement. Friend ReadOnly Property BlockSyntax As MethodBlockBaseSyntax Get If m_syntaxReferenceOpt Is Nothing Then Return Nothing End If Dim decl = m_syntaxReferenceOpt.GetSyntax() Return TryCast(decl.Parent, MethodBlockBaseSyntax) End Get End Property Friend Overrides ReadOnly Property Syntax As SyntaxNode Get If m_syntaxReferenceOpt Is Nothing Then Return Nothing End If ' usually the syntax of a source method symbol should be the block syntax Dim syntaxNode = Me.BlockSyntax If syntaxNode IsNot Nothing Then Return syntaxNode End If ' in case of a method in an interface there is no block. ' just return the sub/function statement in this case. Return m_syntaxReferenceOpt.GetVisualBasicSyntax() End Get End Property ' Return the syntax tree that contains the method block. Public ReadOnly Property SyntaxTree As SyntaxTree Get If m_syntaxReferenceOpt IsNot Nothing Then Return m_syntaxReferenceOpt.SyntaxTree End If Return Nothing End Get End Property Friend ReadOnly Property DeclarationSyntax As MethodBaseSyntax Get Return If(m_syntaxReferenceOpt IsNot Nothing, DirectCast(m_syntaxReferenceOpt.GetSyntax(), MethodBaseSyntax), Nothing) End Get End Property Friend Overridable ReadOnly Property HasEmptyBody As Boolean Get Dim blockSyntax = Me.BlockSyntax Return blockSyntax Is Nothing OrElse Not blockSyntax.Statements.Any End Get End Property Public Overrides ReadOnly Property DeclaringSyntaxReferences As ImmutableArray(Of SyntaxReference) Get Return GetDeclaringSyntaxReferenceHelper(m_syntaxReferenceOpt) End Get End Property Friend NotOverridable Overrides Function IsDefinedInSourceTree(tree As SyntaxTree, definedWithinSpan As TextSpan?, Optional cancellationToken As CancellationToken = Nothing) As Boolean Return IsDefinedInSourceTree(Me.Syntax, tree, definedWithinSpan, cancellationToken) End Function Public NotOverridable Overrides Function GetDocumentationCommentXml(Optional preferredCulture As CultureInfo = Nothing, Optional expandIncludes As Boolean = False, Optional cancellationToken As CancellationToken = Nothing) As String If expandIncludes Then Return GetAndCacheDocumentationComment(Me, preferredCulture, expandIncludes, _lazyExpandedDocComment, cancellationToken) Else Return GetAndCacheDocumentationComment(Me, preferredCulture, expandIncludes, _lazyDocComment, cancellationToken) End If End Function ''' <summary> ''' Return the location from syntax reference only. ''' </summary> Friend ReadOnly Property NonMergedLocation As Location Get Return If(m_syntaxReferenceOpt IsNot Nothing, GetSymbolLocation(m_syntaxReferenceOpt), Nothing) End Get End Property Friend Overrides Function GetLexicalSortKey() As LexicalSortKey ' WARNING: this should not allocate memory! Return If(m_syntaxReferenceOpt IsNot Nothing, New LexicalSortKey(m_syntaxReferenceOpt, Me.DeclaringCompilation), LexicalSortKey.NotInSource) End Function Public Overrides ReadOnly Property Locations As ImmutableArray(Of Location) Get ' NOTE: access to m_locations don't really need to be synchronized because ' it is never being modified after the method symbol is published If _lazyLocations.IsDefault Then ' This symbol location Dim location As Location = Me.NonMergedLocation ImmutableInterlocked.InterlockedCompareExchange(Me._lazyLocations, If(location Is Nothing, ImmutableArray(Of Location).Empty, ImmutableArray.Create(location)), Nothing) End If Return _lazyLocations End Get End Property ' Given a syntax ref, get the symbol location to return. We return the location of the name ' of the method. Private Function GetSymbolLocation(syntaxRef As SyntaxReference) As Location Dim syntaxNode = syntaxRef.GetVisualBasicSyntax() Dim syntaxTree = syntaxRef.SyntaxTree Return syntaxTree.GetLocation(GetMethodLocationFromSyntax(syntaxNode)) End Function ' Get the location of a method given the syntax for its declaration. We use the location of the name ' of the method, or similar keywords. Private Shared Function GetMethodLocationFromSyntax(node As VisualBasicSyntaxNode) As TextSpan Select Case node.Kind Case SyntaxKind.MultiLineFunctionLambdaExpression, SyntaxKind.MultiLineSubLambdaExpression, SyntaxKind.SingleLineFunctionLambdaExpression, SyntaxKind.SingleLineSubLambdaExpression Return DirectCast(node, LambdaExpressionSyntax).SubOrFunctionHeader.Span Case SyntaxKind.SubStatement, SyntaxKind.FunctionStatement Return DirectCast(node, MethodStatementSyntax).Identifier.Span Case SyntaxKind.DeclareSubStatement, SyntaxKind.DeclareFunctionStatement Return DirectCast(node, DeclareStatementSyntax).Identifier.Span Case SyntaxKind.SubNewStatement Return DirectCast(node, SubNewStatementSyntax).NewKeyword.Span Case SyntaxKind.OperatorStatement Return DirectCast(node, OperatorStatementSyntax).OperatorToken.Span Case Else Throw ExceptionUtilities.UnexpectedValue(node.Kind) End Select End Function ''' <summary> ''' Bind the constraint declarations for the given type parameter. ''' </summary> ''' <remarks> ''' The caller is expected to handle constraint checking and any caching of results. ''' </remarks> Friend Function BindTypeParameterConstraints(syntax As TypeParameterSyntax, diagnostics As BindingDiagnosticBag) As ImmutableArray(Of TypeParameterConstraint) Dim binder As Binder = BinderBuilder.CreateBinderForType(Me.ContainingSourceModule, Me.SyntaxTree, m_containingType) binder = BinderBuilder.CreateBinderForGenericMethodDeclaration(Me, binder) ' Handle type parameter variance. If syntax.VarianceKeyword.Kind <> SyntaxKind.None Then binder.ReportDiagnostic(diagnostics, syntax.VarianceKeyword, ERRID.ERR_VarianceDisallowedHere) End If ' Wrap constraints binder in a location-specific binder to ' avoid checking constraints when binding type names. binder = New LocationSpecificBinder(BindingLocation.GenericConstraintsClause, Me, binder) Return binder.BindTypeParameterConstraintClause(Me, syntax.TypeParameterConstraintClause, diagnostics) End Function ' Get the symbol name that would be used for this method base syntax. Friend Shared Function GetMemberNameFromSyntax(node As MethodBaseSyntax) As String Select Case node.Kind Case SyntaxKind.SubStatement, SyntaxKind.FunctionStatement Return DirectCast(node, MethodStatementSyntax).Identifier.ValueText Case SyntaxKind.PropertyStatement Return DirectCast(node, PropertyStatementSyntax).Identifier.ValueText Case SyntaxKind.DeclareSubStatement, SyntaxKind.DeclareFunctionStatement Return DirectCast(node, DeclareStatementSyntax).Identifier.ValueText Case SyntaxKind.OperatorStatement Dim operatorStatement = DirectCast(node, OperatorStatementSyntax) Select Case operatorStatement.OperatorToken.Kind Case SyntaxKind.NotKeyword Return WellKnownMemberNames.OnesComplementOperatorName Case SyntaxKind.IsTrueKeyword Return WellKnownMemberNames.TrueOperatorName Case SyntaxKind.IsFalseKeyword Return WellKnownMemberNames.FalseOperatorName Case SyntaxKind.PlusToken If operatorStatement.ParameterList.Parameters.Count <= 1 Then Return WellKnownMemberNames.UnaryPlusOperatorName Else Return WellKnownMemberNames.AdditionOperatorName End If Case SyntaxKind.MinusToken If operatorStatement.ParameterList.Parameters.Count <= 1 Then Return WellKnownMemberNames.UnaryNegationOperatorName Else Return WellKnownMemberNames.SubtractionOperatorName End If Case SyntaxKind.AsteriskToken Return WellKnownMemberNames.MultiplyOperatorName Case SyntaxKind.SlashToken Return WellKnownMemberNames.DivisionOperatorName Case SyntaxKind.BackslashToken Return WellKnownMemberNames.IntegerDivisionOperatorName Case SyntaxKind.ModKeyword Return WellKnownMemberNames.ModulusOperatorName Case SyntaxKind.CaretToken Return WellKnownMemberNames.ExponentOperatorName Case SyntaxKind.EqualsToken Return WellKnownMemberNames.EqualityOperatorName Case SyntaxKind.LessThanGreaterThanToken Return WellKnownMemberNames.InequalityOperatorName Case SyntaxKind.LessThanToken Return WellKnownMemberNames.LessThanOperatorName Case SyntaxKind.GreaterThanToken Return WellKnownMemberNames.GreaterThanOperatorName Case SyntaxKind.LessThanEqualsToken Return WellKnownMemberNames.LessThanOrEqualOperatorName Case SyntaxKind.GreaterThanEqualsToken Return WellKnownMemberNames.GreaterThanOrEqualOperatorName Case SyntaxKind.LikeKeyword Return WellKnownMemberNames.LikeOperatorName Case SyntaxKind.AmpersandToken Return WellKnownMemberNames.ConcatenateOperatorName Case SyntaxKind.AndKeyword Return WellKnownMemberNames.BitwiseAndOperatorName Case SyntaxKind.OrKeyword Return WellKnownMemberNames.BitwiseOrOperatorName Case SyntaxKind.XorKeyword Return WellKnownMemberNames.ExclusiveOrOperatorName Case SyntaxKind.LessThanLessThanToken Return WellKnownMemberNames.LeftShiftOperatorName Case SyntaxKind.GreaterThanGreaterThanToken Return WellKnownMemberNames.RightShiftOperatorName Case SyntaxKind.CTypeKeyword For Each keywordSyntax In operatorStatement.Modifiers Dim currentModifier As SourceMemberFlags = Binder.MapKeywordToFlag(keywordSyntax) If currentModifier = SourceMemberFlags.Widening Then Return WellKnownMemberNames.ImplicitConversionName ElseIf currentModifier = SourceMemberFlags.Narrowing Then Return WellKnownMemberNames.ExplicitConversionName End If Next Return WellKnownMemberNames.ExplicitConversionName Case Else Throw ExceptionUtilities.UnexpectedValue(operatorStatement.OperatorToken.Kind) End Select Case SyntaxKind.SubNewStatement ' Symbol name of a constructor depends on if it is shared. We ideally we like to just call ' DecodeConstructorModifiers here, but we don't have a binder or container to pass. So we have ' to duplicate some of the logic just to determine if it is shared. Dim isShared As Boolean = False For Each tok In node.Modifiers If tok.Kind = SyntaxKind.SharedKeyword Then isShared = True End If Next ' inside a module are implicitly shared. If node.Parent IsNot Nothing Then If node.Parent.Kind = SyntaxKind.ModuleBlock OrElse (node.Parent.Parent IsNot Nothing AndAlso node.Parent.Parent.Kind = SyntaxKind.ModuleBlock) Then isShared = True End If End If Return If(isShared, WellKnownMemberNames.StaticConstructorName, WellKnownMemberNames.InstanceConstructorName) Case Else Throw ExceptionUtilities.UnexpectedValue(node.Kind) End Select End Function ' Given the syntax declaration, and a container, get the source method symbol declared from that syntax. ' This is done by lookup up the name from the declaration in the container, handling duplicates and ' so forth correctly. Friend Shared Function FindSymbolFromSyntax(syntax As MethodBaseSyntax, tree As SyntaxTree, container As NamedTypeSymbol) As Symbol Select Case syntax.Kind Case SyntaxKind.GetAccessorStatement, SyntaxKind.SetAccessorStatement Dim propertySyntax = TryCast(syntax.Parent.Parent, PropertyBlockSyntax) If propertySyntax IsNot Nothing Then Dim propertyIdentifier = propertySyntax.PropertyStatement.Identifier Dim propertySymbol = DirectCast( container.FindMember(propertyIdentifier.ValueText, SymbolKind.Property, propertyIdentifier.Span, tree), PropertySymbol) ' in case of ill formed syntax it can happen that the ContainingType of the actual binder does not directly contain ' this property symbol. One example is e.g. a namespace nested in a class. Instead of a namespace binder, the containing ' binder will be used in this error case and then member lookups will fail because the symbol of the containing binder does ' not contain these members. If propertySymbol Is Nothing Then Return Nothing End If Dim accessor = If(syntax.Kind = SyntaxKind.GetAccessorStatement, propertySymbol.GetMethod, propertySymbol.SetMethod) ' symbol must have same syntax as the accessor's block If accessor.Syntax Is syntax.Parent Then Return accessor Else ' This can happen if property has multiple accessors. ' Parser allows multiple accessors, but binder will accept only one of a kind Return Nothing End If Else ' Did not find a property block. Can happen if syntax was ill-formed. Return Nothing End If Case SyntaxKind.AddHandlerAccessorStatement, SyntaxKind.RemoveHandlerAccessorStatement, SyntaxKind.RaiseEventAccessorStatement Dim eventBlockSyntax = TryCast(syntax.Parent.Parent, EventBlockSyntax) If eventBlockSyntax IsNot Nothing Then Dim eventIdentifier = eventBlockSyntax.EventStatement.Identifier Dim eventSymbol = DirectCast( container.FindMember(eventIdentifier.ValueText, SymbolKind.Event, eventIdentifier.Span, tree), EventSymbol) ' in case of ill formed syntax it can happen that the ContainingType of the actual binder does not directly contain ' this event symbol. One example is e.g. a namespace nested in a class. Instead of a namespace binder, the containing ' binder will be used in this error case and then member lookups will fail because the symbol of the containing binder does ' not contain these members. If eventSymbol Is Nothing Then Return Nothing End If Dim accessor As MethodSymbol = Nothing Select Case syntax.Kind Case SyntaxKind.AddHandlerAccessorStatement accessor = eventSymbol.AddMethod Case SyntaxKind.RemoveHandlerAccessorStatement accessor = eventSymbol.RemoveMethod Case SyntaxKind.RaiseEventAccessorStatement accessor = eventSymbol.RaiseMethod End Select ' symbol must have same syntax as the accessor's block If accessor IsNot Nothing AndAlso accessor.Syntax Is syntax.Parent Then Return accessor Else ' This can happen if event has multiple accessors. ' Parser allows multiple accessors, but binder will accept only one of a kind Return Nothing End If Else ' Did not find an event block. Can happen if syntax was ill-formed. Return Nothing End If Case SyntaxKind.PropertyStatement Dim propertyIdentifier = DirectCast(syntax, PropertyStatementSyntax).Identifier Return container.FindMember(propertyIdentifier.ValueText, SymbolKind.Property, propertyIdentifier.Span, tree) Case SyntaxKind.EventStatement Dim eventIdentifier = DirectCast(syntax, EventStatementSyntax).Identifier Return container.FindMember(eventIdentifier.ValueText, SymbolKind.Event, eventIdentifier.Span, tree) Case SyntaxKind.DelegateFunctionStatement, SyntaxKind.DelegateSubStatement Dim delegateIdentifier = DirectCast(syntax, DelegateStatementSyntax).Identifier Return container.FindMember(delegateIdentifier.ValueText, SymbolKind.NamedType, delegateIdentifier.Span, tree) Case Else Dim methodSymbol = DirectCast(container.FindMember(GetMemberNameFromSyntax(syntax), SymbolKind.Method, GetMethodLocationFromSyntax(syntax), tree), MethodSymbol) ' Substitute with partial method implementation? If methodSymbol IsNot Nothing Then Dim partialImpl = methodSymbol.PartialImplementationPart If partialImpl IsNot Nothing AndAlso partialImpl.Syntax Is syntax.Parent Then methodSymbol = partialImpl End If End If Return methodSymbol End Select End Function ' Get the location of the implements name for an explicit implemented method, for later error reporting. Friend Function GetImplementingLocation(implementedMethod As MethodSymbol) As Location Debug.Assert(ExplicitInterfaceImplementations.Contains(implementedMethod)) Dim methodSyntax As MethodStatementSyntax = Nothing Dim syntaxTree As SyntaxTree = Nothing Dim containingSourceType = TryCast(m_containingType, SourceMemberContainerTypeSymbol) If m_syntaxReferenceOpt IsNot Nothing Then methodSyntax = TryCast(m_syntaxReferenceOpt.GetSyntax(), MethodStatementSyntax) syntaxTree = m_syntaxReferenceOpt.SyntaxTree End If If methodSyntax IsNot Nothing AndAlso methodSyntax.ImplementsClause IsNot Nothing AndAlso containingSourceType IsNot Nothing Then Dim binder As Binder = BinderBuilder.CreateBinderForType(containingSourceType.ContainingSourceModule, syntaxTree, containingSourceType) Dim implementingSyntax = FindImplementingSyntax(methodSyntax.ImplementsClause, Me, implementedMethod, containingSourceType, binder) Return implementingSyntax.GetLocation() End If Return If(Locations.FirstOrDefault(), NoLocation.Singleton) End Function Friend Overrides Function GetBoundMethodBody(compilationState As TypeCompilationState, diagnostics As BindingDiagnosticBag, Optional ByRef methodBodyBinder As Binder = Nothing) As BoundBlock Dim syntaxTree As SyntaxTree = Me.SyntaxTree ' All source method symbols must have block syntax. Dim methodBlock As MethodBlockBaseSyntax = Me.BlockSyntax Debug.Assert(methodBlock IsNot Nothing) ' Bind the method block methodBodyBinder = BinderBuilder.CreateBinderForMethodBody(ContainingSourceModule, syntaxTree, Me) #If DEBUG Then ' Enable DEBUG check for ordering of simple name binding. methodBodyBinder.EnableSimpleNameBindingOrderChecks(True) #End If Dim boundStatement = methodBodyBinder.BindStatement(methodBlock, diagnostics) #If DEBUG Then methodBodyBinder.EnableSimpleNameBindingOrderChecks(False) #End If If boundStatement.Kind = BoundKind.Block Then Return DirectCast(boundStatement, BoundBlock) End If Return New BoundBlock(methodBlock, methodBlock.Statements, ImmutableArray(Of LocalSymbol).Empty, ImmutableArray.Create(boundStatement)) End Function Friend NotOverridable Overrides Function CalculateLocalSyntaxOffset(localPosition As Integer, localTree As SyntaxTree) As Integer Dim span As TextSpan Dim block = BlockSyntax If block IsNot Nothing AndAlso localTree Is block.SyntaxTree Then ' Assign all variables that are associated with the header -1. ' We can't assign >=0 since user-defined variables defined in the first statement of the body have 0 ' and user-defined variables need to have a unique syntax offset. If localPosition = block.BlockStatement.SpanStart Then Return -1 End If span = block.Statements.Span If span.Contains(localPosition) Then Return localPosition - span.Start End If End If ' Calculates a syntax offset of a syntax position which must be either a property or field initializer. Dim syntaxOffset As Integer Dim containingType = DirectCast(Me.ContainingType, SourceNamedTypeSymbol) If containingType.TryCalculateSyntaxOffsetOfPositionInInitializer(localPosition, localTree, Me.IsShared, syntaxOffset) Then Return syntaxOffset End If Throw ExceptionUtilities.Unreachable End Function #End Region #Region "Signature" Public NotOverridable Overrides ReadOnly Property IsVararg As Boolean Get Return False End Get End Property Public NotOverridable Overrides ReadOnly Property IsGenericMethod As Boolean Get Return Arity <> 0 End Get End Property Public NotOverridable Overrides ReadOnly Property TypeArguments As ImmutableArray(Of TypeSymbol) Get Debug.Assert(Not TypeParameters.IsDefault) Return StaticCast(Of TypeSymbol).From(TypeParameters) End Get End Property Public Overrides ReadOnly Property Arity As Integer Get Return TypeParameters.Length End Get End Property Public NotOverridable Overrides ReadOnly Property ReturnsByRef As Boolean Get ' It is not possible to define ref-returning methods in source. Return False End Get End Property Public NotOverridable Overrides ReadOnly Property RefCustomModifiers As ImmutableArray(Of CustomModifier) Get Return ImmutableArray(Of CustomModifier).Empty End Get End Property Public Overrides ReadOnly Property IsSub As Boolean Get Debug.Assert(Me.MethodKind <> MethodKind.EventAdd, "Can't trust the flag for event adders, because their signatures are different under WinRT") Return (m_flags And SourceMemberFlags.MethodIsSub) <> 0 End Get End Property Public NotOverridable Overrides ReadOnly Property IsAsync As Boolean Get Return (m_flags And SourceMemberFlags.Async) <> 0 End Get End Property Public NotOverridable Overrides ReadOnly Property IsIterator As Boolean Get Return (m_flags And SourceMemberFlags.Iterator) <> 0 End Get End Property Public NotOverridable Overrides ReadOnly Property IsInitOnly As Boolean Get Return False End Get End Property Friend NotOverridable Overrides Function TryGetMeParameter(<Out> ByRef meParameter As ParameterSymbol) As Boolean If IsShared Then meParameter = Nothing Else If _lazyMeParameter Is Nothing Then Interlocked.CompareExchange(_lazyMeParameter, New MeParameterSymbol(Me), Nothing) End If meParameter = _lazyMeParameter End If Return True End Function Public Overrides ReadOnly Property ReturnTypeCustomModifiers As ImmutableArray(Of CustomModifier) Get Dim overridden = Me.OverriddenMethod If overridden Is Nothing Then Return ImmutableArray(Of CustomModifier).Empty Else Return overridden.ConstructIfGeneric(TypeArguments).ReturnTypeCustomModifiers End If End Get End Property #End Region #Region "Attributes" ''' <summary> ''' Symbol to copy bound attributes from, or null if the attributes are not shared among multiple source method symbols. ''' </summary> ''' <remarks> ''' Used for example for event accessors. The "remove" method delegates attribute binding to the "add" method. ''' The bound attribute data are then applied to both accessors. ''' </remarks> Protected Overridable ReadOnly Property BoundAttributesSource As SourceMethodSymbol Get Return Nothing End Get End Property ''' <summary> ''' Symbol to copy bound return type attributes from, or null if the attributes are not shared among multiple source symbols. ''' </summary> ''' <remarks> ''' Used for property accessors. Getter copies its return type attributes from the property return type attributes. ''' ''' So far we only need to return <see cref="SourcePropertySymbol"/>. If we ever needed to return a <see cref="SourceMethodSymbol"/> ''' we could implement an interface on those two types. ''' </remarks> Protected Overridable ReadOnly Property BoundReturnTypeAttributesSource As SourcePropertySymbol Get Return Nothing End Get End Property Protected ReadOnly Property AttributeDeclarationSyntaxList As SyntaxList(Of AttributeListSyntax) Get Return If(m_syntaxReferenceOpt IsNot Nothing, DeclarationSyntax.AttributeLists, Nothing) End Get End Property Protected ReadOnly Property ReturnTypeAttributeDeclarationSyntaxList As SyntaxList(Of AttributeListSyntax) Get Dim syntax = DeclarationSyntax If syntax IsNot Nothing Then Dim asClauseOpt = syntax.AsClauseInternal If asClauseOpt IsNot Nothing Then Return asClauseOpt.Attributes End If End If Return Nothing End Get End Property Protected Overridable Function GetAttributeDeclarations() As OneOrMany(Of SyntaxList(Of AttributeListSyntax)) Return OneOrMany.Create(AttributeDeclarationSyntaxList) End Function Protected Overridable Function GetReturnTypeAttributeDeclarations() As OneOrMany(Of SyntaxList(Of AttributeListSyntax)) Return OneOrMany.Create(ReturnTypeAttributeDeclarationSyntaxList) End Function Public ReadOnly Property DefaultAttributeLocation As AttributeLocation Implements IAttributeTargetSymbol.DefaultAttributeLocation Get Return AttributeLocation.Method End Get End Property Private Function GetAttributesBag() As CustomAttributesBag(Of VisualBasicAttributeData) Return GetAttributesBag(m_lazyCustomAttributesBag, forReturnType:=False) End Function Private Function GetReturnTypeAttributesBag() As CustomAttributesBag(Of VisualBasicAttributeData) Return GetAttributesBag(m_lazyReturnTypeCustomAttributesBag, forReturnType:=True) End Function Private Function GetAttributesBag(ByRef lazyCustomAttributesBag As CustomAttributesBag(Of VisualBasicAttributeData), forReturnType As Boolean) As CustomAttributesBag(Of VisualBasicAttributeData) If lazyCustomAttributesBag Is Nothing OrElse Not lazyCustomAttributesBag.IsSealed Then If forReturnType Then Dim copyFrom = Me.BoundReturnTypeAttributesSource ' prevent infinite recursion: Debug.Assert(copyFrom IsNot Me) If copyFrom IsNot Nothing Then Dim attributesBag = copyFrom.GetReturnTypeAttributesBag() Interlocked.CompareExchange(lazyCustomAttributesBag, attributesBag, Nothing) Else LoadAndValidateAttributes(Me.GetReturnTypeAttributeDeclarations(), lazyCustomAttributesBag, symbolPart:=AttributeLocation.Return) End If Else Dim copyFrom = Me.BoundAttributesSource ' prevent infinite recursion: Debug.Assert(copyFrom IsNot Me) If copyFrom IsNot Nothing Then Dim attributesBag = copyFrom.GetAttributesBag() Interlocked.CompareExchange(lazyCustomAttributesBag, attributesBag, Nothing) Else LoadAndValidateAttributes(Me.GetAttributeDeclarations(), lazyCustomAttributesBag) End If End If End If Return lazyCustomAttributesBag End Function ''' <summary> ''' Gets the attributes applied on this symbol. ''' Returns an empty array if there are no attributes. ''' </summary> Public NotOverridable Overrides Function GetAttributes() As ImmutableArray(Of VisualBasicAttributeData) Return Me.GetAttributesBag().Attributes End Function Friend Overrides Sub AddSynthesizedAttributes(compilationState As ModuleCompilationState, ByRef attributes As ArrayBuilder(Of SynthesizedAttributeData)) MyBase.AddSynthesizedAttributes(compilationState, attributes) ' Emit synthesized STAThreadAttribute for this method if both the following requirements are met: ' (a) This is the entry point method. ' (b) There is no applied STAThread or MTAThread attribute on this method. Dim compilation = Me.DeclaringCompilation Dim entryPointMethod As MethodSymbol = compilation.GetEntryPoint(CancellationToken.None) If Me Is entryPointMethod Then If Not Me.HasSTAThreadOrMTAThreadAttribute Then ' UNDONE: UV Support: Do not emit if using the starlite libraries. AddSynthesizedAttribute(attributes, compilation.TrySynthesizeAttribute( WellKnownMember.System_STAThreadAttribute__ctor)) End If End If End Sub Friend Overrides Sub AddSynthesizedReturnTypeAttributes(ByRef attributes As ArrayBuilder(Of SynthesizedAttributeData)) MyBase.AddSynthesizedReturnTypeAttributes(attributes) If Me.ReturnType.ContainsTupleNames() Then AddSynthesizedAttribute(attributes, DeclaringCompilation.SynthesizeTupleNamesAttribute(Me.ReturnType)) End If End Sub Protected Function GetDecodedWellKnownAttributeData() As MethodWellKnownAttributeData Dim attributesBag As CustomAttributesBag(Of VisualBasicAttributeData) = Me.m_lazyCustomAttributesBag If attributesBag Is Nothing OrElse Not attributesBag.IsDecodedWellKnownAttributeDataComputed Then attributesBag = Me.GetAttributesBag() End If Return DirectCast(attributesBag.DecodedWellKnownAttributeData, MethodWellKnownAttributeData) End Function ''' <summary> ''' Returns the list of attributes, if any, associated with the return type. ''' </summary> Public NotOverridable Overrides Function GetReturnTypeAttributes() As ImmutableArray(Of VisualBasicAttributeData) Return Me.GetReturnTypeAttributesBag().Attributes End Function Private Function GetDecodedReturnTypeWellKnownAttributeData() As CommonReturnTypeWellKnownAttributeData Dim attributesBag As CustomAttributesBag(Of VisualBasicAttributeData) = Me.m_lazyReturnTypeCustomAttributesBag If attributesBag Is Nothing OrElse Not attributesBag.IsDecodedWellKnownAttributeDataComputed Then attributesBag = Me.GetReturnTypeAttributesBag() End If Return DirectCast(attributesBag.DecodedWellKnownAttributeData, CommonReturnTypeWellKnownAttributeData) End Function Friend Overrides Function EarlyDecodeWellKnownAttribute(ByRef arguments As EarlyDecodeWellKnownAttributeArguments(Of EarlyWellKnownAttributeBinder, NamedTypeSymbol, AttributeSyntax, AttributeLocation)) As VisualBasicAttributeData Debug.Assert(arguments.AttributeType IsNot Nothing) Debug.Assert(Not arguments.AttributeType.IsErrorType()) Dim hasAnyDiagnostics As Boolean = False If arguments.SymbolPart <> AttributeLocation.Return Then If VisualBasicAttributeData.IsTargetEarlyAttribute(arguments.AttributeType, arguments.AttributeSyntax, AttributeDescription.CaseInsensitiveExtensionAttribute) Then Dim isExtensionMethod As Boolean = False If Not (Me.MethodKind <> MethodKind.Ordinary AndAlso Me.MethodKind <> MethodKind.DeclareMethod) AndAlso m_containingType.AllowsExtensionMethods() AndAlso Me.ParameterCount <> 0 Then Debug.Assert(Me.IsShared) Dim firstParam As ParameterSymbol = Me.Parameters(0) If Not firstParam.IsOptional AndAlso Not firstParam.IsParamArray AndAlso ValidateGenericConstraintsOnExtensionMethodDefinition() Then isExtensionMethod = m_containingType.MightContainExtensionMethods End If End If If isExtensionMethod Then Dim attrdata = arguments.Binder.GetAttribute(arguments.AttributeSyntax, arguments.AttributeType, hasAnyDiagnostics) If Not attrdata.HasErrors Then arguments.GetOrCreateData(Of MethodEarlyWellKnownAttributeData)().IsExtensionMethod = True Return If(Not hasAnyDiagnostics, attrdata, Nothing) End If End If Return Nothing ElseIf VisualBasicAttributeData.IsTargetEarlyAttribute(arguments.AttributeType, arguments.AttributeSyntax, AttributeDescription.ConditionalAttribute) Then Dim attrdata = arguments.Binder.GetAttribute(arguments.AttributeSyntax, arguments.AttributeType, hasAnyDiagnostics) If Not attrdata.HasErrors Then Dim conditionalSymbol As String = attrdata.GetConstructorArgument(Of String)(0, SpecialType.System_String) arguments.GetOrCreateData(Of MethodEarlyWellKnownAttributeData)().AddConditionalSymbol(conditionalSymbol) Return If(Not hasAnyDiagnostics, attrdata, Nothing) Else Return Nothing End If Else Dim BoundAttribute As VisualBasicAttributeData = Nothing Dim obsoleteData As ObsoleteAttributeData = Nothing If EarlyDecodeDeprecatedOrExperimentalOrObsoleteAttribute(arguments, BoundAttribute, obsoleteData) Then If obsoleteData IsNot Nothing Then arguments.GetOrCreateData(Of MethodEarlyWellKnownAttributeData)().ObsoleteAttributeData = obsoleteData End If Return BoundAttribute End If End If End If Return MyBase.EarlyDecodeWellKnownAttribute(arguments) End Function ''' <summary> ''' Returns data decoded from early bound well-known attributes applied to the symbol or null if there are no applied attributes. ''' </summary> ''' <remarks> ''' Forces binding and decoding of attributes. ''' </remarks> Private Function GetEarlyDecodedWellKnownAttributeData() As MethodEarlyWellKnownAttributeData Dim attributesBag As CustomAttributesBag(Of VisualBasicAttributeData) = Me.m_lazyCustomAttributesBag If attributesBag Is Nothing OrElse Not attributesBag.IsEarlyDecodedWellKnownAttributeDataComputed Then attributesBag = Me.GetAttributesBag() End If Return DirectCast(attributesBag.EarlyDecodedWellKnownAttributeData, MethodEarlyWellKnownAttributeData) End Function Friend Overrides Function GetAppliedConditionalSymbols() As ImmutableArray(Of String) Dim data As MethodEarlyWellKnownAttributeData = Me.GetEarlyDecodedWellKnownAttributeData() Return If(data IsNot Nothing, data.ConditionalSymbols, ImmutableArray(Of String).Empty) End Function Friend Overrides Sub DecodeWellKnownAttribute(ByRef arguments As DecodeWellKnownAttributeArguments(Of AttributeSyntax, VisualBasicAttributeData, AttributeLocation)) Dim attrData = arguments.Attribute Debug.Assert(Not attrData.HasErrors) If attrData.IsTargetAttribute(Me, AttributeDescription.TupleElementNamesAttribute) Then DirectCast(arguments.Diagnostics, BindingDiagnosticBag).Add(ERRID.ERR_ExplicitTupleElementNamesAttribute, arguments.AttributeSyntaxOpt.Location) ElseIf attrData.IsTargetAttribute(Me, AttributeDescription.UnmanagedCallersOnlyAttribute) Then ' VB does not support UnmanagedCallersOnly attributes on methods at all DirectCast(arguments.Diagnostics, BindingDiagnosticBag).Add(ERRID.ERR_UnmanagedCallersOnlyNotSupported, arguments.AttributeSyntaxOpt.Location) End If If arguments.SymbolPart = AttributeLocation.Return Then ' Decode well-known attributes applied to return value DecodeWellKnownAttributeAppliedToReturnValue(arguments) Else Debug.Assert(arguments.SymbolPart = AttributeLocation.None) DecodeWellKnownAttributeAppliedToMethod(arguments) End If MyBase.DecodeWellKnownAttribute(arguments) End Sub Private Sub DecodeWellKnownAttributeAppliedToMethod(ByRef arguments As DecodeWellKnownAttributeArguments(Of AttributeSyntax, VisualBasicAttributeData, AttributeLocation)) Debug.Assert(arguments.AttributeSyntaxOpt IsNot Nothing) Dim diagnostics = DirectCast(arguments.Diagnostics, BindingDiagnosticBag) ' Decode well-known attributes applied to method Dim attrData = arguments.Attribute If attrData.IsTargetAttribute(Me, AttributeDescription.CaseInsensitiveExtensionAttribute) Then ' Just report errors here. The extension attribute is decoded early. If Me.MethodKind <> MethodKind.Ordinary AndAlso Me.MethodKind <> MethodKind.DeclareMethod Then diagnostics.Add(ERRID.ERR_ExtensionOnlyAllowedOnModuleSubOrFunction, arguments.AttributeSyntaxOpt.GetLocation()) ElseIf Not m_containingType.AllowsExtensionMethods() Then diagnostics.Add(ERRID.ERR_ExtensionMethodNotInModule, arguments.AttributeSyntaxOpt.GetLocation()) ElseIf Me.ParameterCount = 0 Then diagnostics.Add(ERRID.ERR_ExtensionMethodNoParams, Me.Locations(0)) Else Debug.Assert(Me.IsShared) Dim firstParam As ParameterSymbol = Me.Parameters(0) If firstParam.IsOptional Then diagnostics.Add(ErrorFactory.ErrorInfo(ERRID.ERR_ExtensionMethodOptionalFirstArg), firstParam.Locations(0)) ElseIf firstParam.IsParamArray Then diagnostics.Add(ErrorFactory.ErrorInfo(ERRID.ERR_ExtensionMethodParamArrayFirstArg), firstParam.Locations(0)) ElseIf Not Me.ValidateGenericConstraintsOnExtensionMethodDefinition() Then diagnostics.Add(ErrorFactory.ErrorInfo(ERRID.ERR_ExtensionMethodUncallable1, Me.Name), Me.Locations(0)) End If End If ElseIf attrData.IsTargetAttribute(Me, AttributeDescription.WebMethodAttribute) Then ' Check for optional parameters For Each parameter In Me.Parameters If parameter.IsOptional Then diagnostics.Add(ErrorFactory.ErrorInfo(ERRID.ERR_InvalidOptionalParameterUsage1, "WebMethod"), Me.Locations(0)) End If Next ElseIf attrData.IsTargetAttribute(Me, AttributeDescription.PreserveSigAttribute) Then arguments.GetOrCreateData(Of MethodWellKnownAttributeData)().SetPreserveSignature(arguments.Index) ElseIf attrData.IsTargetAttribute(Me, AttributeDescription.MethodImplAttribute) Then AttributeData.DecodeMethodImplAttribute(Of MethodWellKnownAttributeData, AttributeSyntax, VisualBasicAttributeData, AttributeLocation)(arguments, MessageProvider.Instance) ElseIf attrData.IsTargetAttribute(Me, AttributeDescription.DllImportAttribute) Then If Not IsDllImportAttributeAllowed(arguments.AttributeSyntaxOpt, diagnostics) Then Return End If Dim moduleName As String = TryCast(attrData.CommonConstructorArguments(0).ValueInternal, String) If Not MetadataHelpers.IsValidMetadataIdentifier(moduleName) Then diagnostics.Add(ERRID.ERR_BadAttribute1, arguments.AttributeSyntaxOpt.ArgumentList.Arguments(0).GetLocation(), attrData.AttributeClass) End If ' Default value of charset is inherited from the module (only if specified). ' This might be different from ContainingType.DefaultMarshallingCharSet. If the charset is not specified on module ' ContainingType.DefaultMarshallingCharSet would be Ansi (the class is emitted with "Ansi" charset metadata flag) ' while the charset in P/Invoke metadata should be "None". Dim charSet As CharSet = If(Me.EffectiveDefaultMarshallingCharSet, Microsoft.Cci.Constants.CharSet_None) Dim importName As String = Nothing Dim preserveSig As Boolean = True Dim callingConvention As System.Runtime.InteropServices.CallingConvention = System.Runtime.InteropServices.CallingConvention.Winapi Dim setLastError As Boolean = False Dim exactSpelling As Boolean = False Dim bestFitMapping As Boolean? = Nothing Dim throwOnUnmappable As Boolean? = Nothing Dim position As Integer = 1 For Each namedArg In attrData.CommonNamedArguments Select Case namedArg.Key Case "EntryPoint" importName = TryCast(namedArg.Value.ValueInternal, String) If Not MetadataHelpers.IsValidMetadataIdentifier(importName) Then diagnostics.Add(ERRID.ERR_BadAttribute1, arguments.AttributeSyntaxOpt.ArgumentList.Arguments(position).GetLocation(), attrData.AttributeClass) Return End If Case "CharSet" charSet = namedArg.Value.DecodeValue(Of CharSet)(SpecialType.System_Enum) Case "SetLastError" setLastError = namedArg.Value.DecodeValue(Of Boolean)(SpecialType.System_Boolean) Case "ExactSpelling" exactSpelling = namedArg.Value.DecodeValue(Of Boolean)(SpecialType.System_Boolean) Case "PreserveSig" preserveSig = namedArg.Value.DecodeValue(Of Boolean)(SpecialType.System_Boolean) Case "CallingConvention" callingConvention = namedArg.Value.DecodeValue(Of System.Runtime.InteropServices.CallingConvention)(SpecialType.System_Enum) Case "BestFitMapping" bestFitMapping = namedArg.Value.DecodeValue(Of Boolean)(SpecialType.System_Boolean) Case "ThrowOnUnmappableChar" throwOnUnmappable = namedArg.Value.DecodeValue(Of Boolean)(SpecialType.System_Boolean) End Select position = position + 1 Next Dim data = arguments.GetOrCreateData(Of MethodWellKnownAttributeData)() data.SetDllImport( arguments.Index, moduleName, importName, DllImportData.MakeFlags(exactSpelling, charSet, setLastError, callingConvention, bestFitMapping, throwOnUnmappable), preserveSig) ElseIf attrData.IsTargetAttribute(Me, AttributeDescription.SpecialNameAttribute) Then arguments.GetOrCreateData(Of MethodWellKnownAttributeData)().HasSpecialNameAttribute = True ElseIf attrData.IsTargetAttribute(Me, AttributeDescription.ExcludeFromCodeCoverageAttribute) Then arguments.GetOrCreateData(Of MethodWellKnownAttributeData)().HasExcludeFromCodeCoverageAttribute = True ElseIf attrData.IsTargetAttribute(Me, AttributeDescription.SuppressUnmanagedCodeSecurityAttribute) Then arguments.GetOrCreateData(Of MethodWellKnownAttributeData)().HasSuppressUnmanagedCodeSecurityAttribute = True ElseIf attrData.IsSecurityAttribute(Me.DeclaringCompilation) Then attrData.DecodeSecurityAttribute(Of MethodWellKnownAttributeData)(Me, Me.DeclaringCompilation, arguments) ElseIf attrData.IsTargetAttribute(Me, AttributeDescription.STAThreadAttribute) Then arguments.GetOrCreateData(Of MethodWellKnownAttributeData)().HasSTAThreadAttribute = True ElseIf attrData.IsTargetAttribute(Me, AttributeDescription.MTAThreadAttribute) Then arguments.GetOrCreateData(Of MethodWellKnownAttributeData)().HasMTAThreadAttribute = True ElseIf attrData.IsTargetAttribute(Me, AttributeDescription.ConditionalAttribute) Then If Not Me.IsSub Then ' BC41007: Attribute 'Conditional' is only valid on 'Sub' declarations. diagnostics.Add(ERRID.WRN_ConditionalNotValidOnFunction, Me.Locations(0)) End If ElseIf VerifyObsoleteAttributeAppliedToMethod(arguments, AttributeDescription.ObsoleteAttribute) Then ElseIf VerifyObsoleteAttributeAppliedToMethod(arguments, AttributeDescription.DeprecatedAttribute) Then ElseIf arguments.Attribute.IsTargetAttribute(Me, AttributeDescription.ModuleInitializerAttribute) Then diagnostics.Add(ERRID.WRN_AttributeNotSupportedInVB, arguments.AttributeSyntaxOpt.Location, AttributeDescription.ModuleInitializerAttribute.FullName) Else Dim methodImpl As MethodSymbol = If(Me.IsPartial, PartialImplementationPart, Me) If methodImpl IsNot Nothing AndAlso (methodImpl.IsAsync OrElse methodImpl.IsIterator) AndAlso Not methodImpl.ContainingType.IsInterfaceType() Then If attrData.IsTargetAttribute(Me, AttributeDescription.SecurityCriticalAttribute) Then Binder.ReportDiagnostic(diagnostics, arguments.AttributeSyntaxOpt.GetLocation(), ERRID.ERR_SecurityCriticalAsync, "SecurityCritical") Return ElseIf attrData.IsTargetAttribute(Me, AttributeDescription.SecuritySafeCriticalAttribute) Then Binder.ReportDiagnostic(diagnostics, arguments.AttributeSyntaxOpt.GetLocation(), ERRID.ERR_SecurityCriticalAsync, "SecuritySafeCritical") Return End If End If End If End Sub Private Function VerifyObsoleteAttributeAppliedToMethod( ByRef arguments As DecodeWellKnownAttributeArguments(Of AttributeSyntax, VisualBasicAttributeData, AttributeLocation), description As AttributeDescription ) As Boolean If arguments.Attribute.IsTargetAttribute(Me, description) Then ' Obsolete Attribute is not allowed on event accessors. If Me.IsAccessor() AndAlso Me.AssociatedSymbol.Kind = SymbolKind.Event Then DirectCast(arguments.Diagnostics, BindingDiagnosticBag).Add(ERRID.ERR_ObsoleteInvalidOnEventMember, Me.Locations(0), description.FullName) End If Return True End If Return False End Function Private Sub DecodeWellKnownAttributeAppliedToReturnValue(ByRef arguments As DecodeWellKnownAttributeArguments(Of AttributeSyntax, VisualBasicAttributeData, AttributeLocation)) ' Decode well-known attributes applied to return value Dim attrData = arguments.Attribute Debug.Assert(Not attrData.HasErrors) If attrData.IsTargetAttribute(Me, AttributeDescription.MarshalAsAttribute) Then MarshalAsAttributeDecoder(Of CommonReturnTypeWellKnownAttributeData, AttributeSyntax, VisualBasicAttributeData, AttributeLocation).Decode(arguments, AttributeTargets.ReturnValue, MessageProvider.Instance) End If End Sub Private Function IsDllImportAttributeAllowed(syntax As AttributeSyntax, diagnostics As BindingDiagnosticBag) As Boolean Select Case Me.MethodKind Case MethodKind.DeclareMethod diagnostics.Add(ERRID.ERR_DllImportNotLegalOnDeclare, syntax.Name.GetLocation()) Return False Case MethodKind.PropertyGet, MethodKind.PropertySet diagnostics.Add(ERRID.ERR_DllImportNotLegalOnGetOrSet, syntax.Name.GetLocation()) Return False Case MethodKind.EventAdd, MethodKind.EventRaise, MethodKind.EventRemove diagnostics.Add(ERRID.ERR_DllImportNotLegalOnEventMethod, syntax.Name.GetLocation()) Return False End Select If Me.ContainingType IsNot Nothing AndAlso Me.ContainingType.IsInterface Then diagnostics.Add(ERRID.ERR_DllImportOnInterfaceMethod, syntax.Name.GetLocation()) Return False End If If Me.IsGenericMethod OrElse (Me.ContainingType IsNot Nothing AndAlso Me.ContainingType.IsGenericType) Then diagnostics.Add(ERRID.ERR_DllImportOnGenericSubOrFunction, syntax.Name.GetLocation()) Return False End If If Not Me.IsShared Then diagnostics.Add(ERRID.ERR_DllImportOnInstanceMethod, syntax.Name.GetLocation()) Return False End If Dim methodImpl As SourceMethodSymbol = TryCast(If(Me.IsPartial, PartialImplementationPart, Me), SourceMethodSymbol) If methodImpl IsNot Nothing AndAlso (methodImpl.IsAsync OrElse methodImpl.IsIterator) AndAlso Not methodImpl.ContainingType.IsInterfaceType() Then Dim location As Location = methodImpl.NonMergedLocation If location IsNot Nothing Then Binder.ReportDiagnostic(diagnostics, location, ERRID.ERR_DllImportOnResumableMethod) Return False End If End If If Not HasEmptyBody Then diagnostics.Add(ERRID.ERR_DllImportOnNonEmptySubOrFunction, syntax.Name.GetLocation()) Return False End If Return True End Function Friend Overrides Sub PostDecodeWellKnownAttributes( boundAttributes As ImmutableArray(Of VisualBasicAttributeData), allAttributeSyntaxNodes As ImmutableArray(Of AttributeSyntax), diagnostics As BindingDiagnosticBag, symbolPart As AttributeLocation, decodedData As WellKnownAttributeData) Debug.Assert(Not boundAttributes.IsDefault) Debug.Assert(Not allAttributeSyntaxNodes.IsDefault) Debug.Assert(boundAttributes.Length = allAttributeSyntaxNodes.Length) Debug.Assert(symbolPart = AttributeLocation.Return OrElse symbolPart = AttributeLocation.None) If symbolPart <> AttributeLocation.Return Then Dim methodData = DirectCast(decodedData, MethodWellKnownAttributeData) If methodData IsNot Nothing AndAlso methodData.HasSTAThreadAttribute AndAlso methodData.HasMTAThreadAttribute Then Debug.Assert(Me.NonMergedLocation IsNot Nothing) ' BC31512: 'System.STAThreadAttribute' and 'System.MTAThreadAttribute' cannot both be applied to the same method. diagnostics.Add(ERRID.ERR_STAThreadAndMTAThread0, Me.NonMergedLocation) End If End If MyBase.PostDecodeWellKnownAttributes(boundAttributes, allAttributeSyntaxNodes, diagnostics, symbolPart, decodedData) End Sub Public Overrides ReadOnly Property IsExtensionMethod As Boolean Get Dim data As MethodEarlyWellKnownAttributeData = Me.GetEarlyDecodedWellKnownAttributeData() Return data IsNot Nothing AndAlso data.IsExtensionMethod End Get End Property ' Force derived types to override this. Friend MustOverride Overrides ReadOnly Property MayBeReducibleExtensionMethod As Boolean Public Overrides ReadOnly Property IsExternalMethod As Boolean Get ' External methods are: ' 1) Declare Subs and Declare Functions: IsExternalMethod overridden in SourceDeclareMethodSymbol ' 2) methods marked by DllImportAttribute ' 3) methods marked by MethodImplAttribute: Runtime and InternalCall methods should not have a body emitted Debug.Assert(MethodKind <> MethodKind.DeclareMethod) Dim data As MethodWellKnownAttributeData = GetDecodedWellKnownAttributeData() If data Is Nothing Then Return False End If ' p/invoke If data.DllImportPlatformInvokeData IsNot Nothing Then Return True End If ' internal call If (data.MethodImplAttributes And Reflection.MethodImplAttributes.InternalCall) <> 0 Then Return True End If ' runtime If (data.MethodImplAttributes And Reflection.MethodImplAttributes.CodeTypeMask) = Reflection.MethodImplAttributes.Runtime Then Return True End If Return False End Get End Property Public Overrides Function GetDllImportData() As DllImportData Dim attributeData = GetDecodedWellKnownAttributeData() Return If(attributeData IsNot Nothing, attributeData.DllImportPlatformInvokeData, Nothing) End Function Friend NotOverridable Overrides ReadOnly Property ReturnTypeMarshallingInformation As MarshalPseudoCustomAttributeData Get Dim attributeData = GetDecodedReturnTypeWellKnownAttributeData() Return If(attributeData IsNot Nothing, attributeData.MarshallingInformation, Nothing) End Get End Property Friend Overrides ReadOnly Property ImplementationAttributes As Reflection.MethodImplAttributes Get ' Methods of ComImport types are marked as Runtime implemented and InternalCall If ContainingType.IsComImport AndAlso Not ContainingType.IsInterface Then Return System.Reflection.MethodImplAttributes.Runtime Or Reflection.MethodImplAttributes.InternalCall End If Dim attributeData = GetDecodedWellKnownAttributeData() Return If(attributeData IsNot Nothing, attributeData.MethodImplAttributes, Nothing) End Get End Property Friend NotOverridable Overrides ReadOnly Property HasDeclarativeSecurity As Boolean Get Dim attributeData = GetDecodedWellKnownAttributeData() Return attributeData IsNot Nothing AndAlso attributeData.HasDeclarativeSecurity End Get End Property Friend NotOverridable Overrides Function GetSecurityInformation() As IEnumerable(Of SecurityAttribute) Dim attributesBag As CustomAttributesBag(Of VisualBasicAttributeData) = Me.GetAttributesBag() Dim wellKnownAttributeData = DirectCast(attributesBag.DecodedWellKnownAttributeData, MethodWellKnownAttributeData) If wellKnownAttributeData IsNot Nothing Then Dim securityData As SecurityWellKnownAttributeData = wellKnownAttributeData.SecurityInformation If securityData IsNot Nothing Then Return securityData.GetSecurityAttributes(attributesBag.Attributes) End If End If Return SpecializedCollections.EmptyEnumerable(Of SecurityAttribute)() End Function Friend NotOverridable Overrides ReadOnly Property IsDirectlyExcludedFromCodeCoverage As Boolean Get Dim data = GetDecodedWellKnownAttributeData() Return data IsNot Nothing AndAlso data.HasExcludeFromCodeCoverageAttribute End Get End Property Friend Overrides ReadOnly Property HasRuntimeSpecialName As Boolean Get Return MyBase.HasRuntimeSpecialName OrElse IsVtableGapInterfaceMethod() End Get End Property Private Function IsVtableGapInterfaceMethod() As Boolean Return Me.ContainingType.IsInterface AndAlso ModuleExtensions.GetVTableGapSize(Me.MetadataName) > 0 End Function Friend Overrides ReadOnly Property HasSpecialName As Boolean Get Select Case Me.MethodKind Case MethodKind.Constructor, MethodKind.SharedConstructor, MethodKind.PropertyGet, MethodKind.PropertySet, MethodKind.EventAdd, MethodKind.EventRemove, MethodKind.EventRaise, MethodKind.Conversion, MethodKind.UserDefinedOperator Return True End Select If IsVtableGapInterfaceMethod() Then Return True End If Dim attributeData = GetDecodedWellKnownAttributeData() Return attributeData IsNot Nothing AndAlso attributeData.HasSpecialNameAttribute End Get End Property Private ReadOnly Property HasSTAThreadOrMTAThreadAttribute As Boolean Get ' This property is only accessed during Emit, we must have already bound the attributes. Debug.Assert(m_lazyCustomAttributesBag IsNot Nothing AndAlso m_lazyCustomAttributesBag.IsSealed) Dim decodedData As MethodWellKnownAttributeData = Me.GetDecodedWellKnownAttributeData() Return decodedData IsNot Nothing AndAlso (decodedData.HasSTAThreadAttribute OrElse decodedData.HasMTAThreadAttribute) End Get End Property Friend Overrides ReadOnly Property ObsoleteAttributeData As ObsoleteAttributeData Get ' If there are no attributes then this symbol is not Obsolete. Dim container = TryCast(Me.m_containingType, SourceMemberContainerTypeSymbol) If container Is Nothing OrElse Not container.AnyMemberHasAttributes Then Return Nothing End If Dim lazyCustomAttributesBag = Me.m_lazyCustomAttributesBag If (lazyCustomAttributesBag IsNot Nothing AndAlso lazyCustomAttributesBag.IsEarlyDecodedWellKnownAttributeDataComputed) Then Dim data = DirectCast(m_lazyCustomAttributesBag.EarlyDecodedWellKnownAttributeData, MethodEarlyWellKnownAttributeData) Return If(data IsNot Nothing, data.ObsoleteAttributeData, Nothing) End If Dim reference = Me.DeclaringSyntaxReferences If (reference.IsEmpty) Then ' no references -> no attributes Return Nothing End If Return ObsoleteAttributeData.Uninitialized End Get End Property #End Region Public MustOverride Overrides ReadOnly Property ReturnType As TypeSymbol Public MustOverride Overrides ReadOnly Property Parameters As ImmutableArray(Of ParameterSymbol) Friend MustOverride Overrides ReadOnly Property OverriddenMembers As OverriddenMembersResult(Of MethodSymbol) End Class Friend MustInherit Class SourceNonPropertyAccessorMethodSymbol Inherits SourceMethodSymbol ' Parameters. Private _lazyParameters As ImmutableArray(Of ParameterSymbol) ' Return type. Void for a Sub. Private _lazyReturnType As TypeSymbol ' The overridden or hidden methods. Private _lazyOverriddenMethods As OverriddenMembersResult(Of MethodSymbol) Protected Sub New(containingType As NamedTypeSymbol, flags As SourceMemberFlags, syntaxRef As SyntaxReference, Optional locations As ImmutableArray(Of Location) = Nothing) MyBase.New(containingType, flags, syntaxRef, locations) End Sub Friend NotOverridable Overrides ReadOnly Property ParameterCount As Integer Get If Not Me._lazyParameters.IsDefault Then Return Me._lazyParameters.Length End If Dim decl = Me.DeclarationSyntax Dim paramListOpt As ParameterListSyntax Select Case decl.Kind Case SyntaxKind.SubNewStatement Dim methodStatement = DirectCast(decl, SubNewStatementSyntax) paramListOpt = methodStatement.ParameterList Case SyntaxKind.SubStatement, SyntaxKind.FunctionStatement Dim methodStatement = DirectCast(decl, MethodStatementSyntax) paramListOpt = methodStatement.ParameterList Case Else Return MyBase.ParameterCount End Select Return If(paramListOpt Is Nothing, 0, paramListOpt.Parameters.Count) End Get End Property Public NotOverridable Overrides ReadOnly Property Parameters As ImmutableArray(Of ParameterSymbol) Get EnsureSignature() Return _lazyParameters End Get End Property Private Sub EnsureSignature() If _lazyParameters.IsDefault Then Dim diagBag = BindingDiagnosticBag.GetInstance() Dim sourceModule = ContainingSourceModule Dim params As ImmutableArray(Of ParameterSymbol) = GetParameters(sourceModule, diagBag) Dim errorLocation As SyntaxNodeOrToken = Nothing Dim retType As TypeSymbol = GetReturnType(sourceModule, errorLocation, diagBag) Debug.Assert(Me.IsAccessor OrElse retType.GetArity() = 0 OrElse Not (errorLocation.IsKind(SyntaxKind.None))) ' if we could have constraint errors, the location better exist. ' For an overriding method, we need to copy custom modifiers from the method we override. Dim overriddenMembers As OverriddenMembersResult(Of MethodSymbol) ' Do not support custom modifiers for properties at the moment. If Not Me.IsOverrides OrElse Not OverrideHidingHelper.CanOverrideOrHide(Me) Then overriddenMembers = OverriddenMembersResult(Of MethodSymbol).Empty Else ' Since we cannot expose parameters and return type to the outside world yet, ' let's create a fake symbol to use for overriding resolution Dim fakeTypeParameters As ImmutableArray(Of TypeParameterSymbol) Dim replaceMethodTypeParametersWithFakeTypeParameters As TypeSubstitution If Me.Arity > 0 Then fakeTypeParameters = IndexedTypeParameterSymbol.Take(Me.Arity) replaceMethodTypeParametersWithFakeTypeParameters = TypeSubstitution.Create(Me, Me.TypeParameters, StaticCast(Of TypeSymbol).From(fakeTypeParameters)) Else fakeTypeParameters = ImmutableArray(Of TypeParameterSymbol).Empty replaceMethodTypeParametersWithFakeTypeParameters = Nothing End If Dim fakeParamsBuilder = ArrayBuilder(Of ParameterSymbol).GetInstance(params.Length) For Each param As ParameterSymbol In params fakeParamsBuilder.Add(New SignatureOnlyParameterSymbol( param.Type.InternalSubstituteTypeParameters(replaceMethodTypeParametersWithFakeTypeParameters).AsTypeSymbolOnly(), ImmutableArray(Of CustomModifier).Empty, ImmutableArray(Of CustomModifier).Empty, defaultConstantValue:=Nothing, isParamArray:=False, isByRef:=param.IsByRef, isOut:=False, isOptional:=param.IsOptional)) Next overriddenMembers = OverrideHidingHelper(Of MethodSymbol). MakeOverriddenMembers(New SignatureOnlyMethodSymbol(Me.Name, m_containingType, Me.MethodKind, Me.CallingConvention, fakeTypeParameters, fakeParamsBuilder.ToImmutableAndFree(), returnsByRef:=False, returnType:=retType.InternalSubstituteTypeParameters(replaceMethodTypeParametersWithFakeTypeParameters).AsTypeSymbolOnly(), returnTypeCustomModifiers:=ImmutableArray(Of CustomModifier).Empty, refCustomModifiers:=ImmutableArray(Of CustomModifier).Empty, explicitInterfaceImplementations:=ImmutableArray(Of MethodSymbol).Empty, isOverrides:=True)) End If Debug.Assert(IsDefinition) Dim overridden = overriddenMembers.OverriddenMember If overridden IsNot Nothing Then CustomModifierUtils.CopyMethodCustomModifiers(overridden, Me.TypeArguments, retType, params) End If ' Unlike MethodSymbol, in SourceMethodSymbol we cache the result of MakeOverriddenOfHiddenMembers, because we use ' it heavily while validating methods and emitting. Interlocked.CompareExchange(_lazyOverriddenMethods, overriddenMembers, Nothing) Interlocked.CompareExchange(_lazyReturnType, retType, Nothing) retType = _lazyReturnType For Each param In params ' TODO: The check for Locations is to rule out cases such as implicit parameters ' from property accessors but it allows explicit accessor parameters. Is that correct? If param.Locations.Length > 0 Then ' Note: Errors are reported on the parameter name. Ideally, we should ' match Dev10 and report errors on the parameter type syntax instead. param.Type.CheckAllConstraints(param.Locations(0), diagBag, template:=New CompoundUseSiteInfo(Of AssemblySymbol)(diagBag, sourceModule.ContainingAssembly)) End If Next If Not errorLocation.IsKind(SyntaxKind.None) Then Dim diagnosticsBuilder = ArrayBuilder(Of TypeParameterDiagnosticInfo).GetInstance() Dim useSiteDiagnosticsBuilder As ArrayBuilder(Of TypeParameterDiagnosticInfo) = Nothing retType.CheckAllConstraints(diagnosticsBuilder, useSiteDiagnosticsBuilder, template:=New CompoundUseSiteInfo(Of AssemblySymbol)(diagBag, sourceModule.ContainingAssembly)) If useSiteDiagnosticsBuilder IsNot Nothing Then diagnosticsBuilder.AddRange(useSiteDiagnosticsBuilder) End If For Each diag In diagnosticsBuilder diagBag.Add(diag.UseSiteInfo, errorLocation.GetLocation()) Next diagnosticsBuilder.Free() End If sourceModule.AtomicStoreArrayAndDiagnostics( _lazyParameters, params, diagBag) diagBag.Free() End If End Sub Private Function CreateBinderForMethodDeclaration(sourceModule As SourceModuleSymbol) As Binder Dim binder As Binder = BinderBuilder.CreateBinderForMethodDeclaration(sourceModule, Me.SyntaxTree, Me) ' Constraint checking for parameter and return types must be delayed ' until the parameter and return type fields have been set since ' evaluating constraints may require comparing this method signature ' (to find the implemented method for instance). Return New LocationSpecificBinder(BindingLocation.MethodSignature, Me, binder) End Function Protected Overridable Function GetParameters(sourceModule As SourceModuleSymbol, diagBag As BindingDiagnosticBag) As ImmutableArray(Of ParameterSymbol) Dim decl = Me.DeclarationSyntax Dim binder As Binder = CreateBinderForMethodDeclaration(sourceModule) Dim paramList As ParameterListSyntax Select Case decl.Kind Case SyntaxKind.SubNewStatement paramList = DirectCast(decl, SubNewStatementSyntax).ParameterList Case SyntaxKind.OperatorStatement paramList = DirectCast(decl, OperatorStatementSyntax).ParameterList Case SyntaxKind.SubStatement, SyntaxKind.FunctionStatement paramList = DirectCast(decl, MethodStatementSyntax).ParameterList Case SyntaxKind.DeclareSubStatement, SyntaxKind.DeclareFunctionStatement paramList = DirectCast(decl, DeclareStatementSyntax).ParameterList Case Else Throw ExceptionUtilities.UnexpectedValue(decl.Kind) End Select Return binder.DecodeParameterList(Me, False, m_flags, paramList, diagBag) End Function Public NotOverridable Overrides ReadOnly Property ReturnType As TypeSymbol Get EnsureSignature() Return _lazyReturnType End Get End Property Private Shared Function GetNameToken(methodStatement As MethodBaseSyntax) As SyntaxToken Select Case methodStatement.Kind Case SyntaxKind.OperatorStatement Return DirectCast(methodStatement, OperatorStatementSyntax).OperatorToken Case SyntaxKind.SubStatement, SyntaxKind.FunctionStatement Return DirectCast(methodStatement, MethodStatementSyntax).Identifier Case SyntaxKind.DeclareSubStatement, SyntaxKind.DeclareFunctionStatement Return DirectCast(methodStatement, DeclareStatementSyntax).Identifier Case Else Throw ExceptionUtilities.UnexpectedValue(methodStatement.Kind) End Select End Function Private Function GetReturnType(sourceModule As SourceModuleSymbol, ByRef errorLocation As SyntaxNodeOrToken, diagBag As BindingDiagnosticBag) As TypeSymbol Dim binder As Binder = CreateBinderForMethodDeclaration(sourceModule) Select Case MethodKind Case MethodKind.Constructor, MethodKind.SharedConstructor, MethodKind.EventRemove, MethodKind.EventRaise Debug.Assert(Me.IsSub) Return binder.GetSpecialType(SpecialType.System_Void, Syntax, diagBag) Case MethodKind.EventAdd Dim isWindowsRuntimeEvent As Boolean = DirectCast(Me.AssociatedSymbol, EventSymbol).IsWindowsRuntimeEvent Return If(isWindowsRuntimeEvent, binder.GetWellKnownType(WellKnownType.System_Runtime_InteropServices_WindowsRuntime_EventRegistrationToken, Syntax, diagBag), binder.GetSpecialType(SpecialType.System_Void, Syntax, diagBag)) Case MethodKind.PropertyGet, MethodKind.PropertySet Throw ExceptionUtilities.Unreachable Case Else Dim methodStatement As MethodBaseSyntax = Me.DeclarationSyntax Dim retType As TypeSymbol Select Case methodStatement.Kind Case SyntaxKind.SubStatement, SyntaxKind.DeclareSubStatement Debug.Assert(Me.IsSub) binder.DisallowTypeCharacter(GetNameToken(methodStatement), diagBag, ERRID.ERR_TypeCharOnSub) retType = binder.GetSpecialType(SpecialType.System_Void, Syntax, diagBag) errorLocation = methodStatement.DeclarationKeyword Case Else Dim getErrorInfo As Func(Of DiagnosticInfo) = Nothing If binder.OptionStrict = OptionStrict.On Then getErrorInfo = ErrorFactory.GetErrorInfo_ERR_StrictDisallowsImplicitProc ElseIf binder.OptionStrict = OptionStrict.Custom Then If Me.MethodKind = MethodKind.UserDefinedOperator Then getErrorInfo = ErrorFactory.GetErrorInfo_WRN_ObjectAssumed1_WRN_MissingAsClauseinOperator Else getErrorInfo = ErrorFactory.GetErrorInfo_WRN_ObjectAssumed1_WRN_MissingAsClauseinFunction End If End If Dim asClause As AsClauseSyntax = methodStatement.AsClauseInternal retType = binder.DecodeIdentifierType(GetNameToken(methodStatement), asClause, getErrorInfo, diagBag) If asClause IsNot Nothing Then errorLocation = asClause.Type Else errorLocation = methodStatement.DeclarationKeyword End If End Select If Not retType.IsErrorType() Then AccessCheck.VerifyAccessExposureForMemberType(Me, errorLocation, retType, diagBag) Dim restrictedType As TypeSymbol = Nothing If retType.IsRestrictedArrayType(restrictedType) Then binder.ReportDiagnostic(diagBag, errorLocation, ERRID.ERR_RestrictedType1, restrictedType) End If If Not (Me.IsAsync AndAlso Me.IsIterator) Then If Me.IsSub Then If Me.IsIterator Then binder.ReportDiagnostic(diagBag, errorLocation, ERRID.ERR_BadIteratorReturn) End If Else If Me.IsAsync Then Dim compilation = Me.DeclaringCompilation If Not retType.OriginalDefinition.Equals(compilation.GetWellKnownType(WellKnownType.System_Threading_Tasks_Task_T)) AndAlso Not retType.Equals(compilation.GetWellKnownType(WellKnownType.System_Threading_Tasks_Task)) Then binder.ReportDiagnostic(diagBag, errorLocation, ERRID.ERR_BadAsyncReturn) End If End If If Me.IsIterator Then Dim originalRetTypeDef = retType.OriginalDefinition If originalRetTypeDef.SpecialType <> SpecialType.System_Collections_Generic_IEnumerable_T AndAlso originalRetTypeDef.SpecialType <> SpecialType.System_Collections_Generic_IEnumerator_T AndAlso retType.SpecialType <> SpecialType.System_Collections_IEnumerable AndAlso retType.SpecialType <> SpecialType.System_Collections_IEnumerator Then binder.ReportDiagnostic(diagBag, errorLocation, ERRID.ERR_BadIteratorReturn) End If End If End If End If End If Return retType End Select End Function Friend NotOverridable Overrides ReadOnly Property OverriddenMembers As OverriddenMembersResult(Of MethodSymbol) Get EnsureSignature() Return Me._lazyOverriddenMethods End Get End Property End Class End Namespace
-1
dotnet/roslyn
55,428
Test adding nested namespaces
Fixes https://github.com/dotnet/roslyn/issues/54939 The "workaround" that's already implemented is actually the correct behavior.
tmat
2021-08-05T01:19:03Z
2021-08-11T18:38:54Z
bc874ebc5111a2a33221409f895953b1536f6612
1cbbd423e17b186a8f1de89febb4db9a386d180d
Test adding nested namespaces. Fixes https://github.com/dotnet/roslyn/issues/54939 The "workaround" that's already implemented is actually the correct behavior.
./src/EditorFeatures/Core/ExternalAccess/VSTypeScript/Api/VSTypeScriptDebugLocationInfoWrapper.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Microsoft.CodeAnalysis.Debugging; namespace Microsoft.CodeAnalysis.ExternalAccess.VSTypeScript.Api { internal readonly struct VSTypeScriptDebugLocationInfoWrapper { internal readonly DebugLocationInfo UnderlyingObject; public VSTypeScriptDebugLocationInfoWrapper(string name, int lineOffset) => UnderlyingObject = new DebugLocationInfo(name, lineOffset); public readonly string Name => UnderlyingObject.Name; public readonly int LineOffset => UnderlyingObject.LineOffset; internal bool IsDefault => UnderlyingObject.IsDefault; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Microsoft.CodeAnalysis.Debugging; namespace Microsoft.CodeAnalysis.ExternalAccess.VSTypeScript.Api { internal readonly struct VSTypeScriptDebugLocationInfoWrapper { internal readonly DebugLocationInfo UnderlyingObject; public VSTypeScriptDebugLocationInfoWrapper(string name, int lineOffset) => UnderlyingObject = new DebugLocationInfo(name, lineOffset); public readonly string Name => UnderlyingObject.Name; public readonly int LineOffset => UnderlyingObject.LineOffset; internal bool IsDefault => UnderlyingObject.IsDefault; } }
-1
dotnet/roslyn
55,428
Test adding nested namespaces
Fixes https://github.com/dotnet/roslyn/issues/54939 The "workaround" that's already implemented is actually the correct behavior.
tmat
2021-08-05T01:19:03Z
2021-08-11T18:38:54Z
bc874ebc5111a2a33221409f895953b1536f6612
1cbbd423e17b186a8f1de89febb4db9a386d180d
Test adding nested namespaces. Fixes https://github.com/dotnet/roslyn/issues/54939 The "workaround" that's already implemented is actually the correct behavior.
./src/Workspaces/Core/Portable/Workspace/Solution/IDocumentTextDifferencingService.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Immutable; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis { internal interface IDocumentTextDifferencingService : IWorkspaceService { /// <summary> /// Computes the text changes between two documents. /// </summary> /// <param name="oldDocument">The old version of the document.</param> /// <param name="newDocument">The new version of the document.</param> /// <param name="cancellationToken">The cancellation token.</param> /// <returns>An array of changes.</returns> Task<ImmutableArray<TextChange>> GetTextChangesAsync(Document oldDocument, Document newDocument, CancellationToken cancellationToken); /// <summary> /// Computes the text changes between two documents. /// </summary> /// <param name="oldDocument">The old version of the document.</param> /// <param name="newDocument">The new version of the document.</param> /// <param name="preferredDifferenceType">The type of differencing to perform. Not supported by all text differencing services.</param> /// <param name="cancellationToken">The cancellation token.</param> /// <returns>An array of changes.</returns> Task<ImmutableArray<TextChange>> GetTextChangesAsync(Document oldDocument, Document newDocument, TextDifferenceTypes preferredDifferenceType, CancellationToken cancellationToken); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Immutable; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis { internal interface IDocumentTextDifferencingService : IWorkspaceService { /// <summary> /// Computes the text changes between two documents. /// </summary> /// <param name="oldDocument">The old version of the document.</param> /// <param name="newDocument">The new version of the document.</param> /// <param name="cancellationToken">The cancellation token.</param> /// <returns>An array of changes.</returns> Task<ImmutableArray<TextChange>> GetTextChangesAsync(Document oldDocument, Document newDocument, CancellationToken cancellationToken); /// <summary> /// Computes the text changes between two documents. /// </summary> /// <param name="oldDocument">The old version of the document.</param> /// <param name="newDocument">The new version of the document.</param> /// <param name="preferredDifferenceType">The type of differencing to perform. Not supported by all text differencing services.</param> /// <param name="cancellationToken">The cancellation token.</param> /// <returns>An array of changes.</returns> Task<ImmutableArray<TextChange>> GetTextChangesAsync(Document oldDocument, Document newDocument, TextDifferenceTypes preferredDifferenceType, CancellationToken cancellationToken); } }
-1
dotnet/roslyn
55,428
Test adding nested namespaces
Fixes https://github.com/dotnet/roslyn/issues/54939 The "workaround" that's already implemented is actually the correct behavior.
tmat
2021-08-05T01:19:03Z
2021-08-11T18:38:54Z
bc874ebc5111a2a33221409f895953b1536f6612
1cbbd423e17b186a8f1de89febb4db9a386d180d
Test adding nested namespaces. Fixes https://github.com/dotnet/roslyn/issues/54939 The "workaround" that's already implemented is actually the correct behavior.
./docs/compilers/Design/Closure Conversion.md
Closure Conversion in C# ======================== This document describes the how the C# compiler turns closures (anonymous and local functions) into top-level functions (methods). If you aren't familiar with closure conversion, the introduction contains a walkthrough describing the transformations. Otherwise, you can skip to the Internals section to see how the actual transformations are done in Roslyn. # Introduction In the simplest case, this is trivial -- all closures are simply given new, unmentionable names and are lifted to the top level as static methods. The complexity comes when a closure captures a variable from its surrounding scope. At that point, we must not only move the closure to a method, we also have to create an "environment" to hold its captured variables and somehow deliver that environment into the context of the rewritten method. There are two possible strategies that are both employed in different situations in the compiler. The first strategy is to pass the environment as an extra parameter to all method calls to the closure. For example, ```csharp void M() { int x = 0; int Local() => x + 1; } ``` becomes ```csharp void M() { var env = new Environment(); env.x = 0; <>__Local(env); } static int <>__Local(Environment env) { return env.x + 1; } struct Environment { int x; } ``` Instead of referring to local variables, the rewritten closure now references fields on the environment. A `struct` environment is used to prevent extra allocations, since `struct`s are normally allocated on the stack. However, the astute reader may notice a problem with this conversion -- `struct`s are always copied when passed as arguments to a function call! This means that writes to the environment field will not always propagate back to the local variable in the method `M`. To work around this flaw, all Environment variables are passed as `ref` arguments to the rewritten closures. The second strategy for rewriting closures is necessary when the closure interacts with external code. Consider the following program: ```csharp void M(IEnumerable<int> e) { int x = 0; var positive = e.Where(n => n > 0); ... } ``` In this case we're passing a closure to the `IEnumerable<int>.Where` function, which is expecting a delegate of type `Func<int, bool>`. Note that that delegate type is immutable -- it is defined in external code and cannot be changed. Therefore, rewriting external callsites to take an extra `Environment` argument is impossible. We have to choose a different strategy for acquiring the environment. What we do is use a `class` Environment for cases like this. With a `class` Environment, the previous environment can be rewritten as follows: ```csharp void M(IEnumerable<int> e) { var env = new Environment(); env.x = 0; var positive = e.Where(env.<>__Local); } class Environment { int x; bool <>__Local(int n) => n > 0; } ``` Since the local variables are now fields in a class instance we can keep the same delegate signature and rely on field access to read and write the free variables. This covers the transformations C# performs at a high level. The following section covers how these transformations are performed in detail. # Internals There are two phases at the top level of closure conversion. The first phase, Analysis, is responsible for building an AnalysisResult data structure which contains all information necessary to rewrite all closures. The second phase, Rewriting, actually performs the aforementioned rewriting by replacing and adding BoundNodes to the Bound Tree. The most important contract between these two phases is that the Analysis phase performs no modifications to the Bound Tree and the Rewriting phase performs no computation and contains no logic aside from a simple mechanical modification of the Bound Tree based on the AnalysisResult. ## Analysis In this phase we build an AnalysisResult, which is a tree structure that exactly represents the state mapping from the original program to the closure-converted form. For example, the following program ```csharp void M() { int x = 0; int Local() => x + 1; { int y = 0; int z = 0; int Local2() => Local() + y; z++; Local2(); } Local(); } ``` Would produce a tree similar to ``` +-------------------------------------+ |Captured: Closures: | |int x int Local() | |int Local() | | | | +--------------------------------+ | | | Captured: Closures: | | | | int y int Local2() | | | | | | | +--------------------------------+ | +-------------------------------------+ ``` To create this AnalysisResult there are multiple passes. The first pass gathers information by constructing a naive tree of scopes, closures, and captured variables. The result is a tree of nested scopes, where each scope lists the captured variables declared in the scope and the closures in that scope. The first pass must first gather information since most rewriting decisions, like what Environment type to use for the closures or what the rewritten closure signature will be, are dependent on context from the entire method. Information about captured variables are stored on instances of the `CapturedVariable` class, which holds information about the Symbol that was captured and rewriting information like the `SynthesizedLocal` that will replace the variable post-rewriting. Similarly, closures will be stored in instances of the `Closure` class, which contain both the original Symbol and the synthesized type or method created for the closure. All of these classes are mutable since it's expected that later passes will fill in more rewriting information using the structure gathered from the earlier passes. For instance, in the previous example we need to walk the tree to generate an Environment for the closures `Closure`, resulting in something like the following: ``` Closure ------- Name: Local Generated Sig: int <>_Local(ref <>_Env1) Environment: - Captures: 'int x' - Name: <>_Env1 - Type: Struct Name: Local2 Generated Sig: int <>_Local(ref <>_Env2, ref <>_Env1) Environment: - Captures: 'int y', 'ref <>_Env1' - Name: <>_Env2 - Type: Struct ``` This result would be generated by each piece filling in required info: first filling in all the capture lists, then deciding the Environment type based on the capture list, then generating the end signature based on the environment type and final capture list. Some further details of analysis calculations can be found below: **TODO** _Add details for each analysis phase as implementation is fleshed out_ * Deciding what environment type is necessary for each closure. An environment can be a struct unless one of the following things is true: 1. The closure is converted to delegate. 2. The closure captures a variable which is captured by a closure that cannot have a `struct` Environment. 3. A reference to the closure is captured by a closure that cannot have a `struct` Environment. * Creating `SynthesizedLocal`s for hoisted captured variables and captured Environment references * Assigning rewritten names, signatures, and type parameters to each closure ## Optimization The final passes are optimization passes. They attempt to simplify the tree by removing intermediate scopes with no captured variables and otherwise correcting the tree to create the most efficient rewritten form. Optimization opportunities could include running escape analysis to determine if capture hoisting could be done via copy or done in a narrower scope. ## Rewriting The rewriting phase simply walks the bound tree and, at each new scope, checks to see if the AnalysisResult contains a scope with rewriting information to process. If so, locals and closures are replaced with the substitutions provided by the tree. Practically, this means that the tree contains: 1. A list of synthesized locals to add to each scope. 2. A set of proxies to replace existing symbols. 3. A list of synthesized methods and types to add to the enclosing type.
Closure Conversion in C# ======================== This document describes the how the C# compiler turns closures (anonymous and local functions) into top-level functions (methods). If you aren't familiar with closure conversion, the introduction contains a walkthrough describing the transformations. Otherwise, you can skip to the Internals section to see how the actual transformations are done in Roslyn. # Introduction In the simplest case, this is trivial -- all closures are simply given new, unmentionable names and are lifted to the top level as static methods. The complexity comes when a closure captures a variable from its surrounding scope. At that point, we must not only move the closure to a method, we also have to create an "environment" to hold its captured variables and somehow deliver that environment into the context of the rewritten method. There are two possible strategies that are both employed in different situations in the compiler. The first strategy is to pass the environment as an extra parameter to all method calls to the closure. For example, ```csharp void M() { int x = 0; int Local() => x + 1; } ``` becomes ```csharp void M() { var env = new Environment(); env.x = 0; <>__Local(env); } static int <>__Local(Environment env) { return env.x + 1; } struct Environment { int x; } ``` Instead of referring to local variables, the rewritten closure now references fields on the environment. A `struct` environment is used to prevent extra allocations, since `struct`s are normally allocated on the stack. However, the astute reader may notice a problem with this conversion -- `struct`s are always copied when passed as arguments to a function call! This means that writes to the environment field will not always propagate back to the local variable in the method `M`. To work around this flaw, all Environment variables are passed as `ref` arguments to the rewritten closures. The second strategy for rewriting closures is necessary when the closure interacts with external code. Consider the following program: ```csharp void M(IEnumerable<int> e) { int x = 0; var positive = e.Where(n => n > 0); ... } ``` In this case we're passing a closure to the `IEnumerable<int>.Where` function, which is expecting a delegate of type `Func<int, bool>`. Note that that delegate type is immutable -- it is defined in external code and cannot be changed. Therefore, rewriting external callsites to take an extra `Environment` argument is impossible. We have to choose a different strategy for acquiring the environment. What we do is use a `class` Environment for cases like this. With a `class` Environment, the previous environment can be rewritten as follows: ```csharp void M(IEnumerable<int> e) { var env = new Environment(); env.x = 0; var positive = e.Where(env.<>__Local); } class Environment { int x; bool <>__Local(int n) => n > 0; } ``` Since the local variables are now fields in a class instance we can keep the same delegate signature and rely on field access to read and write the free variables. This covers the transformations C# performs at a high level. The following section covers how these transformations are performed in detail. # Internals There are two phases at the top level of closure conversion. The first phase, Analysis, is responsible for building an AnalysisResult data structure which contains all information necessary to rewrite all closures. The second phase, Rewriting, actually performs the aforementioned rewriting by replacing and adding BoundNodes to the Bound Tree. The most important contract between these two phases is that the Analysis phase performs no modifications to the Bound Tree and the Rewriting phase performs no computation and contains no logic aside from a simple mechanical modification of the Bound Tree based on the AnalysisResult. ## Analysis In this phase we build an AnalysisResult, which is a tree structure that exactly represents the state mapping from the original program to the closure-converted form. For example, the following program ```csharp void M() { int x = 0; int Local() => x + 1; { int y = 0; int z = 0; int Local2() => Local() + y; z++; Local2(); } Local(); } ``` Would produce a tree similar to ``` +-------------------------------------+ |Captured: Closures: | |int x int Local() | |int Local() | | | | +--------------------------------+ | | | Captured: Closures: | | | | int y int Local2() | | | | | | | +--------------------------------+ | +-------------------------------------+ ``` To create this AnalysisResult there are multiple passes. The first pass gathers information by constructing a naive tree of scopes, closures, and captured variables. The result is a tree of nested scopes, where each scope lists the captured variables declared in the scope and the closures in that scope. The first pass must first gather information since most rewriting decisions, like what Environment type to use for the closures or what the rewritten closure signature will be, are dependent on context from the entire method. Information about captured variables are stored on instances of the `CapturedVariable` class, which holds information about the Symbol that was captured and rewriting information like the `SynthesizedLocal` that will replace the variable post-rewriting. Similarly, closures will be stored in instances of the `Closure` class, which contain both the original Symbol and the synthesized type or method created for the closure. All of these classes are mutable since it's expected that later passes will fill in more rewriting information using the structure gathered from the earlier passes. For instance, in the previous example we need to walk the tree to generate an Environment for the closures `Closure`, resulting in something like the following: ``` Closure ------- Name: Local Generated Sig: int <>_Local(ref <>_Env1) Environment: - Captures: 'int x' - Name: <>_Env1 - Type: Struct Name: Local2 Generated Sig: int <>_Local(ref <>_Env2, ref <>_Env1) Environment: - Captures: 'int y', 'ref <>_Env1' - Name: <>_Env2 - Type: Struct ``` This result would be generated by each piece filling in required info: first filling in all the capture lists, then deciding the Environment type based on the capture list, then generating the end signature based on the environment type and final capture list. Some further details of analysis calculations can be found below: **TODO** _Add details for each analysis phase as implementation is fleshed out_ * Deciding what environment type is necessary for each closure. An environment can be a struct unless one of the following things is true: 1. The closure is converted to delegate. 2. The closure captures a variable which is captured by a closure that cannot have a `struct` Environment. 3. A reference to the closure is captured by a closure that cannot have a `struct` Environment. * Creating `SynthesizedLocal`s for hoisted captured variables and captured Environment references * Assigning rewritten names, signatures, and type parameters to each closure ## Optimization The final passes are optimization passes. They attempt to simplify the tree by removing intermediate scopes with no captured variables and otherwise correcting the tree to create the most efficient rewritten form. Optimization opportunities could include running escape analysis to determine if capture hoisting could be done via copy or done in a narrower scope. ## Rewriting The rewriting phase simply walks the bound tree and, at each new scope, checks to see if the AnalysisResult contains a scope with rewriting information to process. If so, locals and closures are replaced with the substitutions provided by the tree. Practically, this means that the tree contains: 1. A list of synthesized locals to add to each scope. 2. A set of proxies to replace existing symbols. 3. A list of synthesized methods and types to add to the enclosing type.
-1
dotnet/roslyn
55,428
Test adding nested namespaces
Fixes https://github.com/dotnet/roslyn/issues/54939 The "workaround" that's already implemented is actually the correct behavior.
tmat
2021-08-05T01:19:03Z
2021-08-11T18:38:54Z
bc874ebc5111a2a33221409f895953b1536f6612
1cbbd423e17b186a8f1de89febb4db9a386d180d
Test adding nested namespaces. Fixes https://github.com/dotnet/roslyn/issues/54939 The "workaround" that's already implemented is actually the correct behavior.
./src/Workspaces/Core/Portable/CodeRefactorings/CodeRefactoringProvider.cs
// Licensed to the .NET Foundation under one or more agreements. // 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.CodeActions; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CodeRefactorings { /// <summary> /// Inherit this type to provide source code refactorings. /// Remember to use <see cref="ExportCodeRefactoringProviderAttribute"/> so the host environment can offer your refactorings in a UI. /// </summary> public abstract class CodeRefactoringProvider { /// <summary> /// Computes one or more refactorings for the specified <see cref="CodeRefactoringContext"/>. /// </summary> public abstract Task ComputeRefactoringsAsync(CodeRefactoringContext context); /// <summary> /// What priority this provider should run at. /// </summary> internal CodeActionRequestPriority RequestPriority { get { var priority = ComputeRequestPriority(); Contract.ThrowIfFalse(priority is CodeActionRequestPriority.Normal or CodeActionRequestPriority.High); return priority; } } private protected virtual CodeActionRequestPriority ComputeRequestPriority() => CodeActionRequestPriority.Normal; } }
// Licensed to the .NET Foundation under one or more agreements. // 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.CodeActions; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CodeRefactorings { /// <summary> /// Inherit this type to provide source code refactorings. /// Remember to use <see cref="ExportCodeRefactoringProviderAttribute"/> so the host environment can offer your refactorings in a UI. /// </summary> public abstract class CodeRefactoringProvider { /// <summary> /// Computes one or more refactorings for the specified <see cref="CodeRefactoringContext"/>. /// </summary> public abstract Task ComputeRefactoringsAsync(CodeRefactoringContext context); /// <summary> /// What priority this provider should run at. /// </summary> internal CodeActionRequestPriority RequestPriority { get { var priority = ComputeRequestPriority(); Contract.ThrowIfFalse(priority is CodeActionRequestPriority.Normal or CodeActionRequestPriority.High); return priority; } } private protected virtual CodeActionRequestPriority ComputeRequestPriority() => CodeActionRequestPriority.Normal; } }
-1
dotnet/roslyn
55,428
Test adding nested namespaces
Fixes https://github.com/dotnet/roslyn/issues/54939 The "workaround" that's already implemented is actually the correct behavior.
tmat
2021-08-05T01:19:03Z
2021-08-11T18:38:54Z
bc874ebc5111a2a33221409f895953b1536f6612
1cbbd423e17b186a8f1de89febb4db9a386d180d
Test adding nested namespaces. Fixes https://github.com/dotnet/roslyn/issues/54939 The "workaround" that's already implemented is actually the correct behavior.
./src/Workspaces/Core/Portable/Workspace/Solution/ProjectInfo.cs
// Licensed to the .NET Foundation under one or more agreements. // 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.Text.RegularExpressions; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Serialization; using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis { /// <summary> /// A class that represents all the arguments necessary to create a new project instance. /// </summary> [DebuggerDisplay("{GetDebuggerDisplay(), nq}")] public sealed class ProjectInfo { internal ProjectAttributes Attributes { get; } /// <summary> /// The unique Id of the project. /// </summary> public ProjectId Id => Attributes.Id; /// <summary> /// The version of the project. /// </summary> public VersionStamp Version => Attributes.Version; /// <summary> /// The name of the project. This may differ from the project's filename. /// </summary> public string Name => Attributes.Name; /// <inheritdoc cref="ProjectAttributes.NameAndFlavor"/> internal (string? name, string? flavor) NameAndFlavor => Attributes.NameAndFlavor; /// <summary> /// The name of the assembly that this project will create, without file extension. /// </summary>, public string AssemblyName => Attributes.AssemblyName; /// <summary> /// The language of the project. /// </summary> public string Language => Attributes.Language; /// <summary> /// The path to the project file or null if there is no project file. /// </summary> public string? FilePath => Attributes.FilePath; /// <summary> /// The path to the output file (module or assembly). /// </summary> public string? OutputFilePath => Attributes.OutputFilePath; /// <summary> /// The path to the reference assembly output file. /// </summary> public string? OutputRefFilePath => Attributes.OutputRefFilePath; /// <summary> /// The path to the compiler output file (module or assembly). /// </summary> public CompilationOutputInfo CompilationOutputInfo => Attributes.CompilationOutputInfo; /// <summary> /// The default namespace of the project ("" if not defined, which means global namespace), /// or null if it is unknown or not applicable. /// </summary> /// <remarks> /// Right now VB doesn't have the concept of "default namespace", but we conjure one in workspace /// by assigning the value of the project's root namespace to it. So various features can choose to /// use it for their own purpose. /// In the future, we might consider officially exposing "default namespace" for VB project /// (e.g. through a "defaultnamespace" msbuild property) /// </remarks> internal string? DefaultNamespace => Attributes.DefaultNamespace; /// <summary> /// True if this is a submission project for interactive sessions. /// </summary> public bool IsSubmission => Attributes.IsSubmission; /// <summary> /// True if project information is complete. In some workspace hosts, it is possible /// a project only has partial information. In such cases, a project might not have all /// information on its files or references. /// </summary> internal bool HasAllInformation => Attributes.HasAllInformation; /// <summary> /// True if we should run analyzers for this project. /// </summary> internal bool RunAnalyzers => Attributes.RunAnalyzers; /// <summary> /// The initial compilation options for the project, or null if the default options should be used. /// </summary> public CompilationOptions? CompilationOptions { get; } /// <summary> /// The initial parse options for the source code documents in this project, or null if the default options should be used. /// </summary> public ParseOptions? ParseOptions { get; } /// <summary> /// The list of source documents initially associated with the project. /// </summary> public IReadOnlyList<DocumentInfo> Documents { get; } /// <summary> /// The project references initially defined for the project. /// </summary> public IReadOnlyList<ProjectReference> ProjectReferences { get; } /// <summary> /// The metadata references initially defined for the project. /// </summary> public IReadOnlyList<MetadataReference> MetadataReferences { get; } /// <summary> /// The analyzers initially associated with this project. /// </summary> public IReadOnlyList<AnalyzerReference> AnalyzerReferences { get; } /// <summary> /// The list of non-source documents associated with this project. /// </summary> public IReadOnlyList<DocumentInfo> AdditionalDocuments { get; } /// <summary> /// The list of analyzerconfig documents associated with this project. /// </summary> public IReadOnlyList<DocumentInfo> AnalyzerConfigDocuments { get; } /// <summary> /// Type of the host object. /// </summary> public Type? HostObjectType { get; } private ProjectInfo( ProjectAttributes attributes, CompilationOptions? compilationOptions, ParseOptions? parseOptions, IReadOnlyList<DocumentInfo> documents, IReadOnlyList<ProjectReference> projectReferences, IReadOnlyList<MetadataReference> metadataReferences, IReadOnlyList<AnalyzerReference> analyzerReferences, IReadOnlyList<DocumentInfo> additionalDocuments, IReadOnlyList<DocumentInfo> analyzerConfigDocuments, Type? hostObjectType) { Attributes = attributes; CompilationOptions = compilationOptions; ParseOptions = parseOptions; Documents = documents; ProjectReferences = projectReferences; MetadataReferences = metadataReferences; AnalyzerReferences = analyzerReferences; AdditionalDocuments = additionalDocuments; AnalyzerConfigDocuments = analyzerConfigDocuments; HostObjectType = hostObjectType; } // 2.7.0 BACKCOMPAT OVERLOAD -- DO NOT TOUCH /// <summary> /// Create a new instance of a <see cref="ProjectInfo"/>. /// </summary> public static ProjectInfo Create( ProjectId id, VersionStamp version, string name, string assemblyName, string language, string? filePath, string? outputFilePath, CompilationOptions? compilationOptions, ParseOptions? parseOptions, IEnumerable<DocumentInfo>? documents, IEnumerable<ProjectReference>? projectReferences, IEnumerable<MetadataReference>? metadataReferences, IEnumerable<AnalyzerReference>? analyzerReferences, IEnumerable<DocumentInfo>? additionalDocuments, bool isSubmission, Type? hostObjectType) { return Create( id, version, name, assemblyName, language, filePath, outputFilePath, compilationOptions, parseOptions, documents, projectReferences, metadataReferences, analyzerReferences, additionalDocuments, isSubmission, hostObjectType, outputRefFilePath: null); } /// <summary> /// Create a new instance of a <see cref="ProjectInfo"/>. /// </summary> public static ProjectInfo Create( ProjectId id, VersionStamp version, string name, string assemblyName, string language, string? filePath = null, string? outputFilePath = null, CompilationOptions? compilationOptions = null, ParseOptions? parseOptions = null, IEnumerable<DocumentInfo>? documents = null, IEnumerable<ProjectReference>? projectReferences = null, IEnumerable<MetadataReference>? metadataReferences = null, IEnumerable<AnalyzerReference>? analyzerReferences = null, IEnumerable<DocumentInfo>? additionalDocuments = null, bool isSubmission = false, Type? hostObjectType = null, string? outputRefFilePath = null) { return new ProjectInfo( new ProjectAttributes( id ?? throw new ArgumentNullException(nameof(id)), version, name ?? throw new ArgumentNullException(nameof(name)), assemblyName ?? throw new ArgumentNullException(nameof(assemblyName)), language ?? throw new ArgumentNullException(nameof(language)), filePath, outputFilePath, outputRefFilePath, compilationOutputFilePaths: default, defaultNamespace: null, isSubmission, hasAllInformation: true, runAnalyzers: true, telemetryId: default), compilationOptions, parseOptions, PublicContract.ToBoxedImmutableArrayWithDistinctNonNullItems(documents, nameof(documents)), PublicContract.ToBoxedImmutableArrayWithDistinctNonNullItems(projectReferences, nameof(projectReferences)), PublicContract.ToBoxedImmutableArrayWithDistinctNonNullItems(metadataReferences, nameof(metadataReferences)), PublicContract.ToBoxedImmutableArrayWithDistinctNonNullItems(analyzerReferences, nameof(analyzerReferences)), PublicContract.ToBoxedImmutableArrayWithDistinctNonNullItems(additionalDocuments, nameof(additionalDocuments)), analyzerConfigDocuments: SpecializedCollections.EmptyBoxedImmutableArray<DocumentInfo>(), hostObjectType); } internal ProjectInfo With( ProjectAttributes? attributes = null, Optional<CompilationOptions?> compilationOptions = default, Optional<ParseOptions?> parseOptions = default, IReadOnlyList<DocumentInfo>? documents = null, IReadOnlyList<ProjectReference>? projectReferences = null, IReadOnlyList<MetadataReference>? metadataReferences = null, IReadOnlyList<AnalyzerReference>? analyzerReferences = null, IReadOnlyList<DocumentInfo>? additionalDocuments = null, IReadOnlyList<DocumentInfo>? analyzerConfigDocuments = null, Optional<Type?> hostObjectType = default) { var newAttributes = attributes ?? Attributes; var newCompilationOptions = compilationOptions.HasValue ? compilationOptions.Value : CompilationOptions; var newParseOptions = parseOptions.HasValue ? parseOptions.Value : ParseOptions; var newDocuments = documents ?? Documents; var newProjectReferences = projectReferences ?? ProjectReferences; var newMetadataReferences = metadataReferences ?? MetadataReferences; var newAnalyzerReferences = analyzerReferences ?? AnalyzerReferences; var newAdditionalDocuments = additionalDocuments ?? AdditionalDocuments; var newAnalyzerConfigDocuments = analyzerConfigDocuments ?? AnalyzerConfigDocuments; var newHostObjectType = hostObjectType.HasValue ? hostObjectType.Value : HostObjectType; if (newAttributes == Attributes && newCompilationOptions == CompilationOptions && newParseOptions == ParseOptions && newDocuments == Documents && newProjectReferences == ProjectReferences && newMetadataReferences == MetadataReferences && newAnalyzerReferences == AnalyzerReferences && newAdditionalDocuments == AdditionalDocuments && newAnalyzerConfigDocuments == AnalyzerConfigDocuments && newHostObjectType == HostObjectType) { return this; } return new ProjectInfo( newAttributes, newCompilationOptions, newParseOptions, newDocuments, newProjectReferences, newMetadataReferences, newAnalyzerReferences, newAdditionalDocuments, newAnalyzerConfigDocuments, newHostObjectType); } public ProjectInfo WithVersion(VersionStamp version) => With(attributes: Attributes.With(version: version)); public ProjectInfo WithName(string name) => With(attributes: Attributes.With(name: name ?? throw new ArgumentNullException(nameof(name)))); public ProjectInfo WithAssemblyName(string assemblyName) => With(attributes: Attributes.With(assemblyName: assemblyName ?? throw new ArgumentNullException(nameof(assemblyName)))); public ProjectInfo WithFilePath(string? filePath) => With(attributes: Attributes.With(filePath: filePath)); public ProjectInfo WithOutputFilePath(string? outputFilePath) => With(attributes: Attributes.With(outputPath: outputFilePath)); public ProjectInfo WithOutputRefFilePath(string? outputRefFilePath) => With(attributes: Attributes.With(outputRefPath: outputRefFilePath)); public ProjectInfo WithCompilationOutputInfo(in CompilationOutputInfo info) => With(attributes: Attributes.With(compilationOutputInfo: info)); public ProjectInfo WithDefaultNamespace(string? defaultNamespace) => With(attributes: Attributes.With(defaultNamespace: defaultNamespace)); internal ProjectInfo WithHasAllInformation(bool hasAllInformation) => With(attributes: Attributes.With(hasAllInformation: hasAllInformation)); internal ProjectInfo WithRunAnalyzers(bool runAnalyzers) => With(attributes: Attributes.With(runAnalyzers: runAnalyzers)); public ProjectInfo WithCompilationOptions(CompilationOptions? compilationOptions) => With(compilationOptions: compilationOptions); public ProjectInfo WithParseOptions(ParseOptions? parseOptions) => With(parseOptions: parseOptions); public ProjectInfo WithDocuments(IEnumerable<DocumentInfo>? documents) => With(documents: PublicContract.ToBoxedImmutableArrayWithDistinctNonNullItems(documents, nameof(documents))); public ProjectInfo WithAdditionalDocuments(IEnumerable<DocumentInfo>? additionalDocuments) => With(additionalDocuments: PublicContract.ToBoxedImmutableArrayWithDistinctNonNullItems(additionalDocuments, nameof(additionalDocuments))); public ProjectInfo WithAnalyzerConfigDocuments(IEnumerable<DocumentInfo>? analyzerConfigDocuments) => With(analyzerConfigDocuments: PublicContract.ToBoxedImmutableArrayWithDistinctNonNullItems(analyzerConfigDocuments, nameof(analyzerConfigDocuments))); public ProjectInfo WithProjectReferences(IEnumerable<ProjectReference>? projectReferences) => With(projectReferences: PublicContract.ToBoxedImmutableArrayWithDistinctNonNullItems(projectReferences, nameof(projectReferences))); public ProjectInfo WithMetadataReferences(IEnumerable<MetadataReference>? metadataReferences) => With(metadataReferences: PublicContract.ToBoxedImmutableArrayWithDistinctNonNullItems(metadataReferences, nameof(metadataReferences))); public ProjectInfo WithAnalyzerReferences(IEnumerable<AnalyzerReference>? analyzerReferences) => With(analyzerReferences: PublicContract.ToBoxedImmutableArrayWithDistinctNonNullItems(analyzerReferences, nameof(analyzerReferences))); internal ProjectInfo WithTelemetryId(Guid telemetryId) { return With(attributes: Attributes.With(telemetryId: telemetryId)); } internal string GetDebuggerDisplay() => nameof(ProjectInfo) + " " + Name + (!string.IsNullOrWhiteSpace(FilePath) ? " " + FilePath : ""); /// <summary> /// type that contains information regarding this project itself but /// no tree information such as document info /// </summary> internal sealed class ProjectAttributes : IChecksummedObject, IObjectWritable { /// <summary> /// Matches names like: Microsoft.CodeAnalysis.Features (netcoreapp3.1) /// </summary> private static readonly Regex s_projectNameAndFlavor = new Regex(@"^(?<name>.*?)\s*\((?<flavor>.*?)\)$", RegexOptions.Compiled); private Checksum? _lazyChecksum; /// <summary> /// The unique Id of the project. /// </summary> public ProjectId Id { get; } /// <summary> /// The version of the project. /// </summary> public VersionStamp Version { get; } /// <summary> /// The name of the project. This may differ from the project's filename. /// </summary> public string Name { get; } /// <summary> /// The name and flavor portions of the project broken out. For example, the project /// <c>Microsoft.CodeAnalysis.Workspace (netcoreapp3.1)</c> would have the name /// <c>Microsoft.CodeAnalysis.Workspace</c> and the flavor <c>netcoreapp3.1</c>. Values may be null <see /// langword="null"/> if the name does not contain a flavor. /// </summary> public (string? name, string? flavor) NameAndFlavor { get; } /// <summary> /// The name of the assembly that this project will create, without file extension. /// </summary>, public string AssemblyName { get; } /// <summary> /// The language of the project. /// </summary> public string Language { get; } /// <summary> /// The path to the project file or null if there is no project file. /// </summary> public string? FilePath { get; } /// <summary> /// The path to the output file (module or assembly). /// </summary> public string? OutputFilePath { get; } /// <summary> /// The path to the reference assembly output file. /// </summary> public string? OutputRefFilePath { get; } /// <summary> /// Paths to the compiler output files. /// </summary> public CompilationOutputInfo CompilationOutputInfo { get; } /// <summary> /// The default namespace of the project. /// </summary> public string? DefaultNamespace { get; } /// <summary> /// True if this is a submission project for interactive sessions. /// </summary> public bool IsSubmission { get; } /// <summary> /// True if project information is complete. In some workspace hosts, it is possible /// a project only has partial information. In such cases, a project might not have all /// information on its files or references. /// </summary> public bool HasAllInformation { get; } /// <summary> /// True if we should run analyzers for this project. /// </summary> public bool RunAnalyzers { get; } /// <summary> /// The id report during telemetry events. /// </summary> public Guid TelemetryId { get; } public ProjectAttributes( ProjectId id, VersionStamp version, string name, string assemblyName, string language, string? filePath, string? outputFilePath, string? outputRefFilePath, CompilationOutputInfo compilationOutputFilePaths, string? defaultNamespace, bool isSubmission, bool hasAllInformation, bool runAnalyzers, Guid telemetryId) { Id = id; Name = name; Language = language; AssemblyName = assemblyName; Version = version; FilePath = filePath; OutputFilePath = outputFilePath; OutputRefFilePath = outputRefFilePath; CompilationOutputInfo = compilationOutputFilePaths; DefaultNamespace = defaultNamespace; IsSubmission = isSubmission; HasAllInformation = hasAllInformation; RunAnalyzers = runAnalyzers; TelemetryId = telemetryId; var match = s_projectNameAndFlavor.Match(Name); if (match?.Success == true) NameAndFlavor = (match.Groups["name"].Value, match.Groups["flavor"].Value); } public ProjectAttributes With( VersionStamp? version = null, string? name = null, string? assemblyName = null, string? language = null, Optional<string?> filePath = default, Optional<string?> outputPath = default, Optional<string?> outputRefPath = default, Optional<CompilationOutputInfo> compilationOutputInfo = default, Optional<string?> defaultNamespace = default, Optional<bool> isSubmission = default, Optional<bool> hasAllInformation = default, Optional<bool> runAnalyzers = default, Optional<Guid> telemetryId = default) { var newVersion = version ?? Version; var newName = name ?? Name; var newAssemblyName = assemblyName ?? AssemblyName; var newLanguage = language ?? Language; var newFilepath = filePath.HasValue ? filePath.Value : FilePath; var newOutputPath = outputPath.HasValue ? outputPath.Value : OutputFilePath; var newOutputRefPath = outputRefPath.HasValue ? outputRefPath.Value : OutputRefFilePath; var newCompilationOutputPaths = compilationOutputInfo.HasValue ? compilationOutputInfo.Value : CompilationOutputInfo; var newDefaultNamespace = defaultNamespace.HasValue ? defaultNamespace.Value : DefaultNamespace; var newIsSubmission = isSubmission.HasValue ? isSubmission.Value : IsSubmission; var newHasAllInformation = hasAllInformation.HasValue ? hasAllInformation.Value : HasAllInformation; var newRunAnalyzers = runAnalyzers.HasValue ? runAnalyzers.Value : RunAnalyzers; var newTelemetryId = telemetryId.HasValue ? telemetryId.Value : TelemetryId; if (newVersion == Version && newName == Name && newAssemblyName == AssemblyName && newLanguage == Language && newFilepath == FilePath && newOutputPath == OutputFilePath && newOutputRefPath == OutputRefFilePath && newCompilationOutputPaths == CompilationOutputInfo && newDefaultNamespace == DefaultNamespace && newIsSubmission == IsSubmission && newHasAllInformation == HasAllInformation && newRunAnalyzers == RunAnalyzers && newTelemetryId == TelemetryId) { return this; } return new ProjectAttributes( Id, newVersion, newName, newAssemblyName, newLanguage, newFilepath, newOutputPath, newOutputRefPath, newCompilationOutputPaths, newDefaultNamespace, newIsSubmission, newHasAllInformation, newRunAnalyzers, newTelemetryId); } bool IObjectWritable.ShouldReuseInSerialization => true; public void WriteTo(ObjectWriter writer) { Id.WriteTo(writer); // TODO: figure out a way to send version info over as well // info.Version.WriteTo(writer); writer.WriteString(Name); writer.WriteString(AssemblyName); writer.WriteString(Language); writer.WriteString(FilePath); writer.WriteString(OutputFilePath); writer.WriteString(OutputRefFilePath); CompilationOutputInfo.WriteTo(writer); writer.WriteString(DefaultNamespace); writer.WriteBoolean(IsSubmission); writer.WriteBoolean(HasAllInformation); writer.WriteBoolean(RunAnalyzers); writer.WriteGuid(TelemetryId); // TODO: once CompilationOptions, ParseOptions, ProjectReference, MetadataReference, AnalyzerReference supports // serialization, we should include those here as well. } public static ProjectAttributes ReadFrom(ObjectReader reader) { var projectId = ProjectId.ReadFrom(reader); // var version = VersionStamp.ReadFrom(reader); var name = reader.ReadString(); var assemblyName = reader.ReadString(); var language = reader.ReadString(); var filePath = reader.ReadString(); var outputFilePath = reader.ReadString(); var outputRefFilePath = reader.ReadString(); var compilationOutputFilePaths = CompilationOutputInfo.ReadFrom(reader); var defaultNamespace = reader.ReadString(); var isSubmission = reader.ReadBoolean(); var hasAllInformation = reader.ReadBoolean(); var runAnalyzers = reader.ReadBoolean(); var telemetryId = reader.ReadGuid(); return new ProjectAttributes( projectId, VersionStamp.Create(), name, assemblyName, language, filePath, outputFilePath, outputRefFilePath, compilationOutputFilePaths, defaultNamespace, isSubmission, hasAllInformation, runAnalyzers, telemetryId); } Checksum IChecksummedObject.Checksum => _lazyChecksum ??= Checksum.Create(this); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Diagnostics; using System.Text.RegularExpressions; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Serialization; using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis { /// <summary> /// A class that represents all the arguments necessary to create a new project instance. /// </summary> [DebuggerDisplay("{GetDebuggerDisplay(), nq}")] public sealed class ProjectInfo { internal ProjectAttributes Attributes { get; } /// <summary> /// The unique Id of the project. /// </summary> public ProjectId Id => Attributes.Id; /// <summary> /// The version of the project. /// </summary> public VersionStamp Version => Attributes.Version; /// <summary> /// The name of the project. This may differ from the project's filename. /// </summary> public string Name => Attributes.Name; /// <inheritdoc cref="ProjectAttributes.NameAndFlavor"/> internal (string? name, string? flavor) NameAndFlavor => Attributes.NameAndFlavor; /// <summary> /// The name of the assembly that this project will create, without file extension. /// </summary>, public string AssemblyName => Attributes.AssemblyName; /// <summary> /// The language of the project. /// </summary> public string Language => Attributes.Language; /// <summary> /// The path to the project file or null if there is no project file. /// </summary> public string? FilePath => Attributes.FilePath; /// <summary> /// The path to the output file (module or assembly). /// </summary> public string? OutputFilePath => Attributes.OutputFilePath; /// <summary> /// The path to the reference assembly output file. /// </summary> public string? OutputRefFilePath => Attributes.OutputRefFilePath; /// <summary> /// The path to the compiler output file (module or assembly). /// </summary> public CompilationOutputInfo CompilationOutputInfo => Attributes.CompilationOutputInfo; /// <summary> /// The default namespace of the project ("" if not defined, which means global namespace), /// or null if it is unknown or not applicable. /// </summary> /// <remarks> /// Right now VB doesn't have the concept of "default namespace", but we conjure one in workspace /// by assigning the value of the project's root namespace to it. So various features can choose to /// use it for their own purpose. /// In the future, we might consider officially exposing "default namespace" for VB project /// (e.g. through a "defaultnamespace" msbuild property) /// </remarks> internal string? DefaultNamespace => Attributes.DefaultNamespace; /// <summary> /// True if this is a submission project for interactive sessions. /// </summary> public bool IsSubmission => Attributes.IsSubmission; /// <summary> /// True if project information is complete. In some workspace hosts, it is possible /// a project only has partial information. In such cases, a project might not have all /// information on its files or references. /// </summary> internal bool HasAllInformation => Attributes.HasAllInformation; /// <summary> /// True if we should run analyzers for this project. /// </summary> internal bool RunAnalyzers => Attributes.RunAnalyzers; /// <summary> /// The initial compilation options for the project, or null if the default options should be used. /// </summary> public CompilationOptions? CompilationOptions { get; } /// <summary> /// The initial parse options for the source code documents in this project, or null if the default options should be used. /// </summary> public ParseOptions? ParseOptions { get; } /// <summary> /// The list of source documents initially associated with the project. /// </summary> public IReadOnlyList<DocumentInfo> Documents { get; } /// <summary> /// The project references initially defined for the project. /// </summary> public IReadOnlyList<ProjectReference> ProjectReferences { get; } /// <summary> /// The metadata references initially defined for the project. /// </summary> public IReadOnlyList<MetadataReference> MetadataReferences { get; } /// <summary> /// The analyzers initially associated with this project. /// </summary> public IReadOnlyList<AnalyzerReference> AnalyzerReferences { get; } /// <summary> /// The list of non-source documents associated with this project. /// </summary> public IReadOnlyList<DocumentInfo> AdditionalDocuments { get; } /// <summary> /// The list of analyzerconfig documents associated with this project. /// </summary> public IReadOnlyList<DocumentInfo> AnalyzerConfigDocuments { get; } /// <summary> /// Type of the host object. /// </summary> public Type? HostObjectType { get; } private ProjectInfo( ProjectAttributes attributes, CompilationOptions? compilationOptions, ParseOptions? parseOptions, IReadOnlyList<DocumentInfo> documents, IReadOnlyList<ProjectReference> projectReferences, IReadOnlyList<MetadataReference> metadataReferences, IReadOnlyList<AnalyzerReference> analyzerReferences, IReadOnlyList<DocumentInfo> additionalDocuments, IReadOnlyList<DocumentInfo> analyzerConfigDocuments, Type? hostObjectType) { Attributes = attributes; CompilationOptions = compilationOptions; ParseOptions = parseOptions; Documents = documents; ProjectReferences = projectReferences; MetadataReferences = metadataReferences; AnalyzerReferences = analyzerReferences; AdditionalDocuments = additionalDocuments; AnalyzerConfigDocuments = analyzerConfigDocuments; HostObjectType = hostObjectType; } // 2.7.0 BACKCOMPAT OVERLOAD -- DO NOT TOUCH /// <summary> /// Create a new instance of a <see cref="ProjectInfo"/>. /// </summary> public static ProjectInfo Create( ProjectId id, VersionStamp version, string name, string assemblyName, string language, string? filePath, string? outputFilePath, CompilationOptions? compilationOptions, ParseOptions? parseOptions, IEnumerable<DocumentInfo>? documents, IEnumerable<ProjectReference>? projectReferences, IEnumerable<MetadataReference>? metadataReferences, IEnumerable<AnalyzerReference>? analyzerReferences, IEnumerable<DocumentInfo>? additionalDocuments, bool isSubmission, Type? hostObjectType) { return Create( id, version, name, assemblyName, language, filePath, outputFilePath, compilationOptions, parseOptions, documents, projectReferences, metadataReferences, analyzerReferences, additionalDocuments, isSubmission, hostObjectType, outputRefFilePath: null); } /// <summary> /// Create a new instance of a <see cref="ProjectInfo"/>. /// </summary> public static ProjectInfo Create( ProjectId id, VersionStamp version, string name, string assemblyName, string language, string? filePath = null, string? outputFilePath = null, CompilationOptions? compilationOptions = null, ParseOptions? parseOptions = null, IEnumerable<DocumentInfo>? documents = null, IEnumerable<ProjectReference>? projectReferences = null, IEnumerable<MetadataReference>? metadataReferences = null, IEnumerable<AnalyzerReference>? analyzerReferences = null, IEnumerable<DocumentInfo>? additionalDocuments = null, bool isSubmission = false, Type? hostObjectType = null, string? outputRefFilePath = null) { return new ProjectInfo( new ProjectAttributes( id ?? throw new ArgumentNullException(nameof(id)), version, name ?? throw new ArgumentNullException(nameof(name)), assemblyName ?? throw new ArgumentNullException(nameof(assemblyName)), language ?? throw new ArgumentNullException(nameof(language)), filePath, outputFilePath, outputRefFilePath, compilationOutputFilePaths: default, defaultNamespace: null, isSubmission, hasAllInformation: true, runAnalyzers: true, telemetryId: default), compilationOptions, parseOptions, PublicContract.ToBoxedImmutableArrayWithDistinctNonNullItems(documents, nameof(documents)), PublicContract.ToBoxedImmutableArrayWithDistinctNonNullItems(projectReferences, nameof(projectReferences)), PublicContract.ToBoxedImmutableArrayWithDistinctNonNullItems(metadataReferences, nameof(metadataReferences)), PublicContract.ToBoxedImmutableArrayWithDistinctNonNullItems(analyzerReferences, nameof(analyzerReferences)), PublicContract.ToBoxedImmutableArrayWithDistinctNonNullItems(additionalDocuments, nameof(additionalDocuments)), analyzerConfigDocuments: SpecializedCollections.EmptyBoxedImmutableArray<DocumentInfo>(), hostObjectType); } internal ProjectInfo With( ProjectAttributes? attributes = null, Optional<CompilationOptions?> compilationOptions = default, Optional<ParseOptions?> parseOptions = default, IReadOnlyList<DocumentInfo>? documents = null, IReadOnlyList<ProjectReference>? projectReferences = null, IReadOnlyList<MetadataReference>? metadataReferences = null, IReadOnlyList<AnalyzerReference>? analyzerReferences = null, IReadOnlyList<DocumentInfo>? additionalDocuments = null, IReadOnlyList<DocumentInfo>? analyzerConfigDocuments = null, Optional<Type?> hostObjectType = default) { var newAttributes = attributes ?? Attributes; var newCompilationOptions = compilationOptions.HasValue ? compilationOptions.Value : CompilationOptions; var newParseOptions = parseOptions.HasValue ? parseOptions.Value : ParseOptions; var newDocuments = documents ?? Documents; var newProjectReferences = projectReferences ?? ProjectReferences; var newMetadataReferences = metadataReferences ?? MetadataReferences; var newAnalyzerReferences = analyzerReferences ?? AnalyzerReferences; var newAdditionalDocuments = additionalDocuments ?? AdditionalDocuments; var newAnalyzerConfigDocuments = analyzerConfigDocuments ?? AnalyzerConfigDocuments; var newHostObjectType = hostObjectType.HasValue ? hostObjectType.Value : HostObjectType; if (newAttributes == Attributes && newCompilationOptions == CompilationOptions && newParseOptions == ParseOptions && newDocuments == Documents && newProjectReferences == ProjectReferences && newMetadataReferences == MetadataReferences && newAnalyzerReferences == AnalyzerReferences && newAdditionalDocuments == AdditionalDocuments && newAnalyzerConfigDocuments == AnalyzerConfigDocuments && newHostObjectType == HostObjectType) { return this; } return new ProjectInfo( newAttributes, newCompilationOptions, newParseOptions, newDocuments, newProjectReferences, newMetadataReferences, newAnalyzerReferences, newAdditionalDocuments, newAnalyzerConfigDocuments, newHostObjectType); } public ProjectInfo WithVersion(VersionStamp version) => With(attributes: Attributes.With(version: version)); public ProjectInfo WithName(string name) => With(attributes: Attributes.With(name: name ?? throw new ArgumentNullException(nameof(name)))); public ProjectInfo WithAssemblyName(string assemblyName) => With(attributes: Attributes.With(assemblyName: assemblyName ?? throw new ArgumentNullException(nameof(assemblyName)))); public ProjectInfo WithFilePath(string? filePath) => With(attributes: Attributes.With(filePath: filePath)); public ProjectInfo WithOutputFilePath(string? outputFilePath) => With(attributes: Attributes.With(outputPath: outputFilePath)); public ProjectInfo WithOutputRefFilePath(string? outputRefFilePath) => With(attributes: Attributes.With(outputRefPath: outputRefFilePath)); public ProjectInfo WithCompilationOutputInfo(in CompilationOutputInfo info) => With(attributes: Attributes.With(compilationOutputInfo: info)); public ProjectInfo WithDefaultNamespace(string? defaultNamespace) => With(attributes: Attributes.With(defaultNamespace: defaultNamespace)); internal ProjectInfo WithHasAllInformation(bool hasAllInformation) => With(attributes: Attributes.With(hasAllInformation: hasAllInformation)); internal ProjectInfo WithRunAnalyzers(bool runAnalyzers) => With(attributes: Attributes.With(runAnalyzers: runAnalyzers)); public ProjectInfo WithCompilationOptions(CompilationOptions? compilationOptions) => With(compilationOptions: compilationOptions); public ProjectInfo WithParseOptions(ParseOptions? parseOptions) => With(parseOptions: parseOptions); public ProjectInfo WithDocuments(IEnumerable<DocumentInfo>? documents) => With(documents: PublicContract.ToBoxedImmutableArrayWithDistinctNonNullItems(documents, nameof(documents))); public ProjectInfo WithAdditionalDocuments(IEnumerable<DocumentInfo>? additionalDocuments) => With(additionalDocuments: PublicContract.ToBoxedImmutableArrayWithDistinctNonNullItems(additionalDocuments, nameof(additionalDocuments))); public ProjectInfo WithAnalyzerConfigDocuments(IEnumerable<DocumentInfo>? analyzerConfigDocuments) => With(analyzerConfigDocuments: PublicContract.ToBoxedImmutableArrayWithDistinctNonNullItems(analyzerConfigDocuments, nameof(analyzerConfigDocuments))); public ProjectInfo WithProjectReferences(IEnumerable<ProjectReference>? projectReferences) => With(projectReferences: PublicContract.ToBoxedImmutableArrayWithDistinctNonNullItems(projectReferences, nameof(projectReferences))); public ProjectInfo WithMetadataReferences(IEnumerable<MetadataReference>? metadataReferences) => With(metadataReferences: PublicContract.ToBoxedImmutableArrayWithDistinctNonNullItems(metadataReferences, nameof(metadataReferences))); public ProjectInfo WithAnalyzerReferences(IEnumerable<AnalyzerReference>? analyzerReferences) => With(analyzerReferences: PublicContract.ToBoxedImmutableArrayWithDistinctNonNullItems(analyzerReferences, nameof(analyzerReferences))); internal ProjectInfo WithTelemetryId(Guid telemetryId) { return With(attributes: Attributes.With(telemetryId: telemetryId)); } internal string GetDebuggerDisplay() => nameof(ProjectInfo) + " " + Name + (!string.IsNullOrWhiteSpace(FilePath) ? " " + FilePath : ""); /// <summary> /// type that contains information regarding this project itself but /// no tree information such as document info /// </summary> internal sealed class ProjectAttributes : IChecksummedObject, IObjectWritable { /// <summary> /// Matches names like: Microsoft.CodeAnalysis.Features (netcoreapp3.1) /// </summary> private static readonly Regex s_projectNameAndFlavor = new Regex(@"^(?<name>.*?)\s*\((?<flavor>.*?)\)$", RegexOptions.Compiled); private Checksum? _lazyChecksum; /// <summary> /// The unique Id of the project. /// </summary> public ProjectId Id { get; } /// <summary> /// The version of the project. /// </summary> public VersionStamp Version { get; } /// <summary> /// The name of the project. This may differ from the project's filename. /// </summary> public string Name { get; } /// <summary> /// The name and flavor portions of the project broken out. For example, the project /// <c>Microsoft.CodeAnalysis.Workspace (netcoreapp3.1)</c> would have the name /// <c>Microsoft.CodeAnalysis.Workspace</c> and the flavor <c>netcoreapp3.1</c>. Values may be null <see /// langword="null"/> if the name does not contain a flavor. /// </summary> public (string? name, string? flavor) NameAndFlavor { get; } /// <summary> /// The name of the assembly that this project will create, without file extension. /// </summary>, public string AssemblyName { get; } /// <summary> /// The language of the project. /// </summary> public string Language { get; } /// <summary> /// The path to the project file or null if there is no project file. /// </summary> public string? FilePath { get; } /// <summary> /// The path to the output file (module or assembly). /// </summary> public string? OutputFilePath { get; } /// <summary> /// The path to the reference assembly output file. /// </summary> public string? OutputRefFilePath { get; } /// <summary> /// Paths to the compiler output files. /// </summary> public CompilationOutputInfo CompilationOutputInfo { get; } /// <summary> /// The default namespace of the project. /// </summary> public string? DefaultNamespace { get; } /// <summary> /// True if this is a submission project for interactive sessions. /// </summary> public bool IsSubmission { get; } /// <summary> /// True if project information is complete. In some workspace hosts, it is possible /// a project only has partial information. In such cases, a project might not have all /// information on its files or references. /// </summary> public bool HasAllInformation { get; } /// <summary> /// True if we should run analyzers for this project. /// </summary> public bool RunAnalyzers { get; } /// <summary> /// The id report during telemetry events. /// </summary> public Guid TelemetryId { get; } public ProjectAttributes( ProjectId id, VersionStamp version, string name, string assemblyName, string language, string? filePath, string? outputFilePath, string? outputRefFilePath, CompilationOutputInfo compilationOutputFilePaths, string? defaultNamespace, bool isSubmission, bool hasAllInformation, bool runAnalyzers, Guid telemetryId) { Id = id; Name = name; Language = language; AssemblyName = assemblyName; Version = version; FilePath = filePath; OutputFilePath = outputFilePath; OutputRefFilePath = outputRefFilePath; CompilationOutputInfo = compilationOutputFilePaths; DefaultNamespace = defaultNamespace; IsSubmission = isSubmission; HasAllInformation = hasAllInformation; RunAnalyzers = runAnalyzers; TelemetryId = telemetryId; var match = s_projectNameAndFlavor.Match(Name); if (match?.Success == true) NameAndFlavor = (match.Groups["name"].Value, match.Groups["flavor"].Value); } public ProjectAttributes With( VersionStamp? version = null, string? name = null, string? assemblyName = null, string? language = null, Optional<string?> filePath = default, Optional<string?> outputPath = default, Optional<string?> outputRefPath = default, Optional<CompilationOutputInfo> compilationOutputInfo = default, Optional<string?> defaultNamespace = default, Optional<bool> isSubmission = default, Optional<bool> hasAllInformation = default, Optional<bool> runAnalyzers = default, Optional<Guid> telemetryId = default) { var newVersion = version ?? Version; var newName = name ?? Name; var newAssemblyName = assemblyName ?? AssemblyName; var newLanguage = language ?? Language; var newFilepath = filePath.HasValue ? filePath.Value : FilePath; var newOutputPath = outputPath.HasValue ? outputPath.Value : OutputFilePath; var newOutputRefPath = outputRefPath.HasValue ? outputRefPath.Value : OutputRefFilePath; var newCompilationOutputPaths = compilationOutputInfo.HasValue ? compilationOutputInfo.Value : CompilationOutputInfo; var newDefaultNamespace = defaultNamespace.HasValue ? defaultNamespace.Value : DefaultNamespace; var newIsSubmission = isSubmission.HasValue ? isSubmission.Value : IsSubmission; var newHasAllInformation = hasAllInformation.HasValue ? hasAllInformation.Value : HasAllInformation; var newRunAnalyzers = runAnalyzers.HasValue ? runAnalyzers.Value : RunAnalyzers; var newTelemetryId = telemetryId.HasValue ? telemetryId.Value : TelemetryId; if (newVersion == Version && newName == Name && newAssemblyName == AssemblyName && newLanguage == Language && newFilepath == FilePath && newOutputPath == OutputFilePath && newOutputRefPath == OutputRefFilePath && newCompilationOutputPaths == CompilationOutputInfo && newDefaultNamespace == DefaultNamespace && newIsSubmission == IsSubmission && newHasAllInformation == HasAllInformation && newRunAnalyzers == RunAnalyzers && newTelemetryId == TelemetryId) { return this; } return new ProjectAttributes( Id, newVersion, newName, newAssemblyName, newLanguage, newFilepath, newOutputPath, newOutputRefPath, newCompilationOutputPaths, newDefaultNamespace, newIsSubmission, newHasAllInformation, newRunAnalyzers, newTelemetryId); } bool IObjectWritable.ShouldReuseInSerialization => true; public void WriteTo(ObjectWriter writer) { Id.WriteTo(writer); // TODO: figure out a way to send version info over as well // info.Version.WriteTo(writer); writer.WriteString(Name); writer.WriteString(AssemblyName); writer.WriteString(Language); writer.WriteString(FilePath); writer.WriteString(OutputFilePath); writer.WriteString(OutputRefFilePath); CompilationOutputInfo.WriteTo(writer); writer.WriteString(DefaultNamespace); writer.WriteBoolean(IsSubmission); writer.WriteBoolean(HasAllInformation); writer.WriteBoolean(RunAnalyzers); writer.WriteGuid(TelemetryId); // TODO: once CompilationOptions, ParseOptions, ProjectReference, MetadataReference, AnalyzerReference supports // serialization, we should include those here as well. } public static ProjectAttributes ReadFrom(ObjectReader reader) { var projectId = ProjectId.ReadFrom(reader); // var version = VersionStamp.ReadFrom(reader); var name = reader.ReadString(); var assemblyName = reader.ReadString(); var language = reader.ReadString(); var filePath = reader.ReadString(); var outputFilePath = reader.ReadString(); var outputRefFilePath = reader.ReadString(); var compilationOutputFilePaths = CompilationOutputInfo.ReadFrom(reader); var defaultNamespace = reader.ReadString(); var isSubmission = reader.ReadBoolean(); var hasAllInformation = reader.ReadBoolean(); var runAnalyzers = reader.ReadBoolean(); var telemetryId = reader.ReadGuid(); return new ProjectAttributes( projectId, VersionStamp.Create(), name, assemblyName, language, filePath, outputFilePath, outputRefFilePath, compilationOutputFilePaths, defaultNamespace, isSubmission, hasAllInformation, runAnalyzers, telemetryId); } Checksum IChecksummedObject.Checksum => _lazyChecksum ??= Checksum.Create(this); } } }
-1
dotnet/roslyn
55,428
Test adding nested namespaces
Fixes https://github.com/dotnet/roslyn/issues/54939 The "workaround" that's already implemented is actually the correct behavior.
tmat
2021-08-05T01:19:03Z
2021-08-11T18:38:54Z
bc874ebc5111a2a33221409f895953b1536f6612
1cbbd423e17b186a8f1de89febb4db9a386d180d
Test adding nested namespaces. Fixes https://github.com/dotnet/roslyn/issues/54939 The "workaround" that's already implemented is actually the correct behavior.
./src/Features/VisualBasic/Portable/CodeFixes/AddMissingReference/VisualBasicAddMissingReferenceCodeFixProvider.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable Imports System.Composition Imports System.Diagnostics.CodeAnalysis Imports Microsoft.CodeAnalysis.AddMissingReference Imports Microsoft.CodeAnalysis.CodeFixes Namespace Microsoft.CodeAnalysis.VisualBasic.AddMissingReference <ExportCodeFixProvider(LanguageNames.VisualBasic, Name:=PredefinedCodeFixProviderNames.AddMissingReference), [Shared]> <ExtensionOrder(After:=PredefinedCodeFixProviderNames.SimplifyNames)> Friend Class VisualBasicAddMissingReferenceCodeFixProvider Inherits AbstractAddMissingReferenceCodeFixProvider Friend Const BC30005 As String = "BC30005" ' ERR_UnreferencedAssemblyEvent3 Friend Const BC30652 As String = "BC30652" ' ERR_UnreferencedAssembly3 <ImportingConstructor> <SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification:="Used in test code: https://github.com/dotnet/roslyn/issues/42814")> Public Sub New() End Sub Public NotOverridable Overrides ReadOnly Property FixableDiagnosticIds As ImmutableArray(Of String) = ImmutableArray.Create(BC30005, BC30652) End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable Imports System.Composition Imports System.Diagnostics.CodeAnalysis Imports Microsoft.CodeAnalysis.AddMissingReference Imports Microsoft.CodeAnalysis.CodeFixes Namespace Microsoft.CodeAnalysis.VisualBasic.AddMissingReference <ExportCodeFixProvider(LanguageNames.VisualBasic, Name:=PredefinedCodeFixProviderNames.AddMissingReference), [Shared]> <ExtensionOrder(After:=PredefinedCodeFixProviderNames.SimplifyNames)> Friend Class VisualBasicAddMissingReferenceCodeFixProvider Inherits AbstractAddMissingReferenceCodeFixProvider Friend Const BC30005 As String = "BC30005" ' ERR_UnreferencedAssemblyEvent3 Friend Const BC30652 As String = "BC30652" ' ERR_UnreferencedAssembly3 <ImportingConstructor> <SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification:="Used in test code: https://github.com/dotnet/roslyn/issues/42814")> Public Sub New() End Sub Public NotOverridable Overrides ReadOnly Property FixableDiagnosticIds As ImmutableArray(Of String) = ImmutableArray.Create(BC30005, BC30652) End Class End Namespace
-1
dotnet/roslyn
55,428
Test adding nested namespaces
Fixes https://github.com/dotnet/roslyn/issues/54939 The "workaround" that's already implemented is actually the correct behavior.
tmat
2021-08-05T01:19:03Z
2021-08-11T18:38:54Z
bc874ebc5111a2a33221409f895953b1536f6612
1cbbd423e17b186a8f1de89febb4db9a386d180d
Test adding nested namespaces. Fixes https://github.com/dotnet/roslyn/issues/54939 The "workaround" that's already implemented is actually the correct behavior.
./src/Workspaces/SharedUtilitiesAndExtensions/Workspace/CSharp/Extensions/ITypeSymbolExtensions.TypeSyntaxGeneratorVisitor.cs
// Licensed to the .NET Foundation under one or more agreements. // 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 System.Linq; using System.Threading; using Microsoft.CodeAnalysis.CSharp.CodeGeneration; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Simplification; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Extensions { internal partial class ITypeSymbolExtensions { private class TypeSyntaxGeneratorVisitor : SymbolVisitor<TypeSyntax> { private readonly bool _nameOnly; private static readonly TypeSyntaxGeneratorVisitor NameOnlyInstance = new(nameOnly: true); private static readonly TypeSyntaxGeneratorVisitor NotNameOnlyInstance = new(nameOnly: false); private TypeSyntaxGeneratorVisitor(bool nameOnly) => _nameOnly = nameOnly; public static TypeSyntaxGeneratorVisitor Create(bool nameOnly = false) => nameOnly ? NameOnlyInstance : NotNameOnlyInstance; public override TypeSyntax DefaultVisit(ISymbol node) => throw new NotImplementedException(); private static TTypeSyntax AddInformationTo<TTypeSyntax>(TTypeSyntax syntax, ISymbol symbol) where TTypeSyntax : TypeSyntax { syntax = syntax.WithPrependedLeadingTrivia(SyntaxFactory.ElasticMarker).WithAppendedTrailingTrivia(SyntaxFactory.ElasticMarker); syntax = syntax.WithAdditionalAnnotations(SymbolAnnotation.Create(symbol)); return syntax; } public override TypeSyntax VisitAlias(IAliasSymbol symbol) => AddInformationTo(symbol.Name.ToIdentifierName(), symbol); private void ThrowIfNameOnly() { if (_nameOnly) { throw new InvalidOperationException("This symbol cannot be converted into a NameSyntax"); } } public override TypeSyntax VisitArrayType(IArrayTypeSymbol symbol) { ThrowIfNameOnly(); ITypeSymbol underlyingType = symbol; while (underlyingType is IArrayTypeSymbol innerArray) { underlyingType = innerArray.ElementType; if (underlyingType.NullableAnnotation == NullableAnnotation.Annotated) { // If the inner array we just moved to is also nullable, then // we must terminate the digging now so we produce the syntax for that, // and then append the ranks we passed through at the end. This is because // nullability annotations acts as a "barrier" where we won't reorder array // through. So whereas: // // string[][,] // // is really an array of rank 1 that has an element of rank 2, // // string[]?[,] // // is really an array of rank 2 that has nullable elements of rank 1. break; } } var elementTypeSyntax = underlyingType.GenerateTypeSyntax(); using var _ = ArrayBuilder<ArrayRankSpecifierSyntax>.GetInstance(out var ranks); var arrayType = symbol; while (arrayType != null && !arrayType.Equals(underlyingType)) { ranks.Add(SyntaxFactory.ArrayRankSpecifier( SyntaxFactory.SeparatedList(Enumerable.Repeat<ExpressionSyntax>(SyntaxFactory.OmittedArraySizeExpression(), arrayType.Rank)))); arrayType = arrayType.ElementType as IArrayTypeSymbol; } TypeSyntax arrayTypeSyntax = SyntaxFactory.ArrayType(elementTypeSyntax, ranks.ToSyntaxList()); if (symbol.NullableAnnotation == NullableAnnotation.Annotated) { arrayTypeSyntax = SyntaxFactory.NullableType(arrayTypeSyntax); } return AddInformationTo(arrayTypeSyntax, symbol); } public override TypeSyntax VisitDynamicType(IDynamicTypeSymbol symbol) => AddInformationTo(SyntaxFactory.IdentifierName("dynamic"), symbol); public static bool TryCreateNativeIntegerType(INamedTypeSymbol symbol, [NotNullWhen(true)] out TypeSyntax? syntax) { if (symbol.IsNativeIntegerType) { syntax = SyntaxFactory.IdentifierName(symbol.SpecialType == SpecialType.System_IntPtr ? "nint" : "nuint"); return true; } syntax = null; return false; } public override TypeSyntax VisitFunctionPointerType(IFunctionPointerTypeSymbol symbol) { FunctionPointerCallingConventionSyntax? callingConventionSyntax = null; // For varargs there is no C# syntax. You get a use-site diagnostic if you attempt to use it, and just // making a default-convention symbol is likely good enough. This is only observable through metadata // that always be uncompilable in C# anyway. if (symbol.Signature.CallingConvention != System.Reflection.Metadata.SignatureCallingConvention.Default && symbol.Signature.CallingConvention != System.Reflection.Metadata.SignatureCallingConvention.VarArgs) { var conventionsList = symbol.Signature.CallingConvention switch { System.Reflection.Metadata.SignatureCallingConvention.CDecl => new[] { GetConventionForString("Cdecl") }, System.Reflection.Metadata.SignatureCallingConvention.StdCall => new[] { GetConventionForString("Stdcall") }, System.Reflection.Metadata.SignatureCallingConvention.ThisCall => new[] { GetConventionForString("Thiscall") }, System.Reflection.Metadata.SignatureCallingConvention.FastCall => new[] { GetConventionForString("Fastcall") }, System.Reflection.Metadata.SignatureCallingConvention.Unmanaged => // All types that come from CallingConventionTypes start with "CallConv". We don't want the prefix for the actual // syntax, so strip it off symbol.Signature.UnmanagedCallingConventionTypes.IsEmpty ? null : symbol.Signature.UnmanagedCallingConventionTypes.Select(type => GetConventionForString(type.Name["CallConv".Length..])), _ => throw ExceptionUtilities.UnexpectedValue(symbol.Signature.CallingConvention), }; callingConventionSyntax = SyntaxFactory.FunctionPointerCallingConvention( SyntaxFactory.Token(SyntaxKind.UnmanagedKeyword), conventionsList is object ? SyntaxFactory.FunctionPointerUnmanagedCallingConventionList(SyntaxFactory.SeparatedList(conventionsList)) : null); static FunctionPointerUnmanagedCallingConventionSyntax GetConventionForString(string identifier) => SyntaxFactory.FunctionPointerUnmanagedCallingConvention(SyntaxFactory.Identifier(identifier)); } var parameters = symbol.Signature.Parameters.Select(p => (p.Type, RefKindModifiers: CSharpSyntaxGeneratorInternal.GetParameterModifiers(p.RefKind))) .Concat(SpecializedCollections.SingletonEnumerable(( Type: symbol.Signature.ReturnType, RefKindModifiers: CSharpSyntaxGeneratorInternal.GetParameterModifiers(symbol.Signature.RefKind, forFunctionPointerReturnParameter: true)))) .SelectAsArray(t => SyntaxFactory.FunctionPointerParameter(t.Type.GenerateTypeSyntax()).WithModifiers(t.RefKindModifiers)); return AddInformationTo( SyntaxFactory.FunctionPointerType(callingConventionSyntax, SyntaxFactory.FunctionPointerParameterList(SyntaxFactory.SeparatedList(parameters))), symbol); } public TypeSyntax CreateSimpleTypeSyntax(INamedTypeSymbol symbol) { if (!_nameOnly) { var syntax = TryCreateSpecializedNamedTypeSyntax(symbol); if (syntax != null) return syntax; } if (symbol.IsTupleType && symbol.TupleUnderlyingType != null && !symbol.Equals(symbol.TupleUnderlyingType)) { return CreateSimpleTypeSyntax(symbol.TupleUnderlyingType); } if (symbol.Name == string.Empty || symbol.IsAnonymousType) { return CreateSystemObject(); } if (symbol.TypeParameters.Length == 0) { if (symbol.TypeKind == TypeKind.Error && symbol.Name == "var") { return CreateSystemObject(); } return symbol.Name.ToIdentifierName(); } var typeArguments = symbol.IsUnboundGenericType ? Enumerable.Repeat((TypeSyntax)SyntaxFactory.OmittedTypeArgument(), symbol.TypeArguments.Length) : symbol.TypeArguments.SelectAsArray(t => t.GenerateTypeSyntax()); return SyntaxFactory.GenericName( symbol.Name.ToIdentifierToken(), SyntaxFactory.TypeArgumentList(SyntaxFactory.SeparatedList(typeArguments))); } private static QualifiedNameSyntax CreateSystemObject() { return SyntaxFactory.QualifiedName( SyntaxFactory.AliasQualifiedName( CreateGlobalIdentifier(), SyntaxFactory.IdentifierName("System")), SyntaxFactory.IdentifierName("Object")); } private static IdentifierNameSyntax CreateGlobalIdentifier() => SyntaxFactory.IdentifierName(SyntaxFactory.Token(SyntaxKind.GlobalKeyword)); private static TypeSyntax? TryCreateSpecializedNamedTypeSyntax(INamedTypeSymbol symbol) { if (symbol.SpecialType == SpecialType.System_Void) { return SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.VoidKeyword)); } if (symbol.IsTupleType && symbol.TupleElements.Length >= 2) { return CreateTupleTypeSyntax(symbol); } if (symbol.IsNullable()) { // Can't have a nullable of a pointer type. i.e. "int*?" is illegal. var innerType = symbol.TypeArguments.First(); if (innerType.TypeKind != TypeKind.Pointer) { return AddInformationTo( SyntaxFactory.NullableType(innerType.GenerateTypeSyntax()), symbol); } } return null; } private static TupleTypeSyntax CreateTupleTypeSyntax(INamedTypeSymbol symbol) { var list = new SeparatedSyntaxList<TupleElementSyntax>(); foreach (var element in symbol.TupleElements) { var name = element.IsImplicitlyDeclared ? default : SyntaxFactory.Identifier(element.Name); list = list.Add(SyntaxFactory.TupleElement(element.Type.GenerateTypeSyntax(), name)); } return AddInformationTo(SyntaxFactory.TupleType(list), symbol); } public override TypeSyntax VisitNamedType(INamedTypeSymbol symbol) { if (TryCreateNativeIntegerType(symbol, out var typeSyntax)) return typeSyntax; typeSyntax = CreateSimpleTypeSyntax(symbol); if (!(typeSyntax is SimpleNameSyntax)) return typeSyntax; var simpleNameSyntax = (SimpleNameSyntax)typeSyntax; if (symbol.ContainingType != null) { if (symbol.ContainingType.TypeKind != TypeKind.Submission) { var containingTypeSyntax = symbol.ContainingType.Accept(this); if (containingTypeSyntax is NameSyntax name) { typeSyntax = AddInformationTo( SyntaxFactory.QualifiedName(name, simpleNameSyntax), symbol); } else { typeSyntax = AddInformationTo(simpleNameSyntax, symbol); } } } else if (symbol.ContainingNamespace != null) { if (symbol.ContainingNamespace.IsGlobalNamespace) { if (symbol.TypeKind != TypeKind.Error) { typeSyntax = AddGlobalAlias(symbol, simpleNameSyntax); } } else { var container = symbol.ContainingNamespace.Accept(this)!; typeSyntax = AddInformationTo(SyntaxFactory.QualifiedName( (NameSyntax)container, simpleNameSyntax), symbol); } } if (symbol is { IsValueType: false, NullableAnnotation: NullableAnnotation.Annotated }) { // value type with nullable annotation may be composed from unconstrained nullable generic // doesn't mean nullable value type in this case typeSyntax = AddInformationTo(SyntaxFactory.NullableType(typeSyntax), symbol); } return typeSyntax; } public override TypeSyntax VisitNamespace(INamespaceSymbol symbol) { var syntax = AddInformationTo(symbol.Name.ToIdentifierName(), symbol); if (symbol.ContainingNamespace == null) { return syntax; } if (symbol.ContainingNamespace.IsGlobalNamespace) { return AddGlobalAlias(symbol, syntax); } else { var container = symbol.ContainingNamespace.Accept(this)!; return AddInformationTo(SyntaxFactory.QualifiedName( (NameSyntax)container, syntax), symbol); } } /// <summary> /// We always unilaterally add "global::" to all named types/namespaces. This /// will then be trimmed off if possible by calls to /// <see cref="Simplifier.ReduceAsync(Document, OptionSet, CancellationToken)"/> /// </summary> private static TypeSyntax AddGlobalAlias(INamespaceOrTypeSymbol symbol, SimpleNameSyntax syntax) { return AddInformationTo( SyntaxFactory.AliasQualifiedName( CreateGlobalIdentifier(), syntax), symbol); } public override TypeSyntax VisitPointerType(IPointerTypeSymbol symbol) { ThrowIfNameOnly(); return AddInformationTo( SyntaxFactory.PointerType(symbol.PointedAtType.GenerateTypeSyntax()), symbol); } public override TypeSyntax VisitTypeParameter(ITypeParameterSymbol symbol) { TypeSyntax typeSyntax = AddInformationTo(symbol.Name.ToIdentifierName(), symbol); if (symbol is { IsValueType: false, NullableAnnotation: NullableAnnotation.Annotated }) { // value type with nullable annotation may be composed from unconstrained nullable generic // doesn't mean nullable value type in this case typeSyntax = AddInformationTo(SyntaxFactory.NullableType(typeSyntax), symbol); } return typeSyntax; } } } }
// Licensed to the .NET Foundation under one or more agreements. // 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 System.Linq; using System.Threading; using Microsoft.CodeAnalysis.CSharp.CodeGeneration; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Simplification; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Extensions { internal partial class ITypeSymbolExtensions { private class TypeSyntaxGeneratorVisitor : SymbolVisitor<TypeSyntax> { private readonly bool _nameOnly; private static readonly TypeSyntaxGeneratorVisitor NameOnlyInstance = new(nameOnly: true); private static readonly TypeSyntaxGeneratorVisitor NotNameOnlyInstance = new(nameOnly: false); private TypeSyntaxGeneratorVisitor(bool nameOnly) => _nameOnly = nameOnly; public static TypeSyntaxGeneratorVisitor Create(bool nameOnly = false) => nameOnly ? NameOnlyInstance : NotNameOnlyInstance; public override TypeSyntax DefaultVisit(ISymbol node) => throw new NotImplementedException(); private static TTypeSyntax AddInformationTo<TTypeSyntax>(TTypeSyntax syntax, ISymbol symbol) where TTypeSyntax : TypeSyntax { syntax = syntax.WithPrependedLeadingTrivia(SyntaxFactory.ElasticMarker).WithAppendedTrailingTrivia(SyntaxFactory.ElasticMarker); syntax = syntax.WithAdditionalAnnotations(SymbolAnnotation.Create(symbol)); return syntax; } public override TypeSyntax VisitAlias(IAliasSymbol symbol) => AddInformationTo(symbol.Name.ToIdentifierName(), symbol); private void ThrowIfNameOnly() { if (_nameOnly) { throw new InvalidOperationException("This symbol cannot be converted into a NameSyntax"); } } public override TypeSyntax VisitArrayType(IArrayTypeSymbol symbol) { ThrowIfNameOnly(); ITypeSymbol underlyingType = symbol; while (underlyingType is IArrayTypeSymbol innerArray) { underlyingType = innerArray.ElementType; if (underlyingType.NullableAnnotation == NullableAnnotation.Annotated) { // If the inner array we just moved to is also nullable, then // we must terminate the digging now so we produce the syntax for that, // and then append the ranks we passed through at the end. This is because // nullability annotations acts as a "barrier" where we won't reorder array // through. So whereas: // // string[][,] // // is really an array of rank 1 that has an element of rank 2, // // string[]?[,] // // is really an array of rank 2 that has nullable elements of rank 1. break; } } var elementTypeSyntax = underlyingType.GenerateTypeSyntax(); using var _ = ArrayBuilder<ArrayRankSpecifierSyntax>.GetInstance(out var ranks); var arrayType = symbol; while (arrayType != null && !arrayType.Equals(underlyingType)) { ranks.Add(SyntaxFactory.ArrayRankSpecifier( SyntaxFactory.SeparatedList(Enumerable.Repeat<ExpressionSyntax>(SyntaxFactory.OmittedArraySizeExpression(), arrayType.Rank)))); arrayType = arrayType.ElementType as IArrayTypeSymbol; } TypeSyntax arrayTypeSyntax = SyntaxFactory.ArrayType(elementTypeSyntax, ranks.ToSyntaxList()); if (symbol.NullableAnnotation == NullableAnnotation.Annotated) { arrayTypeSyntax = SyntaxFactory.NullableType(arrayTypeSyntax); } return AddInformationTo(arrayTypeSyntax, symbol); } public override TypeSyntax VisitDynamicType(IDynamicTypeSymbol symbol) => AddInformationTo(SyntaxFactory.IdentifierName("dynamic"), symbol); public static bool TryCreateNativeIntegerType(INamedTypeSymbol symbol, [NotNullWhen(true)] out TypeSyntax? syntax) { if (symbol.IsNativeIntegerType) { syntax = SyntaxFactory.IdentifierName(symbol.SpecialType == SpecialType.System_IntPtr ? "nint" : "nuint"); return true; } syntax = null; return false; } public override TypeSyntax VisitFunctionPointerType(IFunctionPointerTypeSymbol symbol) { FunctionPointerCallingConventionSyntax? callingConventionSyntax = null; // For varargs there is no C# syntax. You get a use-site diagnostic if you attempt to use it, and just // making a default-convention symbol is likely good enough. This is only observable through metadata // that always be uncompilable in C# anyway. if (symbol.Signature.CallingConvention != System.Reflection.Metadata.SignatureCallingConvention.Default && symbol.Signature.CallingConvention != System.Reflection.Metadata.SignatureCallingConvention.VarArgs) { var conventionsList = symbol.Signature.CallingConvention switch { System.Reflection.Metadata.SignatureCallingConvention.CDecl => new[] { GetConventionForString("Cdecl") }, System.Reflection.Metadata.SignatureCallingConvention.StdCall => new[] { GetConventionForString("Stdcall") }, System.Reflection.Metadata.SignatureCallingConvention.ThisCall => new[] { GetConventionForString("Thiscall") }, System.Reflection.Metadata.SignatureCallingConvention.FastCall => new[] { GetConventionForString("Fastcall") }, System.Reflection.Metadata.SignatureCallingConvention.Unmanaged => // All types that come from CallingConventionTypes start with "CallConv". We don't want the prefix for the actual // syntax, so strip it off symbol.Signature.UnmanagedCallingConventionTypes.IsEmpty ? null : symbol.Signature.UnmanagedCallingConventionTypes.Select(type => GetConventionForString(type.Name["CallConv".Length..])), _ => throw ExceptionUtilities.UnexpectedValue(symbol.Signature.CallingConvention), }; callingConventionSyntax = SyntaxFactory.FunctionPointerCallingConvention( SyntaxFactory.Token(SyntaxKind.UnmanagedKeyword), conventionsList is object ? SyntaxFactory.FunctionPointerUnmanagedCallingConventionList(SyntaxFactory.SeparatedList(conventionsList)) : null); static FunctionPointerUnmanagedCallingConventionSyntax GetConventionForString(string identifier) => SyntaxFactory.FunctionPointerUnmanagedCallingConvention(SyntaxFactory.Identifier(identifier)); } var parameters = symbol.Signature.Parameters.Select(p => (p.Type, RefKindModifiers: CSharpSyntaxGeneratorInternal.GetParameterModifiers(p.RefKind))) .Concat(SpecializedCollections.SingletonEnumerable(( Type: symbol.Signature.ReturnType, RefKindModifiers: CSharpSyntaxGeneratorInternal.GetParameterModifiers(symbol.Signature.RefKind, forFunctionPointerReturnParameter: true)))) .SelectAsArray(t => SyntaxFactory.FunctionPointerParameter(t.Type.GenerateTypeSyntax()).WithModifiers(t.RefKindModifiers)); return AddInformationTo( SyntaxFactory.FunctionPointerType(callingConventionSyntax, SyntaxFactory.FunctionPointerParameterList(SyntaxFactory.SeparatedList(parameters))), symbol); } public TypeSyntax CreateSimpleTypeSyntax(INamedTypeSymbol symbol) { if (!_nameOnly) { var syntax = TryCreateSpecializedNamedTypeSyntax(symbol); if (syntax != null) return syntax; } if (symbol.IsTupleType && symbol.TupleUnderlyingType != null && !symbol.Equals(symbol.TupleUnderlyingType)) { return CreateSimpleTypeSyntax(symbol.TupleUnderlyingType); } if (symbol.Name == string.Empty || symbol.IsAnonymousType) { return CreateSystemObject(); } if (symbol.TypeParameters.Length == 0) { if (symbol.TypeKind == TypeKind.Error && symbol.Name == "var") { return CreateSystemObject(); } return symbol.Name.ToIdentifierName(); } var typeArguments = symbol.IsUnboundGenericType ? Enumerable.Repeat((TypeSyntax)SyntaxFactory.OmittedTypeArgument(), symbol.TypeArguments.Length) : symbol.TypeArguments.SelectAsArray(t => t.GenerateTypeSyntax()); return SyntaxFactory.GenericName( symbol.Name.ToIdentifierToken(), SyntaxFactory.TypeArgumentList(SyntaxFactory.SeparatedList(typeArguments))); } private static QualifiedNameSyntax CreateSystemObject() { return SyntaxFactory.QualifiedName( SyntaxFactory.AliasQualifiedName( CreateGlobalIdentifier(), SyntaxFactory.IdentifierName("System")), SyntaxFactory.IdentifierName("Object")); } private static IdentifierNameSyntax CreateGlobalIdentifier() => SyntaxFactory.IdentifierName(SyntaxFactory.Token(SyntaxKind.GlobalKeyword)); private static TypeSyntax? TryCreateSpecializedNamedTypeSyntax(INamedTypeSymbol symbol) { if (symbol.SpecialType == SpecialType.System_Void) { return SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.VoidKeyword)); } if (symbol.IsTupleType && symbol.TupleElements.Length >= 2) { return CreateTupleTypeSyntax(symbol); } if (symbol.IsNullable()) { // Can't have a nullable of a pointer type. i.e. "int*?" is illegal. var innerType = symbol.TypeArguments.First(); if (innerType.TypeKind != TypeKind.Pointer) { return AddInformationTo( SyntaxFactory.NullableType(innerType.GenerateTypeSyntax()), symbol); } } return null; } private static TupleTypeSyntax CreateTupleTypeSyntax(INamedTypeSymbol symbol) { var list = new SeparatedSyntaxList<TupleElementSyntax>(); foreach (var element in symbol.TupleElements) { var name = element.IsImplicitlyDeclared ? default : SyntaxFactory.Identifier(element.Name); list = list.Add(SyntaxFactory.TupleElement(element.Type.GenerateTypeSyntax(), name)); } return AddInformationTo(SyntaxFactory.TupleType(list), symbol); } public override TypeSyntax VisitNamedType(INamedTypeSymbol symbol) { if (TryCreateNativeIntegerType(symbol, out var typeSyntax)) return typeSyntax; typeSyntax = CreateSimpleTypeSyntax(symbol); if (!(typeSyntax is SimpleNameSyntax)) return typeSyntax; var simpleNameSyntax = (SimpleNameSyntax)typeSyntax; if (symbol.ContainingType != null) { if (symbol.ContainingType.TypeKind != TypeKind.Submission) { var containingTypeSyntax = symbol.ContainingType.Accept(this); if (containingTypeSyntax is NameSyntax name) { typeSyntax = AddInformationTo( SyntaxFactory.QualifiedName(name, simpleNameSyntax), symbol); } else { typeSyntax = AddInformationTo(simpleNameSyntax, symbol); } } } else if (symbol.ContainingNamespace != null) { if (symbol.ContainingNamespace.IsGlobalNamespace) { if (symbol.TypeKind != TypeKind.Error) { typeSyntax = AddGlobalAlias(symbol, simpleNameSyntax); } } else { var container = symbol.ContainingNamespace.Accept(this)!; typeSyntax = AddInformationTo(SyntaxFactory.QualifiedName( (NameSyntax)container, simpleNameSyntax), symbol); } } if (symbol is { IsValueType: false, NullableAnnotation: NullableAnnotation.Annotated }) { // value type with nullable annotation may be composed from unconstrained nullable generic // doesn't mean nullable value type in this case typeSyntax = AddInformationTo(SyntaxFactory.NullableType(typeSyntax), symbol); } return typeSyntax; } public override TypeSyntax VisitNamespace(INamespaceSymbol symbol) { var syntax = AddInformationTo(symbol.Name.ToIdentifierName(), symbol); if (symbol.ContainingNamespace == null) { return syntax; } if (symbol.ContainingNamespace.IsGlobalNamespace) { return AddGlobalAlias(symbol, syntax); } else { var container = symbol.ContainingNamespace.Accept(this)!; return AddInformationTo(SyntaxFactory.QualifiedName( (NameSyntax)container, syntax), symbol); } } /// <summary> /// We always unilaterally add "global::" to all named types/namespaces. This /// will then be trimmed off if possible by calls to /// <see cref="Simplifier.ReduceAsync(Document, OptionSet, CancellationToken)"/> /// </summary> private static TypeSyntax AddGlobalAlias(INamespaceOrTypeSymbol symbol, SimpleNameSyntax syntax) { return AddInformationTo( SyntaxFactory.AliasQualifiedName( CreateGlobalIdentifier(), syntax), symbol); } public override TypeSyntax VisitPointerType(IPointerTypeSymbol symbol) { ThrowIfNameOnly(); return AddInformationTo( SyntaxFactory.PointerType(symbol.PointedAtType.GenerateTypeSyntax()), symbol); } public override TypeSyntax VisitTypeParameter(ITypeParameterSymbol symbol) { TypeSyntax typeSyntax = AddInformationTo(symbol.Name.ToIdentifierName(), symbol); if (symbol is { IsValueType: false, NullableAnnotation: NullableAnnotation.Annotated }) { // value type with nullable annotation may be composed from unconstrained nullable generic // doesn't mean nullable value type in this case typeSyntax = AddInformationTo(SyntaxFactory.NullableType(typeSyntax), symbol); } return typeSyntax; } } } }
-1
dotnet/roslyn
55,428
Test adding nested namespaces
Fixes https://github.com/dotnet/roslyn/issues/54939 The "workaround" that's already implemented is actually the correct behavior.
tmat
2021-08-05T01:19:03Z
2021-08-11T18:38:54Z
bc874ebc5111a2a33221409f895953b1536f6612
1cbbd423e17b186a8f1de89febb4db9a386d180d
Test adding nested namespaces. Fixes https://github.com/dotnet/roslyn/issues/54939 The "workaround" that's already implemented is actually the correct behavior.
./src/Features/VisualBasic/Portable/Microsoft.CodeAnalysis.VisualBasic.Features.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 Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Library</OutputType> <TargetFrameworks>netcoreapp3.1;netstandard2.0</TargetFrameworks> <RootNamespace></RootNamespace> <ApplyNgenOptimization>partial</ApplyNgenOptimization> <!-- NuGet --> <IsPackable>true</IsPackable> <PackageDescription> .NET Compiler Platform ("Roslyn") support for creating Visual Basic editing experiences. </PackageDescription> </PropertyGroup> <ItemGroup Label="Project References"> <ProjectReference Include="..\..\..\Compilers\Core\Portable\Microsoft.CodeAnalysis.csproj" /> <ProjectReference Include="..\..\..\Compilers\VisualBasic\Portable\Microsoft.CodeAnalysis.VisualBasic.vbproj" /> <ProjectReference Include="..\..\..\Workspaces\Core\Portable\Microsoft.CodeAnalysis.Workspaces.csproj" /> <ProjectReference Include="..\..\Core\Portable\Microsoft.CodeAnalysis.Features.csproj" /> <ProjectReference Include="..\..\..\Workspaces\VisualBasic\Portable\Microsoft.CodeAnalysis.VisualBasic.Workspaces.vbproj" /> </ItemGroup> <ItemGroup> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.VisualBasic.EditorFeatures" /> <InternalsVisibleTo Include="Microsoft.VisualStudio.LanguageServices.VisualBasic" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.Remote.Workspaces" /> <!-- BEGIN MONODEVELOP These MonoDevelop dependencies don't ship with Visual Studio, so can't break our binary insertions and are exempted from the ExternalAccess adapter assembly policies. --> <InternalsVisibleTo Include="MonoDevelop.VBNetBinding" Key="$(MonoDevelopKey)" LoadsWithinVisualStudio="false" /> <InternalsVisibleTo Include="MonoDevelop.VBNetBinding.Tests" Key="$(MonoDevelopKey)" LoadsWithinVisualStudio="false" /> <!-- END MONODEVELOP --> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.EditorFeatures.UnitTests" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.EditorFeatures2.UnitTests" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.VisualBasic.EditorFeatures.UnitTests" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.Workspaces.UnitTests" /> <InternalsVisibleTo Include="Microsoft.VisualStudio.LanguageServices.UnitTests" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.EditorFeatures.DiagnosticsTests.Utilities" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.EditorFeatures.Test.Utilities" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.EditorFeatures.Test.Utilities2" /> <InternalsVisibleTo Include="Roslyn.VisualStudio.Next.UnitTests" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.CodeStyle.LegacyTestFramework.UnitTestUtilities" /> </ItemGroup> <ItemGroup> <Import Include="Microsoft.CodeAnalysis.Shared.Extensions" /> <Import Include="Microsoft.CodeAnalysis.Shared.Utilities" /> <Import Include="Microsoft.CodeAnalysis.VisualBasic.Extensions" /> <Import Include="Roslyn.Utilities" /> <Import Include="System.Threading.Tasks" /> <Import Include="System.Xml.Linq" /> </ItemGroup> <ItemGroup> <Compile Include="..\..\..\Compilers\VisualBasic\Portable\Syntax\LambdaUtilities.vb"> <Link>InternalUtilities\LambdaUtilities.vb</Link> </Compile> </ItemGroup> <ItemGroup> <EmbeddedResource Update="VBFeaturesResources.resx" GenerateSource="true" Namespace="Microsoft.CodeAnalysis.VisualBasic" /> </ItemGroup> <ItemGroup> <Folder Include="My Project\" /> </ItemGroup> <ItemGroup> <PublicAPI Include="PublicAPI.Shipped.txt" /> <PublicAPI Include="PublicAPI.Unshipped.txt" /> </ItemGroup> <Import Project="..\..\..\Compilers\VisualBasic\BasicAnalyzerDriver\BasicAnalyzerDriver.projitems" Label="Shared" /> <Import Project="..\..\..\Analyzers\VisualBasic\Analyzers\VisualBasicAnalyzers.projitems" Label="Shared" /> <Import Project="..\..\..\Analyzers\VisualBasic\CodeFixes\VisualBasicCodeFixes.projitems" Label="Shared" /> </Project>
<?xml version="1.0" encoding="utf-8"?> <!-- Licensed to the .NET Foundation under one or more agreements. The .NET Foundation licenses this file to you under the MIT license. See the LICENSE file in the project root for more information. --> <Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Library</OutputType> <TargetFrameworks>netcoreapp3.1;netstandard2.0</TargetFrameworks> <RootNamespace></RootNamespace> <ApplyNgenOptimization>partial</ApplyNgenOptimization> <!-- NuGet --> <IsPackable>true</IsPackable> <PackageDescription> .NET Compiler Platform ("Roslyn") support for creating Visual Basic editing experiences. </PackageDescription> </PropertyGroup> <ItemGroup Label="Project References"> <ProjectReference Include="..\..\..\Compilers\Core\Portable\Microsoft.CodeAnalysis.csproj" /> <ProjectReference Include="..\..\..\Compilers\VisualBasic\Portable\Microsoft.CodeAnalysis.VisualBasic.vbproj" /> <ProjectReference Include="..\..\..\Workspaces\Core\Portable\Microsoft.CodeAnalysis.Workspaces.csproj" /> <ProjectReference Include="..\..\Core\Portable\Microsoft.CodeAnalysis.Features.csproj" /> <ProjectReference Include="..\..\..\Workspaces\VisualBasic\Portable\Microsoft.CodeAnalysis.VisualBasic.Workspaces.vbproj" /> </ItemGroup> <ItemGroup> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.VisualBasic.EditorFeatures" /> <InternalsVisibleTo Include="Microsoft.VisualStudio.LanguageServices.VisualBasic" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.Remote.Workspaces" /> <!-- BEGIN MONODEVELOP These MonoDevelop dependencies don't ship with Visual Studio, so can't break our binary insertions and are exempted from the ExternalAccess adapter assembly policies. --> <InternalsVisibleTo Include="MonoDevelop.VBNetBinding" Key="$(MonoDevelopKey)" LoadsWithinVisualStudio="false" /> <InternalsVisibleTo Include="MonoDevelop.VBNetBinding.Tests" Key="$(MonoDevelopKey)" LoadsWithinVisualStudio="false" /> <!-- END MONODEVELOP --> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.EditorFeatures.UnitTests" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.EditorFeatures2.UnitTests" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.VisualBasic.EditorFeatures.UnitTests" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.Workspaces.UnitTests" /> <InternalsVisibleTo Include="Microsoft.VisualStudio.LanguageServices.UnitTests" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.EditorFeatures.DiagnosticsTests.Utilities" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.EditorFeatures.Test.Utilities" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.EditorFeatures.Test.Utilities2" /> <InternalsVisibleTo Include="Roslyn.VisualStudio.Next.UnitTests" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.CodeStyle.LegacyTestFramework.UnitTestUtilities" /> </ItemGroup> <ItemGroup> <Import Include="Microsoft.CodeAnalysis.Shared.Extensions" /> <Import Include="Microsoft.CodeAnalysis.Shared.Utilities" /> <Import Include="Microsoft.CodeAnalysis.VisualBasic.Extensions" /> <Import Include="Roslyn.Utilities" /> <Import Include="System.Threading.Tasks" /> <Import Include="System.Xml.Linq" /> </ItemGroup> <ItemGroup> <Compile Include="..\..\..\Compilers\VisualBasic\Portable\Syntax\LambdaUtilities.vb"> <Link>InternalUtilities\LambdaUtilities.vb</Link> </Compile> </ItemGroup> <ItemGroup> <EmbeddedResource Update="VBFeaturesResources.resx" GenerateSource="true" Namespace="Microsoft.CodeAnalysis.VisualBasic" /> </ItemGroup> <ItemGroup> <Folder Include="My Project\" /> </ItemGroup> <ItemGroup> <PublicAPI Include="PublicAPI.Shipped.txt" /> <PublicAPI Include="PublicAPI.Unshipped.txt" /> </ItemGroup> <Import Project="..\..\..\Compilers\VisualBasic\BasicAnalyzerDriver\BasicAnalyzerDriver.projitems" Label="Shared" /> <Import Project="..\..\..\Analyzers\VisualBasic\Analyzers\VisualBasicAnalyzers.projitems" Label="Shared" /> <Import Project="..\..\..\Analyzers\VisualBasic\CodeFixes\VisualBasicCodeFixes.projitems" Label="Shared" /> </Project>
-1
dotnet/roslyn
55,428
Test adding nested namespaces
Fixes https://github.com/dotnet/roslyn/issues/54939 The "workaround" that's already implemented is actually the correct behavior.
tmat
2021-08-05T01:19:03Z
2021-08-11T18:38:54Z
bc874ebc5111a2a33221409f895953b1536f6612
1cbbd423e17b186a8f1de89febb4db9a386d180d
Test adding nested namespaces. Fixes https://github.com/dotnet/roslyn/issues/54939 The "workaround" that's already implemented is actually the correct behavior.
./src/Compilers/VisualBasic/Portable/Analysis/FlowAnalysis/ControlFlowPass.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System Imports System.Collections.Generic Imports System.Linq Imports System.Text Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic Partial Friend Class ControlFlowPass Inherits AbstractFlowPass(Of LocalState) Protected _convertInsufficientExecutionStackExceptionToCancelledByStackGuardException As Boolean = False ' By default, just let the original exception to bubble up. Friend Sub New(info As FlowAnalysisInfo, suppressConstExpressionsSupport As Boolean) MyBase.New(info, suppressConstExpressionsSupport) End Sub Friend Sub New(info As FlowAnalysisInfo, region As FlowAnalysisRegionInfo, suppressConstantExpressionsSupport As Boolean) MyBase.New(info, region, suppressConstantExpressionsSupport, False) End Sub Protected Overrides Function ReachableState() As LocalState Return New LocalState(True, False) End Function Protected Overrides Function UnreachableState() As LocalState Return New LocalState(False, Me.State.Reported) End Function Protected Overrides Sub Visit(node As BoundNode, dontLeaveRegion As Boolean) ' Expressions must be visited if regions can be on expression boundaries. If Not (TypeOf node Is BoundExpression) Then MyBase.Visit(node, dontLeaveRegion) End If End Sub ''' <summary> ''' Perform control flow analysis, reporting all necessary diagnostics. Returns true if the end of ''' the body might be reachable.. ''' </summary> ''' <param name = "diagnostics"></param> ''' <returns></returns> Public Overloads Shared Function Analyze(info As FlowAnalysisInfo, diagnostics As DiagnosticBag, suppressConstantExpressionsSupport As Boolean) As Boolean Dim walker = New ControlFlowPass(info, suppressConstantExpressionsSupport) If diagnostics IsNot Nothing Then walker._convertInsufficientExecutionStackExceptionToCancelledByStackGuardException = True End If Try walker.Analyze() If diagnostics IsNot Nothing Then diagnostics.AddRange(walker.diagnostics) End If Return walker.State.Alive Catch ex As CancelledByStackGuardException When diagnostics IsNot Nothing ex.AddAnError(diagnostics) Return True Finally walker.Free() End Try End Function Protected Overrides Function ConvertInsufficientExecutionStackExceptionToCancelledByStackGuardException() As Boolean Return _convertInsufficientExecutionStackExceptionToCancelledByStackGuardException End Function Protected Overrides Sub VisitStatement(statement As BoundStatement) Select Case statement.Kind Case BoundKind.LabelStatement, BoundKind.NoOpStatement, BoundKind.Block Case Else If Not Me.State.Alive AndAlso Not Me.State.Reported Then Select Case statement.Kind Case BoundKind.LocalDeclaration ' Declarations by themselves are not executable. Only report one as unreachable if it has an initializer. Dim decl = TryCast(statement, BoundLocalDeclaration) If decl.InitializerOpt IsNot Nothing Then ' TODO: uncomment the following line 'Me.diagnostics.Add(ERRID.WRN_UnreachableCode, decl.InitializerOpt.Syntax.GetLocation()) Me.State.Reported = True End If Case BoundKind.ReturnStatement ' VB always adds a return at the end of all methods. It may end up being ' marked as unreachable if the code has an explicit return in it. The final return is ' always reachable because all returns jump to the final synthetic return. Dim returnStmt = TryCast(statement, BoundReturnStatement) If Not returnStmt.IsEndOfMethodReturn Then ' TODO: uncomment the following line 'Me.diagnostics.Add(ERRID.WRN_UnreachableCode, statement.Syntax.GetLocation()) Me.State.Reported = True End If Case BoundKind.DimStatement ' Don't report anything, warnings will be reported when ' declarations inside this Dim statement are processed Case Else ' TODO: uncomment the following line 'Me.diagnostics.Add(ERRID.WRN_UnreachableCode, statement.Syntax.GetLocation()) Me.State.Reported = True End Select End If End Select MyBase.VisitStatement(statement) End Sub Protected Overrides Sub VisitTryBlock(tryBlock As BoundStatement, node As BoundTryStatement, ByRef tryState As LocalState) If node.CatchBlocks.IsEmpty Then MyBase.VisitTryBlock(tryBlock, node, tryState) Else Dim oldPendings As SavedPending = Me.SavePending() MyBase.VisitTryBlock(tryBlock, node, tryState) ' NOTE: C# generates errors for 'yield return' inside try statement here; ' it is valid in VB though. Me.RestorePending(oldPendings, mergeLabelsSeen:=True) End If End Sub Protected Overrides Sub VisitCatchBlock(node As BoundCatchBlock, ByRef finallyState As LocalState) Dim oldPendings As SavedPending = Me.SavePending() MyBase.VisitCatchBlock(node, finallyState) For Each branch In Me.PendingBranches if branch.Branch.Kind = BoundKind.YieldStatement Me.diagnostics.Add(ERRID.ERR_BadYieldInTryHandler, branch.Branch.Syntax.GetLocation) End If Next ' NOTE: VB generates error ERR_GotoIntoTryHandler in binding, but ' we still want to 'nest' pendings' state for catch statements Me.RestorePending(oldPendings) End Sub Protected Overrides Sub VisitFinallyBlock(finallyBlock As BoundStatement, ByRef endState As LocalState) Dim oldPending1 As SavedPending = SavePending() ' we do not support branches into a finally block Dim oldPending2 As SavedPending = SavePending() ' track only the branches out of the finally block MyBase.VisitFinallyBlock(finallyBlock, endState) RestorePending(oldPending2) ' resolve branches that remain within the finally block For Each branch In Me.PendingBranches Dim syntax = branch.Branch.Syntax Dim errorLocation As SyntaxNodeOrToken Dim errId As ERRID If branch.Branch.Kind = BoundKind.YieldStatement errId = errId.ERR_BadYieldInTryHandler errorLocation = syntax else errId = errId.ERR_BranchOutOfFinally If syntax.Kind = SyntaxKind.GoToStatement Then errorLocation = DirectCast(syntax, GoToStatementSyntax).Label Else errorLocation = syntax End If End If Me.diagnostics.Add(errId, errorLocation.GetLocation()) Next RestorePending(oldPending1) End Sub End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System Imports System.Collections.Generic Imports System.Linq Imports System.Text Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic Partial Friend Class ControlFlowPass Inherits AbstractFlowPass(Of LocalState) Protected _convertInsufficientExecutionStackExceptionToCancelledByStackGuardException As Boolean = False ' By default, just let the original exception to bubble up. Friend Sub New(info As FlowAnalysisInfo, suppressConstExpressionsSupport As Boolean) MyBase.New(info, suppressConstExpressionsSupport) End Sub Friend Sub New(info As FlowAnalysisInfo, region As FlowAnalysisRegionInfo, suppressConstantExpressionsSupport As Boolean) MyBase.New(info, region, suppressConstantExpressionsSupport, False) End Sub Protected Overrides Function ReachableState() As LocalState Return New LocalState(True, False) End Function Protected Overrides Function UnreachableState() As LocalState Return New LocalState(False, Me.State.Reported) End Function Protected Overrides Sub Visit(node As BoundNode, dontLeaveRegion As Boolean) ' Expressions must be visited if regions can be on expression boundaries. If Not (TypeOf node Is BoundExpression) Then MyBase.Visit(node, dontLeaveRegion) End If End Sub ''' <summary> ''' Perform control flow analysis, reporting all necessary diagnostics. Returns true if the end of ''' the body might be reachable.. ''' </summary> ''' <param name = "diagnostics"></param> ''' <returns></returns> Public Overloads Shared Function Analyze(info As FlowAnalysisInfo, diagnostics As DiagnosticBag, suppressConstantExpressionsSupport As Boolean) As Boolean Dim walker = New ControlFlowPass(info, suppressConstantExpressionsSupport) If diagnostics IsNot Nothing Then walker._convertInsufficientExecutionStackExceptionToCancelledByStackGuardException = True End If Try walker.Analyze() If diagnostics IsNot Nothing Then diagnostics.AddRange(walker.diagnostics) End If Return walker.State.Alive Catch ex As CancelledByStackGuardException When diagnostics IsNot Nothing ex.AddAnError(diagnostics) Return True Finally walker.Free() End Try End Function Protected Overrides Function ConvertInsufficientExecutionStackExceptionToCancelledByStackGuardException() As Boolean Return _convertInsufficientExecutionStackExceptionToCancelledByStackGuardException End Function Protected Overrides Sub VisitStatement(statement As BoundStatement) Select Case statement.Kind Case BoundKind.LabelStatement, BoundKind.NoOpStatement, BoundKind.Block Case Else If Not Me.State.Alive AndAlso Not Me.State.Reported Then Select Case statement.Kind Case BoundKind.LocalDeclaration ' Declarations by themselves are not executable. Only report one as unreachable if it has an initializer. Dim decl = TryCast(statement, BoundLocalDeclaration) If decl.InitializerOpt IsNot Nothing Then ' TODO: uncomment the following line 'Me.diagnostics.Add(ERRID.WRN_UnreachableCode, decl.InitializerOpt.Syntax.GetLocation()) Me.State.Reported = True End If Case BoundKind.ReturnStatement ' VB always adds a return at the end of all methods. It may end up being ' marked as unreachable if the code has an explicit return in it. The final return is ' always reachable because all returns jump to the final synthetic return. Dim returnStmt = TryCast(statement, BoundReturnStatement) If Not returnStmt.IsEndOfMethodReturn Then ' TODO: uncomment the following line 'Me.diagnostics.Add(ERRID.WRN_UnreachableCode, statement.Syntax.GetLocation()) Me.State.Reported = True End If Case BoundKind.DimStatement ' Don't report anything, warnings will be reported when ' declarations inside this Dim statement are processed Case Else ' TODO: uncomment the following line 'Me.diagnostics.Add(ERRID.WRN_UnreachableCode, statement.Syntax.GetLocation()) Me.State.Reported = True End Select End If End Select MyBase.VisitStatement(statement) End Sub Protected Overrides Sub VisitTryBlock(tryBlock As BoundStatement, node As BoundTryStatement, ByRef tryState As LocalState) If node.CatchBlocks.IsEmpty Then MyBase.VisitTryBlock(tryBlock, node, tryState) Else Dim oldPendings As SavedPending = Me.SavePending() MyBase.VisitTryBlock(tryBlock, node, tryState) ' NOTE: C# generates errors for 'yield return' inside try statement here; ' it is valid in VB though. Me.RestorePending(oldPendings, mergeLabelsSeen:=True) End If End Sub Protected Overrides Sub VisitCatchBlock(node As BoundCatchBlock, ByRef finallyState As LocalState) Dim oldPendings As SavedPending = Me.SavePending() MyBase.VisitCatchBlock(node, finallyState) For Each branch In Me.PendingBranches if branch.Branch.Kind = BoundKind.YieldStatement Me.diagnostics.Add(ERRID.ERR_BadYieldInTryHandler, branch.Branch.Syntax.GetLocation) End If Next ' NOTE: VB generates error ERR_GotoIntoTryHandler in binding, but ' we still want to 'nest' pendings' state for catch statements Me.RestorePending(oldPendings) End Sub Protected Overrides Sub VisitFinallyBlock(finallyBlock As BoundStatement, ByRef endState As LocalState) Dim oldPending1 As SavedPending = SavePending() ' we do not support branches into a finally block Dim oldPending2 As SavedPending = SavePending() ' track only the branches out of the finally block MyBase.VisitFinallyBlock(finallyBlock, endState) RestorePending(oldPending2) ' resolve branches that remain within the finally block For Each branch In Me.PendingBranches Dim syntax = branch.Branch.Syntax Dim errorLocation As SyntaxNodeOrToken Dim errId As ERRID If branch.Branch.Kind = BoundKind.YieldStatement errId = errId.ERR_BadYieldInTryHandler errorLocation = syntax else errId = errId.ERR_BranchOutOfFinally If syntax.Kind = SyntaxKind.GoToStatement Then errorLocation = DirectCast(syntax, GoToStatementSyntax).Label Else errorLocation = syntax End If End If Me.diagnostics.Add(errId, errorLocation.GetLocation()) Next RestorePending(oldPending1) End Sub End Class End Namespace
-1
dotnet/roslyn
55,428
Test adding nested namespaces
Fixes https://github.com/dotnet/roslyn/issues/54939 The "workaround" that's already implemented is actually the correct behavior.
tmat
2021-08-05T01:19:03Z
2021-08-11T18:38:54Z
bc874ebc5111a2a33221409f895953b1536f6612
1cbbd423e17b186a8f1de89febb4db9a386d180d
Test adding nested namespaces. Fixes https://github.com/dotnet/roslyn/issues/54939 The "workaround" that's already implemented is actually the correct behavior.
./src/Workspaces/Core/MSBuild/MSBuild/CSharp/CSharpProjectFileLoaderFactory.cs
// Licensed to the .NET Foundation under one or more agreements. // 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; using Microsoft.CodeAnalysis.MSBuild; namespace Microsoft.CodeAnalysis.CSharp { [Shared] [ExportLanguageServiceFactory(typeof(IProjectFileLoader), LanguageNames.CSharp)] [ProjectFileExtension("csproj")] internal class CSharpProjectFileLoaderFactory : ILanguageServiceFactory { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public CSharpProjectFileLoaderFactory() { } public ILanguageService CreateLanguageService(HostLanguageServices languageServices) { return new CSharpProjectFileLoader(); } } }
// Licensed to the .NET Foundation under one or more agreements. // 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; using Microsoft.CodeAnalysis.MSBuild; namespace Microsoft.CodeAnalysis.CSharp { [Shared] [ExportLanguageServiceFactory(typeof(IProjectFileLoader), LanguageNames.CSharp)] [ProjectFileExtension("csproj")] internal class CSharpProjectFileLoaderFactory : ILanguageServiceFactory { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public CSharpProjectFileLoaderFactory() { } public ILanguageService CreateLanguageService(HostLanguageServices languageServices) { return new CSharpProjectFileLoader(); } } }
-1
dotnet/roslyn
55,428
Test adding nested namespaces
Fixes https://github.com/dotnet/roslyn/issues/54939 The "workaround" that's already implemented is actually the correct behavior.
tmat
2021-08-05T01:19:03Z
2021-08-11T18:38:54Z
bc874ebc5111a2a33221409f895953b1536f6612
1cbbd423e17b186a8f1de89febb4db9a386d180d
Test adding nested namespaces. Fixes https://github.com/dotnet/roslyn/issues/54939 The "workaround" that's already implemented is actually the correct behavior.
./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,428
Test adding nested namespaces
Fixes https://github.com/dotnet/roslyn/issues/54939 The "workaround" that's already implemented is actually the correct behavior.
tmat
2021-08-05T01:19:03Z
2021-08-11T18:38:54Z
bc874ebc5111a2a33221409f895953b1536f6612
1cbbd423e17b186a8f1de89febb4db9a386d180d
Test adding nested namespaces. Fixes https://github.com/dotnet/roslyn/issues/54939 The "workaround" that's already implemented is actually the correct behavior.
./src/Features/Core/Portable/FindUsages/IRemoteFindUsagesService.cs
// Licensed to the .NET Foundation under one or more agreements. // 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.Composition; using System.Runtime.Serialization; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.FindSymbols; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Remote; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.FindUsages { internal interface IRemoteFindUsagesService { internal interface ICallback { ValueTask AddItemsAsync(RemoteServiceCallbackId callbackId, int count, CancellationToken cancellationToken); ValueTask ItemCompletedAsync(RemoteServiceCallbackId callbackId, CancellationToken cancellationToken); ValueTask ReportMessageAsync(RemoteServiceCallbackId callbackId, string message, CancellationToken cancellationToken); ValueTask SetSearchTitleAsync(RemoteServiceCallbackId callbackId, string title, CancellationToken cancellationToken); ValueTask OnDefinitionFoundAsync(RemoteServiceCallbackId callbackId, SerializableDefinitionItem definition, CancellationToken cancellationToken); ValueTask OnReferenceFoundAsync(RemoteServiceCallbackId callbackId, SerializableSourceReferenceItem reference, CancellationToken cancellationToken); } ValueTask FindReferencesAsync( PinnedSolutionInfo solutionInfo, RemoteServiceCallbackId callbackId, SerializableSymbolAndProjectId symbolAndProjectId, FindReferencesSearchOptions options, CancellationToken cancellationToken); ValueTask FindImplementationsAsync( PinnedSolutionInfo solutionInfo, RemoteServiceCallbackId callbackId, SerializableSymbolAndProjectId symbolAndProjectId, CancellationToken cancellationToken); } [ExportRemoteServiceCallbackDispatcher(typeof(IRemoteFindUsagesService)), Shared] internal sealed class FindUsagesServerCallbackDispatcher : RemoteServiceCallbackDispatcher, IRemoteFindUsagesService.ICallback { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public FindUsagesServerCallbackDispatcher() { } private new FindUsagesServerCallback GetCallback(RemoteServiceCallbackId callbackId) => (FindUsagesServerCallback)base.GetCallback(callbackId); public ValueTask AddItemsAsync(RemoteServiceCallbackId callbackId, int count, CancellationToken cancellationToken) => GetCallback(callbackId).AddItemsAsync(count, cancellationToken); public ValueTask ItemCompletedAsync(RemoteServiceCallbackId callbackId, CancellationToken cancellationToken) => GetCallback(callbackId).ItemCompletedAsync(cancellationToken); public ValueTask OnDefinitionFoundAsync(RemoteServiceCallbackId callbackId, SerializableDefinitionItem definition, CancellationToken cancellationToken) => GetCallback(callbackId).OnDefinitionFoundAsync(definition, cancellationToken); public ValueTask OnReferenceFoundAsync(RemoteServiceCallbackId callbackId, SerializableSourceReferenceItem reference, CancellationToken cancellationToken) => GetCallback(callbackId).OnReferenceFoundAsync(reference, cancellationToken); public ValueTask ReportMessageAsync(RemoteServiceCallbackId callbackId, string message, CancellationToken cancellationToken) => GetCallback(callbackId).ReportMessageAsync(message, cancellationToken); public ValueTask SetSearchTitleAsync(RemoteServiceCallbackId callbackId, string title, CancellationToken cancellationToken) => GetCallback(callbackId).SetSearchTitleAsync(title, cancellationToken); } internal sealed class FindUsagesServerCallback { private readonly Solution _solution; private readonly IFindUsagesContext _context; private readonly Dictionary<int, DefinitionItem> _idToDefinition = new(); public FindUsagesServerCallback(Solution solution, IFindUsagesContext context) { _solution = solution; _context = context; } public ValueTask AddItemsAsync(int count, CancellationToken cancellationToken) => _context.ProgressTracker.AddItemsAsync(count, cancellationToken); public ValueTask ItemCompletedAsync(CancellationToken cancellationToken) => _context.ProgressTracker.ItemCompletedAsync(cancellationToken); public ValueTask ReportMessageAsync(string message, CancellationToken cancellationToken) => _context.ReportMessageAsync(message, cancellationToken); public ValueTask SetSearchTitleAsync(string title, CancellationToken cancellationToken) => _context.SetSearchTitleAsync(title, cancellationToken); public async ValueTask OnDefinitionFoundAsync(SerializableDefinitionItem definition, CancellationToken cancellationToken) { var id = definition.Id; var rehydrated = await definition.RehydrateAsync(_solution, cancellationToken).ConfigureAwait(false); lock (_idToDefinition) { _idToDefinition.Add(id, rehydrated); } await _context.OnDefinitionFoundAsync(rehydrated, cancellationToken).ConfigureAwait(false); } public async ValueTask OnReferenceFoundAsync(SerializableSourceReferenceItem reference, CancellationToken cancellationToken) { var rehydrated = await reference.RehydrateAsync(_solution, GetDefinition(reference.DefinitionId), cancellationToken).ConfigureAwait(false); await _context.OnReferenceFoundAsync(rehydrated, cancellationToken).ConfigureAwait(false); } private DefinitionItem GetDefinition(int definitionId) { lock (_idToDefinition) { Contract.ThrowIfFalse(_idToDefinition.ContainsKey(definitionId)); return _idToDefinition[definitionId]; } } } [DataContract] internal readonly struct SerializableDocumentSpan { [DataMember(Order = 0)] public readonly DocumentId DocumentId; [DataMember(Order = 1)] public readonly TextSpan SourceSpan; public SerializableDocumentSpan(DocumentId documentId, TextSpan sourceSpan) { DocumentId = documentId; SourceSpan = sourceSpan; } public static SerializableDocumentSpan Dehydrate(DocumentSpan documentSpan) => new(documentSpan.Document.Id, documentSpan.SourceSpan); public async ValueTask<DocumentSpan> RehydrateAsync(Solution solution, CancellationToken cancellationToken) { var document = solution.GetDocument(DocumentId) ?? await solution.GetSourceGeneratedDocumentAsync(DocumentId, cancellationToken).ConfigureAwait(false); Contract.ThrowIfNull(document); return new DocumentSpan(document, SourceSpan); } } [DataContract] internal readonly struct SerializableDefinitionItem { [DataMember(Order = 0)] public readonly int Id; [DataMember(Order = 1)] public readonly ImmutableArray<string> Tags; [DataMember(Order = 2)] public readonly ImmutableArray<TaggedText> DisplayParts; [DataMember(Order = 3)] public readonly ImmutableArray<TaggedText> NameDisplayParts; [DataMember(Order = 4)] public readonly ImmutableArray<TaggedText> OriginationParts; [DataMember(Order = 5)] public readonly ImmutableArray<SerializableDocumentSpan> SourceSpans; [DataMember(Order = 6)] public readonly ImmutableDictionary<string, string> Properties; [DataMember(Order = 7)] public readonly ImmutableDictionary<string, string> DisplayableProperties; [DataMember(Order = 8)] public readonly bool DisplayIfNoReferences; public SerializableDefinitionItem( int id, ImmutableArray<string> tags, ImmutableArray<TaggedText> displayParts, ImmutableArray<TaggedText> nameDisplayParts, ImmutableArray<TaggedText> originationParts, ImmutableArray<SerializableDocumentSpan> sourceSpans, ImmutableDictionary<string, string> properties, ImmutableDictionary<string, string> displayableProperties, bool displayIfNoReferences) { Id = id; Tags = tags; DisplayParts = displayParts; NameDisplayParts = nameDisplayParts; OriginationParts = originationParts; SourceSpans = sourceSpans; Properties = properties; DisplayableProperties = displayableProperties; DisplayIfNoReferences = displayIfNoReferences; } public static SerializableDefinitionItem Dehydrate(int id, DefinitionItem item) => new(id, item.Tags, item.DisplayParts, item.NameDisplayParts, item.OriginationParts, item.SourceSpans.SelectAsArray(ss => SerializableDocumentSpan.Dehydrate(ss)), item.Properties, item.DisplayableProperties, item.DisplayIfNoReferences); public async ValueTask<DefinitionItem> RehydrateAsync(Solution solution, CancellationToken cancellationToken) { var sourceSpans = await SourceSpans.SelectAsArrayAsync((ss, cancellationToken) => ss.RehydrateAsync(solution, cancellationToken), cancellationToken).ConfigureAwait(false); return new DefinitionItem.DefaultDefinitionItem( Tags, DisplayParts, NameDisplayParts, OriginationParts, sourceSpans, Properties, DisplayableProperties, DisplayIfNoReferences); } } [DataContract] internal readonly struct SerializableSourceReferenceItem { [DataMember(Order = 0)] public readonly int DefinitionId; [DataMember(Order = 1)] public readonly SerializableDocumentSpan SourceSpan; [DataMember(Order = 2)] public readonly SymbolUsageInfo SymbolUsageInfo; [DataMember(Order = 3)] public readonly ImmutableDictionary<string, string> AdditionalProperties; public SerializableSourceReferenceItem( int definitionId, SerializableDocumentSpan sourceSpan, SymbolUsageInfo symbolUsageInfo, ImmutableDictionary<string, string> additionalProperties) { DefinitionId = definitionId; SourceSpan = sourceSpan; SymbolUsageInfo = symbolUsageInfo; AdditionalProperties = additionalProperties; } public static SerializableSourceReferenceItem Dehydrate(int definitionId, SourceReferenceItem item) => new(definitionId, SerializableDocumentSpan.Dehydrate(item.SourceSpan), item.SymbolUsageInfo, item.AdditionalProperties); public async Task<SourceReferenceItem> RehydrateAsync(Solution solution, DefinitionItem definition, CancellationToken cancellationToken) => new(definition, await SourceSpan.RehydrateAsync(solution, cancellationToken).ConfigureAwait(false), SymbolUsageInfo, AdditionalProperties.ToImmutableDictionary(t => t.Key, t => t.Value)); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Composition; using System.Runtime.Serialization; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.FindSymbols; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Remote; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.FindUsages { internal interface IRemoteFindUsagesService { internal interface ICallback { ValueTask AddItemsAsync(RemoteServiceCallbackId callbackId, int count, CancellationToken cancellationToken); ValueTask ItemCompletedAsync(RemoteServiceCallbackId callbackId, CancellationToken cancellationToken); ValueTask ReportMessageAsync(RemoteServiceCallbackId callbackId, string message, CancellationToken cancellationToken); ValueTask SetSearchTitleAsync(RemoteServiceCallbackId callbackId, string title, CancellationToken cancellationToken); ValueTask OnDefinitionFoundAsync(RemoteServiceCallbackId callbackId, SerializableDefinitionItem definition, CancellationToken cancellationToken); ValueTask OnReferenceFoundAsync(RemoteServiceCallbackId callbackId, SerializableSourceReferenceItem reference, CancellationToken cancellationToken); } ValueTask FindReferencesAsync( PinnedSolutionInfo solutionInfo, RemoteServiceCallbackId callbackId, SerializableSymbolAndProjectId symbolAndProjectId, FindReferencesSearchOptions options, CancellationToken cancellationToken); ValueTask FindImplementationsAsync( PinnedSolutionInfo solutionInfo, RemoteServiceCallbackId callbackId, SerializableSymbolAndProjectId symbolAndProjectId, CancellationToken cancellationToken); } [ExportRemoteServiceCallbackDispatcher(typeof(IRemoteFindUsagesService)), Shared] internal sealed class FindUsagesServerCallbackDispatcher : RemoteServiceCallbackDispatcher, IRemoteFindUsagesService.ICallback { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public FindUsagesServerCallbackDispatcher() { } private new FindUsagesServerCallback GetCallback(RemoteServiceCallbackId callbackId) => (FindUsagesServerCallback)base.GetCallback(callbackId); public ValueTask AddItemsAsync(RemoteServiceCallbackId callbackId, int count, CancellationToken cancellationToken) => GetCallback(callbackId).AddItemsAsync(count, cancellationToken); public ValueTask ItemCompletedAsync(RemoteServiceCallbackId callbackId, CancellationToken cancellationToken) => GetCallback(callbackId).ItemCompletedAsync(cancellationToken); public ValueTask OnDefinitionFoundAsync(RemoteServiceCallbackId callbackId, SerializableDefinitionItem definition, CancellationToken cancellationToken) => GetCallback(callbackId).OnDefinitionFoundAsync(definition, cancellationToken); public ValueTask OnReferenceFoundAsync(RemoteServiceCallbackId callbackId, SerializableSourceReferenceItem reference, CancellationToken cancellationToken) => GetCallback(callbackId).OnReferenceFoundAsync(reference, cancellationToken); public ValueTask ReportMessageAsync(RemoteServiceCallbackId callbackId, string message, CancellationToken cancellationToken) => GetCallback(callbackId).ReportMessageAsync(message, cancellationToken); public ValueTask SetSearchTitleAsync(RemoteServiceCallbackId callbackId, string title, CancellationToken cancellationToken) => GetCallback(callbackId).SetSearchTitleAsync(title, cancellationToken); } internal sealed class FindUsagesServerCallback { private readonly Solution _solution; private readonly IFindUsagesContext _context; private readonly Dictionary<int, DefinitionItem> _idToDefinition = new(); public FindUsagesServerCallback(Solution solution, IFindUsagesContext context) { _solution = solution; _context = context; } public ValueTask AddItemsAsync(int count, CancellationToken cancellationToken) => _context.ProgressTracker.AddItemsAsync(count, cancellationToken); public ValueTask ItemCompletedAsync(CancellationToken cancellationToken) => _context.ProgressTracker.ItemCompletedAsync(cancellationToken); public ValueTask ReportMessageAsync(string message, CancellationToken cancellationToken) => _context.ReportMessageAsync(message, cancellationToken); public ValueTask SetSearchTitleAsync(string title, CancellationToken cancellationToken) => _context.SetSearchTitleAsync(title, cancellationToken); public async ValueTask OnDefinitionFoundAsync(SerializableDefinitionItem definition, CancellationToken cancellationToken) { var id = definition.Id; var rehydrated = await definition.RehydrateAsync(_solution, cancellationToken).ConfigureAwait(false); lock (_idToDefinition) { _idToDefinition.Add(id, rehydrated); } await _context.OnDefinitionFoundAsync(rehydrated, cancellationToken).ConfigureAwait(false); } public async ValueTask OnReferenceFoundAsync(SerializableSourceReferenceItem reference, CancellationToken cancellationToken) { var rehydrated = await reference.RehydrateAsync(_solution, GetDefinition(reference.DefinitionId), cancellationToken).ConfigureAwait(false); await _context.OnReferenceFoundAsync(rehydrated, cancellationToken).ConfigureAwait(false); } private DefinitionItem GetDefinition(int definitionId) { lock (_idToDefinition) { Contract.ThrowIfFalse(_idToDefinition.ContainsKey(definitionId)); return _idToDefinition[definitionId]; } } } [DataContract] internal readonly struct SerializableDocumentSpan { [DataMember(Order = 0)] public readonly DocumentId DocumentId; [DataMember(Order = 1)] public readonly TextSpan SourceSpan; public SerializableDocumentSpan(DocumentId documentId, TextSpan sourceSpan) { DocumentId = documentId; SourceSpan = sourceSpan; } public static SerializableDocumentSpan Dehydrate(DocumentSpan documentSpan) => new(documentSpan.Document.Id, documentSpan.SourceSpan); public async ValueTask<DocumentSpan> RehydrateAsync(Solution solution, CancellationToken cancellationToken) { var document = solution.GetDocument(DocumentId) ?? await solution.GetSourceGeneratedDocumentAsync(DocumentId, cancellationToken).ConfigureAwait(false); Contract.ThrowIfNull(document); return new DocumentSpan(document, SourceSpan); } } [DataContract] internal readonly struct SerializableDefinitionItem { [DataMember(Order = 0)] public readonly int Id; [DataMember(Order = 1)] public readonly ImmutableArray<string> Tags; [DataMember(Order = 2)] public readonly ImmutableArray<TaggedText> DisplayParts; [DataMember(Order = 3)] public readonly ImmutableArray<TaggedText> NameDisplayParts; [DataMember(Order = 4)] public readonly ImmutableArray<TaggedText> OriginationParts; [DataMember(Order = 5)] public readonly ImmutableArray<SerializableDocumentSpan> SourceSpans; [DataMember(Order = 6)] public readonly ImmutableDictionary<string, string> Properties; [DataMember(Order = 7)] public readonly ImmutableDictionary<string, string> DisplayableProperties; [DataMember(Order = 8)] public readonly bool DisplayIfNoReferences; public SerializableDefinitionItem( int id, ImmutableArray<string> tags, ImmutableArray<TaggedText> displayParts, ImmutableArray<TaggedText> nameDisplayParts, ImmutableArray<TaggedText> originationParts, ImmutableArray<SerializableDocumentSpan> sourceSpans, ImmutableDictionary<string, string> properties, ImmutableDictionary<string, string> displayableProperties, bool displayIfNoReferences) { Id = id; Tags = tags; DisplayParts = displayParts; NameDisplayParts = nameDisplayParts; OriginationParts = originationParts; SourceSpans = sourceSpans; Properties = properties; DisplayableProperties = displayableProperties; DisplayIfNoReferences = displayIfNoReferences; } public static SerializableDefinitionItem Dehydrate(int id, DefinitionItem item) => new(id, item.Tags, item.DisplayParts, item.NameDisplayParts, item.OriginationParts, item.SourceSpans.SelectAsArray(ss => SerializableDocumentSpan.Dehydrate(ss)), item.Properties, item.DisplayableProperties, item.DisplayIfNoReferences); public async ValueTask<DefinitionItem> RehydrateAsync(Solution solution, CancellationToken cancellationToken) { var sourceSpans = await SourceSpans.SelectAsArrayAsync((ss, cancellationToken) => ss.RehydrateAsync(solution, cancellationToken), cancellationToken).ConfigureAwait(false); return new DefinitionItem.DefaultDefinitionItem( Tags, DisplayParts, NameDisplayParts, OriginationParts, sourceSpans, Properties, DisplayableProperties, DisplayIfNoReferences); } } [DataContract] internal readonly struct SerializableSourceReferenceItem { [DataMember(Order = 0)] public readonly int DefinitionId; [DataMember(Order = 1)] public readonly SerializableDocumentSpan SourceSpan; [DataMember(Order = 2)] public readonly SymbolUsageInfo SymbolUsageInfo; [DataMember(Order = 3)] public readonly ImmutableDictionary<string, string> AdditionalProperties; public SerializableSourceReferenceItem( int definitionId, SerializableDocumentSpan sourceSpan, SymbolUsageInfo symbolUsageInfo, ImmutableDictionary<string, string> additionalProperties) { DefinitionId = definitionId; SourceSpan = sourceSpan; SymbolUsageInfo = symbolUsageInfo; AdditionalProperties = additionalProperties; } public static SerializableSourceReferenceItem Dehydrate(int definitionId, SourceReferenceItem item) => new(definitionId, SerializableDocumentSpan.Dehydrate(item.SourceSpan), item.SymbolUsageInfo, item.AdditionalProperties); public async Task<SourceReferenceItem> RehydrateAsync(Solution solution, DefinitionItem definition, CancellationToken cancellationToken) => new(definition, await SourceSpan.RehydrateAsync(solution, cancellationToken).ConfigureAwait(false), SymbolUsageInfo, AdditionalProperties.ToImmutableDictionary(t => t.Key, t => t.Value)); } }
-1
dotnet/roslyn
55,428
Test adding nested namespaces
Fixes https://github.com/dotnet/roslyn/issues/54939 The "workaround" that's already implemented is actually the correct behavior.
tmat
2021-08-05T01:19:03Z
2021-08-11T18:38:54Z
bc874ebc5111a2a33221409f895953b1536f6612
1cbbd423e17b186a8f1de89febb4db9a386d180d
Test adding nested namespaces. Fixes https://github.com/dotnet/roslyn/issues/54939 The "workaround" that's already implemented is actually the correct behavior.
./src/Compilers/CSharp/Portable/Emitter/Model/PENetModuleBuilder.cs
// Licensed to the .NET Foundation under one or more agreements. // 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 Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.Emit; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Symbols; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Emit { internal sealed class PENetModuleBuilder : PEModuleBuilder { internal PENetModuleBuilder( SourceModuleSymbol sourceModule, EmitOptions emitOptions, Cci.ModulePropertiesForSerialization serializationProperties, IEnumerable<ResourceDescription> manifestResources) : base(sourceModule, emitOptions, OutputKind.NetModule, serializationProperties, manifestResources) { } internal override SynthesizedAttributeData SynthesizeEmbeddedAttribute() { // Embedded attributes should never be synthesized in modules. throw ExceptionUtilities.Unreachable; } protected override void AddEmbeddedResourcesFromAddedModules(ArrayBuilder<Cci.ManagedResource> builder, DiagnosticBag diagnostics) { throw ExceptionUtilities.Unreachable; } public override EmitBaseline? PreviousGeneration => null; public override SymbolChanges? EncSymbolChanges => null; public override IEnumerable<Cci.IFileReference> GetFiles(EmitContext context) => SpecializedCollections.EmptyEnumerable<Cci.IFileReference>(); public override ISourceAssemblySymbolInternal? SourceAssemblyOpt => null; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.Emit; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Symbols; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Emit { internal sealed class PENetModuleBuilder : PEModuleBuilder { internal PENetModuleBuilder( SourceModuleSymbol sourceModule, EmitOptions emitOptions, Cci.ModulePropertiesForSerialization serializationProperties, IEnumerable<ResourceDescription> manifestResources) : base(sourceModule, emitOptions, OutputKind.NetModule, serializationProperties, manifestResources) { } internal override SynthesizedAttributeData SynthesizeEmbeddedAttribute() { // Embedded attributes should never be synthesized in modules. throw ExceptionUtilities.Unreachable; } protected override void AddEmbeddedResourcesFromAddedModules(ArrayBuilder<Cci.ManagedResource> builder, DiagnosticBag diagnostics) { throw ExceptionUtilities.Unreachable; } public override EmitBaseline? PreviousGeneration => null; public override SymbolChanges? EncSymbolChanges => null; public override IEnumerable<Cci.IFileReference> GetFiles(EmitContext context) => SpecializedCollections.EmptyEnumerable<Cci.IFileReference>(); public override ISourceAssemblySymbolInternal? SourceAssemblyOpt => null; } }
-1
dotnet/roslyn
55,428
Test adding nested namespaces
Fixes https://github.com/dotnet/roslyn/issues/54939 The "workaround" that's already implemented is actually the correct behavior.
tmat
2021-08-05T01:19:03Z
2021-08-11T18:38:54Z
bc874ebc5111a2a33221409f895953b1536f6612
1cbbd423e17b186a8f1de89febb4db9a386d180d
Test adding nested namespaces. Fixes https://github.com/dotnet/roslyn/issues/54939 The "workaround" that's already implemented is actually the correct behavior.
./src/Features/Core/Portable/SolutionCrawler/IDocumentDifferenceService.cs
// Licensed to the .NET Foundation under one or more agreements. // 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 class DocumentDifferenceResult { public InvocationReasons ChangeType { get; } public SyntaxNode? ChangedMember { get; } public DocumentDifferenceResult(InvocationReasons changeType, SyntaxNode? changedMember = null) { ChangeType = changeType; ChangedMember = changedMember; } } internal interface IDocumentDifferenceService : ILanguageService { Task<DocumentDifferenceResult?> GetDifferenceAsync(Document oldDocument, Document newDocument, 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 class DocumentDifferenceResult { public InvocationReasons ChangeType { get; } public SyntaxNode? ChangedMember { get; } public DocumentDifferenceResult(InvocationReasons changeType, SyntaxNode? changedMember = null) { ChangeType = changeType; ChangedMember = changedMember; } } internal interface IDocumentDifferenceService : ILanguageService { Task<DocumentDifferenceResult?> GetDifferenceAsync(Document oldDocument, Document newDocument, CancellationToken cancellationToken); } }
-1
dotnet/roslyn
55,428
Test adding nested namespaces
Fixes https://github.com/dotnet/roslyn/issues/54939 The "workaround" that's already implemented is actually the correct behavior.
tmat
2021-08-05T01:19:03Z
2021-08-11T18:38:54Z
bc874ebc5111a2a33221409f895953b1536f6612
1cbbd423e17b186a8f1de89febb4db9a386d180d
Test adding nested namespaces. Fixes https://github.com/dotnet/roslyn/issues/54939 The "workaround" that's already implemented is actually the correct behavior.
./src/EditorFeatures/VisualBasicTest/Structure/CollectionInitializerStructureProviderTests.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.Structure Imports Microsoft.CodeAnalysis.VisualBasic.Structure Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Outlining Public Class CollectionInitializerStructureProviderTests Inherits AbstractVisualBasicSyntaxNodeStructureProviderTests(Of CollectionInitializerSyntax) Friend Overrides Function CreateProvider() As AbstractSyntaxStructureProvider Return New CollectionInitializerStructureProvider() End Function <Fact, Trait(Traits.Feature, Traits.Features.Outlining)> Public Async Function TestInnerInitializer() As Task Const code = " Class C Sub M() dim d = new Dictionary(of integer, string) From { {|hintspan:{|textspan:$${ 1, ""goo"" },|}|} { 1, ""goo"" } } End Sub End Class " Await VerifyBlockSpansAsync(code, Region("textspan", "hintspan", bannerText:="...", autoCollapse:=False)) 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.Structure Imports Microsoft.CodeAnalysis.VisualBasic.Structure Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Outlining Public Class CollectionInitializerStructureProviderTests Inherits AbstractVisualBasicSyntaxNodeStructureProviderTests(Of CollectionInitializerSyntax) Friend Overrides Function CreateProvider() As AbstractSyntaxStructureProvider Return New CollectionInitializerStructureProvider() End Function <Fact, Trait(Traits.Feature, Traits.Features.Outlining)> Public Async Function TestInnerInitializer() As Task Const code = " Class C Sub M() dim d = new Dictionary(of integer, string) From { {|hintspan:{|textspan:$${ 1, ""goo"" },|}|} { 1, ""goo"" } } End Sub End Class " Await VerifyBlockSpansAsync(code, Region("textspan", "hintspan", bannerText:="...", autoCollapse:=False)) End Function End Class End Namespace
-1
dotnet/roslyn
55,428
Test adding nested namespaces
Fixes https://github.com/dotnet/roslyn/issues/54939 The "workaround" that's already implemented is actually the correct behavior.
tmat
2021-08-05T01:19:03Z
2021-08-11T18:38:54Z
bc874ebc5111a2a33221409f895953b1536f6612
1cbbd423e17b186a8f1de89febb4db9a386d180d
Test adding nested namespaces. Fixes https://github.com/dotnet/roslyn/issues/54939 The "workaround" that's already implemented is actually the correct behavior.
./src/Compilers/Core/Portable/Diagnostic/LocalizableResourceString.FixedLocalizableString.cs
// Licensed to the .NET Foundation under one or more agreements. // 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 Roslyn.Utilities; namespace Microsoft.CodeAnalysis { public abstract partial class LocalizableString { private sealed class FixedLocalizableString : LocalizableString { /// <summary> /// FixedLocalizableString representing an empty string. /// </summary> private static readonly FixedLocalizableString s_empty = new FixedLocalizableString(string.Empty); private readonly string _fixedString; public static FixedLocalizableString Create(string? fixedResource) { if (RoslynString.IsNullOrEmpty(fixedResource)) { return s_empty; } return new FixedLocalizableString(fixedResource); } private FixedLocalizableString(string fixedResource) { _fixedString = fixedResource; } protected override string GetText(IFormatProvider? formatProvider) { return _fixedString; } protected override bool AreEqual(object? other) { var fixedStr = other as FixedLocalizableString; return fixedStr != null && string.Equals(_fixedString, fixedStr._fixedString); } protected override int GetHash() { return _fixedString?.GetHashCode() ?? 0; } internal override bool CanThrowExceptions => 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 Roslyn.Utilities; namespace Microsoft.CodeAnalysis { public abstract partial class LocalizableString { private sealed class FixedLocalizableString : LocalizableString { /// <summary> /// FixedLocalizableString representing an empty string. /// </summary> private static readonly FixedLocalizableString s_empty = new FixedLocalizableString(string.Empty); private readonly string _fixedString; public static FixedLocalizableString Create(string? fixedResource) { if (RoslynString.IsNullOrEmpty(fixedResource)) { return s_empty; } return new FixedLocalizableString(fixedResource); } private FixedLocalizableString(string fixedResource) { _fixedString = fixedResource; } protected override string GetText(IFormatProvider? formatProvider) { return _fixedString; } protected override bool AreEqual(object? other) { var fixedStr = other as FixedLocalizableString; return fixedStr != null && string.Equals(_fixedString, fixedStr._fixedString); } protected override int GetHash() { return _fixedString?.GetHashCode() ?? 0; } internal override bool CanThrowExceptions => false; } } }
-1
dotnet/roslyn
55,428
Test adding nested namespaces
Fixes https://github.com/dotnet/roslyn/issues/54939 The "workaround" that's already implemented is actually the correct behavior.
tmat
2021-08-05T01:19:03Z
2021-08-11T18:38:54Z
bc874ebc5111a2a33221409f895953b1536f6612
1cbbd423e17b186a8f1de89febb4db9a386d180d
Test adding nested namespaces. Fixes https://github.com/dotnet/roslyn/issues/54939 The "workaround" that's already implemented is actually the correct behavior.
./src/Compilers/Core/Portable/InternalUtilities/SpecializedCollections.Empty.Dictionary.cs
// Licensed to the .NET Foundation under one or more agreements. // 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.Utilities { internal partial class SpecializedCollections { private partial class Empty { internal class Dictionary<TKey, TValue> #nullable disable // Note: if the interfaces we implement weren't oblivious, then we'd warn about the `[MaybeNullWhen(false)] out TValue value` parameter below // We can remove this once `IDictionary` is annotated with `[MaybeNullWhen(false)]` : Collection<KeyValuePair<TKey, TValue>>, IDictionary<TKey, TValue>, IReadOnlyDictionary<TKey, TValue> #nullable enable where TKey : notnull { public static new readonly Dictionary<TKey, TValue> Instance = new(); private Dictionary() { } public void Add(TKey key, TValue value) { throw new NotSupportedException(); } public bool ContainsKey(TKey key) { return false; } public ICollection<TKey> Keys { get { return Collection<TKey>.Instance; } } IEnumerable<TKey> IReadOnlyDictionary<TKey, TValue>.Keys => Keys; IEnumerable<TValue> IReadOnlyDictionary<TKey, TValue>.Values => Values; public bool Remove(TKey key) { throw new NotSupportedException(); } public bool TryGetValue(TKey key, [MaybeNullWhen(returnValue: false)] out TValue value) { value = default!; return false; } public ICollection<TValue> Values { get { return Collection<TValue>.Instance; } } public TValue this[TKey key] { 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.Generic; using System.Diagnostics.CodeAnalysis; namespace Roslyn.Utilities { internal partial class SpecializedCollections { private partial class Empty { internal class Dictionary<TKey, TValue> #nullable disable // Note: if the interfaces we implement weren't oblivious, then we'd warn about the `[MaybeNullWhen(false)] out TValue value` parameter below // We can remove this once `IDictionary` is annotated with `[MaybeNullWhen(false)]` : Collection<KeyValuePair<TKey, TValue>>, IDictionary<TKey, TValue>, IReadOnlyDictionary<TKey, TValue> #nullable enable where TKey : notnull { public static new readonly Dictionary<TKey, TValue> Instance = new(); private Dictionary() { } public void Add(TKey key, TValue value) { throw new NotSupportedException(); } public bool ContainsKey(TKey key) { return false; } public ICollection<TKey> Keys { get { return Collection<TKey>.Instance; } } IEnumerable<TKey> IReadOnlyDictionary<TKey, TValue>.Keys => Keys; IEnumerable<TValue> IReadOnlyDictionary<TKey, TValue>.Values => Values; public bool Remove(TKey key) { throw new NotSupportedException(); } public bool TryGetValue(TKey key, [MaybeNullWhen(returnValue: false)] out TValue value) { value = default!; return false; } public ICollection<TValue> Values { get { return Collection<TValue>.Instance; } } public TValue this[TKey key] { get { throw new NotSupportedException(); } set { throw new NotSupportedException(); } } } } } }
-1
dotnet/roslyn
55,428
Test adding nested namespaces
Fixes https://github.com/dotnet/roslyn/issues/54939 The "workaround" that's already implemented is actually the correct behavior.
tmat
2021-08-05T01:19:03Z
2021-08-11T18:38:54Z
bc874ebc5111a2a33221409f895953b1536f6612
1cbbd423e17b186a8f1de89febb4db9a386d180d
Test adding nested namespaces. Fixes https://github.com/dotnet/roslyn/issues/54939 The "workaround" that's already implemented is actually the correct behavior.
./src/Compilers/Core/Portable/InternalUtilities/IsExternalInit.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. // Copied from: // https://github.com/dotnet/runtime/blob/218ef0f7776c2c20f6c594e3475b80f1fe2d7d08/src/libraries/System.Private.CoreLib/src/System/Runtime/CompilerServices/IsExternalInit.cs using System.ComponentModel; namespace System.Runtime.CompilerServices { /// <summary> /// Reserved to be used by the compiler for tracking metadata. /// This class should not be used by developers in source code. /// </summary> [EditorBrowsable(EditorBrowsableState.Never)] internal static class IsExternalInit { } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. // Copied from: // https://github.com/dotnet/runtime/blob/218ef0f7776c2c20f6c594e3475b80f1fe2d7d08/src/libraries/System.Private.CoreLib/src/System/Runtime/CompilerServices/IsExternalInit.cs using System.ComponentModel; namespace System.Runtime.CompilerServices { /// <summary> /// Reserved to be used by the compiler for tracking metadata. /// This class should not be used by developers in source code. /// </summary> [EditorBrowsable(EditorBrowsableState.Never)] internal static class IsExternalInit { } }
-1
dotnet/roslyn
55,427
Fixes #50462
Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
Blokyk
2021-08-05T01:17:37Z
2021-08-25T05:42:59Z
fefb8c2110625bc4908db4bbdaa367b12bfb1069
fb4ac545a1f1f365e7df570637699d9085ea4f87
Fixes #50462. Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
./src/Analyzers/CSharp/Analyzers/CSharpAnalyzersResources.resx
<?xml version="1.0" encoding="utf-8"?> <root> <!-- Microsoft ResX Schema Version 2.0 The primary goals of this format is to allow a simple XML format that is mostly human readable. The generation and parsing of the various data types are done through the TypeConverter classes associated with the data types. Example: ... ado.net/XML headers & schema ... <resheader name="resmimetype">text/microsoft-resx</resheader> <resheader name="version">2.0</resheader> <resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader> <resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader> <data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data> <data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data> <data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64"> <value>[base64 mime encoded serialized .NET Framework object]</value> </data> <data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64"> <value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value> <comment>This is a comment</comment> </data> There are any number of "resheader" rows that contain simple name/value pairs. Each data row contains a name, and value. The row also contains a type or mimetype. Type corresponds to a .NET class that support text/value conversion through the TypeConverter architecture. Classes that don't support this are serialized and stored with the mimetype set. The mimetype is used for serialized objects, and tells the ResXResourceReader how to depersist the object. This is currently not extensible. For a given mimetype the value must be set accordingly: Note - application/x-microsoft.net.object.binary.base64 is the format that the ResXResourceWriter will generate, however the reader can read any of the formats listed below. mimetype: application/x-microsoft.net.object.binary.base64 value : The object must be serialized with : System.Runtime.Serialization.Formatters.Binary.BinaryFormatter : and then encoded with base64 encoding. mimetype: application/x-microsoft.net.object.soap.base64 value : The object must be serialized with : System.Runtime.Serialization.Formatters.Soap.SoapFormatter : and then encoded with base64 encoding. mimetype: application/x-microsoft.net.object.bytearray.base64 value : The object must be serialized into a byte array : using a System.ComponentModel.TypeConverter : and then encoded with base64 encoding. --> <xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata"> <xsd:import namespace="http://www.w3.org/XML/1998/namespace" /> <xsd:element name="root" msdata:IsDataSet="true"> <xsd:complexType> <xsd:choice maxOccurs="unbounded"> <xsd:element name="metadata"> <xsd:complexType> <xsd:sequence> <xsd:element name="value" type="xsd:string" minOccurs="0" /> </xsd:sequence> <xsd:attribute name="name" use="required" type="xsd:string" /> <xsd:attribute name="type" type="xsd:string" /> <xsd:attribute name="mimetype" type="xsd:string" /> <xsd:attribute ref="xml:space" /> </xsd:complexType> </xsd:element> <xsd:element name="assembly"> <xsd:complexType> <xsd:attribute name="alias" type="xsd:string" /> <xsd:attribute name="name" type="xsd:string" /> </xsd:complexType> </xsd:element> <xsd:element name="data"> <xsd:complexType> <xsd:sequence> <xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" /> <xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" /> </xsd:sequence> <xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" /> <xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" /> <xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" /> <xsd:attribute ref="xml:space" /> </xsd:complexType> </xsd:element> <xsd:element name="resheader"> <xsd:complexType> <xsd:sequence> <xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" /> </xsd:sequence> <xsd:attribute name="name" type="xsd:string" use="required" /> </xsd:complexType> </xsd:element> </xsd:choice> </xsd:complexType> </xsd:element> </xsd:schema> <resheader name="resmimetype"> <value>text/microsoft-resx</value> </resheader> <resheader name="version"> <value>2.0</value> </resheader> <resheader name="reader"> <value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value> </resheader> <resheader name="writer"> <value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value> </resheader> <data name="Convert_switch_statement_to_expression" xml:space="preserve"> <value>Convert switch statement to expression</value> </data> <data name="Use_switch_expression" xml:space="preserve"> <value>Use 'switch' expression</value> </data> <data name="Use_explicit_type_instead_of_var" xml:space="preserve"> <value>Use explicit type instead of 'var'</value> </data> <data name="Use_explicit_type" xml:space="preserve"> <value>Use explicit type</value> </data> <data name="use_var_instead_of_explicit_type" xml:space="preserve"> <value>use 'var' instead of explicit type</value> </data> <data name="Use_implicit_type" xml:space="preserve"> <value>Use implicit type</value> </data> <data name="Using_directive_is_unnecessary" xml:space="preserve"> <value>Using directive is unnecessary.</value> </data> <data name="Add_braces" xml:space="preserve"> <value>Add braces</value> </data> <data name="Add_braces_to_0_statement" xml:space="preserve"> <value>Add braces to '{0}' statement.</value> </data> <data name="Misplaced_using_directive" xml:space="preserve"> <value>Misplaced using directive</value> <comment>{Locked="using"} "using" is a C# keyword and should not be localized.</comment> </data> <data name="Move_misplaced_using_directives" xml:space="preserve"> <value>Move misplaced using directives</value> <comment>{Locked="using"} "using" is a C# keyword and should not be localized.</comment> </data> <data name="Using_directives_must_be_placed_inside_of_a_namespace_declaration" xml:space="preserve"> <value>Using directives must be placed inside of a namespace declaration</value> <comment>{Locked="using"} "using" is a C# keyword and should not be localized. {Locked="namespace"} "namespace" is a C# keyword and should not be localized.</comment> </data> <data name="Using_directives_must_be_placed_outside_of_a_namespace_declaration" xml:space="preserve"> <value>Using directives must be placed outside of a namespace declaration</value> <comment>{Locked="using"} "using" is a C# keyword and should not be localized. {Locked="namespace"} "namespace" is a C# keyword and should not be localized.</comment> </data> <data name="Warning_colon_Moving_using_directives_may_change_code_meaning" xml:space="preserve"> <value>Warning: Moving using directives may change code meaning.</value> <comment>{Locked="using"} "using" is a C# keyword and should not be localized.</comment> </data> <data name="Use_expression_body_for_methods" xml:space="preserve"> <value>Use expression body for methods</value> </data> <data name="Use_block_body_for_methods" xml:space="preserve"> <value>Use block body for methods</value> </data> <data name="Use_block_body_for_accessors" xml:space="preserve"> <value>Use block body for accessors</value> </data> <data name="Use_block_body_for_constructors" xml:space="preserve"> <value>Use block body for constructors</value> </data> <data name="Use_block_body_for_indexers" xml:space="preserve"> <value>Use block body for indexers</value> </data> <data name="Use_block_body_for_operators" xml:space="preserve"> <value>Use block body for operators</value> </data> <data name="Use_block_body_for_properties" xml:space="preserve"> <value>Use block body for properties</value> </data> <data name="Use_expression_body_for_accessors" xml:space="preserve"> <value>Use expression body for accessors</value> </data> <data name="Use_expression_body_for_constructors" xml:space="preserve"> <value>Use expression body for constructors</value> </data> <data name="Use_expression_body_for_indexers" xml:space="preserve"> <value>Use expression body for indexers</value> </data> <data name="Use_expression_body_for_operators" xml:space="preserve"> <value>Use expression body for operators</value> </data> <data name="Use_expression_body_for_properties" xml:space="preserve"> <value>Use expression body for properties</value> </data> <data name="Use_block_body_for_local_functions" xml:space="preserve"> <value>Use block body for local functions</value> </data> <data name="Use_expression_body_for_local_functions" xml:space="preserve"> <value>Use expression body for local functions</value> </data> <data name="Unreachable_code_detected" xml:space="preserve"> <value>Unreachable code detected</value> </data> <data name="Use_pattern_matching" xml:space="preserve"> <value>Use pattern matching</value> </data> <data name="Use_is_null_check" xml:space="preserve"> <value>Use 'is null' check</value> </data> <data name="Prefer_null_check_over_type_check" xml:space="preserve"> <value>Prefer 'null' check over type check</value> </data> <data name="Use_simple_using_statement" xml:space="preserve"> <value>Use simple 'using' statement</value> </data> <data name="using_statement_can_be_simplified" xml:space="preserve"> <value>'using' statement can be simplified</value> </data> <data name="if_statement_can_be_simplified" xml:space="preserve"> <value>'if' statement can be simplified</value> </data> <data name="Simplify_default_expression" xml:space="preserve"> <value>Simplify 'default' expression</value> </data> <data name="default_expression_can_be_simplified" xml:space="preserve"> <value>'default' expression can be simplified</value> </data> <data name="Make_readonly_fields_writable" xml:space="preserve"> <value>Make readonly fields writable</value> <comment>{Locked="readonly"} "readonly" is C# keyword and should not be localized.</comment> </data> <data name="Struct_contains_assignment_to_this_outside_of_constructor_Make_readonly_fields_writable" xml:space="preserve"> <value>Struct contains assignment to 'this' outside of constructor. Make readonly fields writable.</value> <comment>{Locked="Struct"}{Locked="this"} these are C#/VB keywords and should not be localized.</comment> </data> <data name="Deconstruct_variable_declaration" xml:space="preserve"> <value>Deconstruct variable declaration</value> </data> <data name="Variable_declaration_can_be_deconstructed" xml:space="preserve"> <value>Variable declaration can be deconstructed</value> </data> <data name="Local_function_can_be_made_static" xml:space="preserve"> <value>Local function can be made static</value> </data> <data name="Make_local_function_static" xml:space="preserve"> <value>Make local function 'static'</value> </data> <data name="_0_can_be_simplified" xml:space="preserve"> <value>{0} can be simplified</value> </data> <data name="Indexing_can_be_simplified" xml:space="preserve"> <value>Indexing can be simplified</value> </data> <data name="Use_local_function" xml:space="preserve"> <value>Use local function</value> </data> <data name="Use_index_operator" xml:space="preserve"> <value>Use index operator</value> </data> <data name="Use_range_operator" xml:space="preserve"> <value>Use range operator</value> </data> <data name="Delegate_invocation_can_be_simplified" xml:space="preserve"> <value>Delegate invocation can be simplified.</value> </data> <data name="Inline_variable_declaration" xml:space="preserve"> <value>Inline variable declaration</value> </data> <data name="Variable_declaration_can_be_inlined" xml:space="preserve"> <value>Variable declaration can be inlined</value> </data> <data name="Negate_expression_changes_semantics" xml:space="preserve"> <value>Negate expression (changes semantics)</value> </data> <data name="Remove_operator_preserves_semantics" xml:space="preserve"> <value>Remove operator (preserves semantics)</value> </data> <data name="Remove_suppression_operators" xml:space="preserve"> <value>Remove suppression operators</value> </data> <data name="Remove_unnecessary_suppression_operator" xml:space="preserve"> <value>Remove unnecessary suppression operator</value> </data> <data name="Suppression_operator_has_no_effect_and_can_be_misinterpreted" xml:space="preserve"> <value>Suppression operator has no effect and can be misinterpreted</value> </data> <data name="typeof_can_be_converted_ to_nameof" xml:space="preserve"> <value>'typeof' can be converted to 'nameof'</value> </data> <data name="Use_new" xml:space="preserve"> <value>Use 'new(...)'</value> <comment>{Locked="new(...)"} This is a C# construct and should not be localized.</comment> </data> <data name="new_expression_can_be_simplified" xml:space="preserve"> <value>'new' expression can be simplified</value> </data> <data name="Discard_can_be_removed" xml:space="preserve"> <value>Discard can be removed</value> </data> <data name="Remove_unnessary_discard" xml:space="preserve"> <value>Remove unnecessary discard</value> </data> <data name="Embedded_statements_must_be_on_their_own_line" xml:space="preserve"> <value>Embedded statements must be on their own line</value> </data> <data name="Consecutive_braces_must_not_have_a_blank_between_them" xml:space="preserve"> <value>Consecutive braces must not have blank line between them</value> </data> <data name="Blank_line_not_allowed_after_constructor_initializer_colon" xml:space="preserve"> <value>Blank line not allowed after constructor initializer colon</value> </data> <data name="Null_check_can_be_clarified" xml:space="preserve"> <value>Null check can be clarified</value> </data> <data name="Convert_to_file_scoped_namespace" xml:space="preserve"> <value>Convert to file-scoped namespace</value> <comment>{Locked="namespace"} "namespace" is a C# keyword and should not be localized.</comment> </data> <data name="Convert_to_block_scoped_namespace" xml:space="preserve"> <value>Convert to block scoped namespace</value> <comment>{Locked="namespace"} "namespace" is a C# keyword and should not be localized.</comment> </data> </root>
<?xml version="1.0" encoding="utf-8"?> <root> <!-- Microsoft ResX Schema Version 2.0 The primary goals of this format is to allow a simple XML format that is mostly human readable. The generation and parsing of the various data types are done through the TypeConverter classes associated with the data types. Example: ... ado.net/XML headers & schema ... <resheader name="resmimetype">text/microsoft-resx</resheader> <resheader name="version">2.0</resheader> <resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader> <resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader> <data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data> <data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data> <data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64"> <value>[base64 mime encoded serialized .NET Framework object]</value> </data> <data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64"> <value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value> <comment>This is a comment</comment> </data> There are any number of "resheader" rows that contain simple name/value pairs. Each data row contains a name, and value. The row also contains a type or mimetype. Type corresponds to a .NET class that support text/value conversion through the TypeConverter architecture. Classes that don't support this are serialized and stored with the mimetype set. The mimetype is used for serialized objects, and tells the ResXResourceReader how to depersist the object. This is currently not extensible. For a given mimetype the value must be set accordingly: Note - application/x-microsoft.net.object.binary.base64 is the format that the ResXResourceWriter will generate, however the reader can read any of the formats listed below. mimetype: application/x-microsoft.net.object.binary.base64 value : The object must be serialized with : System.Runtime.Serialization.Formatters.Binary.BinaryFormatter : and then encoded with base64 encoding. mimetype: application/x-microsoft.net.object.soap.base64 value : The object must be serialized with : System.Runtime.Serialization.Formatters.Soap.SoapFormatter : and then encoded with base64 encoding. mimetype: application/x-microsoft.net.object.bytearray.base64 value : The object must be serialized into a byte array : using a System.ComponentModel.TypeConverter : and then encoded with base64 encoding. --> <xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata"> <xsd:import namespace="http://www.w3.org/XML/1998/namespace" /> <xsd:element name="root" msdata:IsDataSet="true"> <xsd:complexType> <xsd:choice maxOccurs="unbounded"> <xsd:element name="metadata"> <xsd:complexType> <xsd:sequence> <xsd:element name="value" type="xsd:string" minOccurs="0" /> </xsd:sequence> <xsd:attribute name="name" use="required" type="xsd:string" /> <xsd:attribute name="type" type="xsd:string" /> <xsd:attribute name="mimetype" type="xsd:string" /> <xsd:attribute ref="xml:space" /> </xsd:complexType> </xsd:element> <xsd:element name="assembly"> <xsd:complexType> <xsd:attribute name="alias" type="xsd:string" /> <xsd:attribute name="name" type="xsd:string" /> </xsd:complexType> </xsd:element> <xsd:element name="data"> <xsd:complexType> <xsd:sequence> <xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" /> <xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" /> </xsd:sequence> <xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" /> <xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" /> <xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" /> <xsd:attribute ref="xml:space" /> </xsd:complexType> </xsd:element> <xsd:element name="resheader"> <xsd:complexType> <xsd:sequence> <xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" /> </xsd:sequence> <xsd:attribute name="name" type="xsd:string" use="required" /> </xsd:complexType> </xsd:element> </xsd:choice> </xsd:complexType> </xsd:element> </xsd:schema> <resheader name="resmimetype"> <value>text/microsoft-resx</value> </resheader> <resheader name="version"> <value>2.0</value> </resheader> <resheader name="reader"> <value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value> </resheader> <resheader name="writer"> <value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value> </resheader> <data name="Convert_switch_statement_to_expression" xml:space="preserve"> <value>Convert switch statement to expression</value> </data> <data name="Use_switch_expression" xml:space="preserve"> <value>Use 'switch' expression</value> </data> <data name="Use_explicit_type_instead_of_var" xml:space="preserve"> <value>Use explicit type instead of 'var'</value> </data> <data name="Use_explicit_type" xml:space="preserve"> <value>Use explicit type</value> </data> <data name="use_var_instead_of_explicit_type" xml:space="preserve"> <value>use 'var' instead of explicit type</value> </data> <data name="Use_implicit_type" xml:space="preserve"> <value>Use implicit type</value> </data> <data name="Using_directive_is_unnecessary" xml:space="preserve"> <value>Using directive is unnecessary.</value> </data> <data name="Add_braces" xml:space="preserve"> <value>Add braces</value> </data> <data name="Add_braces_to_0_statement" xml:space="preserve"> <value>Add braces to '{0}' statement.</value> </data> <data name="Misplaced_using_directive" xml:space="preserve"> <value>Misplaced using directive</value> <comment>{Locked="using"} "using" is a C# keyword and should not be localized.</comment> </data> <data name="Move_misplaced_using_directives" xml:space="preserve"> <value>Move misplaced using directives</value> <comment>{Locked="using"} "using" is a C# keyword and should not be localized.</comment> </data> <data name="Using_directives_must_be_placed_inside_of_a_namespace_declaration" xml:space="preserve"> <value>Using directives must be placed inside of a namespace declaration</value> <comment>{Locked="using"} "using" is a C# keyword and should not be localized. {Locked="namespace"} "namespace" is a C# keyword and should not be localized.</comment> </data> <data name="Using_directives_must_be_placed_outside_of_a_namespace_declaration" xml:space="preserve"> <value>Using directives must be placed outside of a namespace declaration</value> <comment>{Locked="using"} "using" is a C# keyword and should not be localized. {Locked="namespace"} "namespace" is a C# keyword and should not be localized.</comment> </data> <data name="Warning_colon_Moving_using_directives_may_change_code_meaning" xml:space="preserve"> <value>Warning: Moving using directives may change code meaning.</value> <comment>{Locked="using"} "using" is a C# keyword and should not be localized.</comment> </data> <data name="Use_expression_body_for_methods" xml:space="preserve"> <value>Use expression body for methods</value> </data> <data name="Use_block_body_for_methods" xml:space="preserve"> <value>Use block body for methods</value> </data> <data name="Use_block_body_for_accessors" xml:space="preserve"> <value>Use block body for accessors</value> </data> <data name="Use_block_body_for_constructors" xml:space="preserve"> <value>Use block body for constructors</value> </data> <data name="Use_block_body_for_indexers" xml:space="preserve"> <value>Use block body for indexers</value> </data> <data name="Use_block_body_for_operators" xml:space="preserve"> <value>Use block body for operators</value> </data> <data name="Use_block_body_for_properties" xml:space="preserve"> <value>Use block body for properties</value> </data> <data name="Use_expression_body_for_accessors" xml:space="preserve"> <value>Use expression body for accessors</value> </data> <data name="Use_expression_body_for_constructors" xml:space="preserve"> <value>Use expression body for constructors</value> </data> <data name="Use_expression_body_for_indexers" xml:space="preserve"> <value>Use expression body for indexers</value> </data> <data name="Use_expression_body_for_operators" xml:space="preserve"> <value>Use expression body for operators</value> </data> <data name="Use_expression_body_for_properties" xml:space="preserve"> <value>Use expression body for properties</value> </data> <data name="Use_block_body_for_local_functions" xml:space="preserve"> <value>Use block body for local functions</value> </data> <data name="Use_expression_body_for_local_functions" xml:space="preserve"> <value>Use expression body for local functions</value> </data> <data name="Unreachable_code_detected" xml:space="preserve"> <value>Unreachable code detected</value> </data> <data name="Use_pattern_matching" xml:space="preserve"> <value>Use pattern matching</value> </data> <data name="Use_is_null_check" xml:space="preserve"> <value>Use 'is null' check</value> </data> <data name="Prefer_null_check_over_type_check" xml:space="preserve"> <value>Prefer 'null' check over type check</value> </data> <data name="Use_simple_using_statement" xml:space="preserve"> <value>Use simple 'using' statement</value> </data> <data name="using_statement_can_be_simplified" xml:space="preserve"> <value>'using' statement can be simplified</value> </data> <data name="if_statement_can_be_simplified" xml:space="preserve"> <value>'if' statement can be simplified</value> </data> <data name="Simplify_default_expression" xml:space="preserve"> <value>Simplify 'default' expression</value> </data> <data name="default_expression_can_be_simplified" xml:space="preserve"> <value>'default' expression can be simplified</value> </data> <data name="Make_readonly_fields_writable" xml:space="preserve"> <value>Make readonly fields writable</value> <comment>{Locked="readonly"} "readonly" is C# keyword and should not be localized.</comment> </data> <data name="Struct_contains_assignment_to_this_outside_of_constructor_Make_readonly_fields_writable" xml:space="preserve"> <value>Struct contains assignment to 'this' outside of constructor. Make readonly fields writable.</value> <comment>{Locked="Struct"}{Locked="this"} these are C#/VB keywords and should not be localized.</comment> </data> <data name="Deconstruct_variable_declaration" xml:space="preserve"> <value>Deconstruct variable declaration</value> </data> <data name="Variable_declaration_can_be_deconstructed" xml:space="preserve"> <value>Variable declaration can be deconstructed</value> </data> <data name="Local_function_can_be_made_static" xml:space="preserve"> <value>Local function can be made static</value> </data> <data name="Make_local_function_static" xml:space="preserve"> <value>Make local function 'static'</value> </data> <data name="_0_can_be_simplified" xml:space="preserve"> <value>{0} can be simplified</value> </data> <data name="Indexing_can_be_simplified" xml:space="preserve"> <value>Indexing can be simplified</value> </data> <data name="Use_local_function" xml:space="preserve"> <value>Use local function</value> </data> <data name="Use_index_operator" xml:space="preserve"> <value>Use index operator</value> </data> <data name="Use_range_operator" xml:space="preserve"> <value>Use range operator</value> </data> <data name="Delegate_invocation_can_be_simplified" xml:space="preserve"> <value>Delegate invocation can be simplified.</value> </data> <data name="Inline_variable_declaration" xml:space="preserve"> <value>Inline variable declaration</value> </data> <data name="Variable_declaration_can_be_inlined" xml:space="preserve"> <value>Variable declaration can be inlined</value> </data> <data name="Negate_expression_changes_semantics" xml:space="preserve"> <value>Negate expression (changes semantics)</value> </data> <data name="Remove_operator_preserves_semantics" xml:space="preserve"> <value>Remove operator (preserves semantics)</value> </data> <data name="Remove_suppression_operators" xml:space="preserve"> <value>Remove suppression operators</value> </data> <data name="Remove_unnecessary_suppression_operator" xml:space="preserve"> <value>Remove unnecessary suppression operator</value> </data> <data name="Suppression_operator_has_no_effect_and_can_be_misinterpreted" xml:space="preserve"> <value>Suppression operator has no effect and can be misinterpreted</value> </data> <data name="typeof_can_be_converted_ to_nameof" xml:space="preserve"> <value>'typeof' can be converted to 'nameof'</value> </data> <data name="Use_new" xml:space="preserve"> <value>Use 'new(...)'</value> <comment>{Locked="new(...)"} This is a C# construct and should not be localized.</comment> </data> <data name="new_expression_can_be_simplified" xml:space="preserve"> <value>'new' expression can be simplified</value> </data> <data name="Discard_can_be_removed" xml:space="preserve"> <value>Discard can be removed</value> </data> <data name="Remove_unnessary_discard" xml:space="preserve"> <value>Remove unnecessary discard</value> </data> <data name="Embedded_statements_must_be_on_their_own_line" xml:space="preserve"> <value>Embedded statements must be on their own line</value> </data> <data name="Consecutive_braces_must_not_have_a_blank_between_them" xml:space="preserve"> <value>Consecutive braces must not have blank line between them</value> </data> <data name="Blank_line_not_allowed_after_constructor_initializer_colon" xml:space="preserve"> <value>Blank line not allowed after constructor initializer colon</value> </data> <data name="Null_check_can_be_clarified" xml:space="preserve"> <value>Null check can be clarified</value> </data> <data name="Convert_to_file_scoped_namespace" xml:space="preserve"> <value>Convert to file-scoped namespace</value> <comment>{Locked="namespace"} "namespace" is a C# keyword and should not be localized.</comment> </data> <data name="Convert_to_block_scoped_namespace" xml:space="preserve"> <value>Convert to block scoped namespace</value> <comment>{Locked="namespace"} "namespace" is a C# keyword and should not be localized.</comment> </data> <data name="Use_pattern_matching_may_change_code_meaning" xml:space="preserve"> <value>Use pattern matching (may change code meaning)</value> </data> </root>
1
dotnet/roslyn
55,427
Fixes #50462
Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
Blokyk
2021-08-05T01:17:37Z
2021-08-25T05:42:59Z
fefb8c2110625bc4908db4bbdaa367b12bfb1069
fb4ac545a1f1f365e7df570637699d9085ea4f87
Fixes #50462. Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
./src/Analyzers/CSharp/Analyzers/UsePatternCombinators/CSharpUsePatternCombinatorsDiagnosticAnalyzer.cs
// Licensed to the .NET Foundation under one or more agreements. // 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 Microsoft.CodeAnalysis.CodeStyle; using Microsoft.CodeAnalysis.CSharp.CodeStyle; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Shared.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Diagnostics; namespace Microsoft.CodeAnalysis.CSharp.UsePatternCombinators { using static AnalyzedPattern; [DiagnosticAnalyzer(LanguageNames.CSharp)] internal sealed class CSharpUsePatternCombinatorsDiagnosticAnalyzer : AbstractBuiltInCodeStyleDiagnosticAnalyzer { public CSharpUsePatternCombinatorsDiagnosticAnalyzer() : base(IDEDiagnosticIds.UsePatternCombinatorsDiagnosticId, EnforceOnBuildValues.UsePatternCombinators, CSharpCodeStyleOptions.PreferPatternMatching, LanguageNames.CSharp, new LocalizableResourceString(nameof(CSharpAnalyzersResources.Use_pattern_matching), CSharpAnalyzersResources.ResourceManager, typeof(CSharpAnalyzersResources)), new LocalizableResourceString(nameof(CSharpAnalyzersResources.Use_pattern_matching), CSharpAnalyzersResources.ResourceManager, typeof(CSharpAnalyzersResources))) { } protected override void InitializeWorker(AnalysisContext context) => context.RegisterSyntaxNodeAction(AnalyzeNode, SyntaxKind.LogicalAndExpression, SyntaxKind.LogicalOrExpression, SyntaxKind.LogicalNotExpression); private void AnalyzeNode(SyntaxNodeAnalysisContext context) { var expression = (ExpressionSyntax)context.Node; if (expression.GetDiagnostics().Any(diagnostic => diagnostic.Severity == DiagnosticSeverity.Error)) return; // Bail if this is not a topmost expression // to avoid overlapping diagnostics. if (!IsTopmostExpression(expression)) return; var syntaxTree = expression.SyntaxTree; if (!((CSharpParseOptions)syntaxTree.Options).LanguageVersion.IsCSharp9OrAbove()) return; var cancellationToken = context.CancellationToken; var styleOption = context.Options.GetOption(CSharpCodeStyleOptions.PreferPatternMatching, syntaxTree, cancellationToken); if (!styleOption.Value) return; var semanticModel = context.SemanticModel; var expressionTypeOpt = semanticModel.Compilation.GetTypeByMetadataName("System.Linq.Expressions.Expression`1"); if (expression.IsInExpressionTree(semanticModel, expressionTypeOpt, cancellationToken)) return; var operation = semanticModel.GetOperation(expression, cancellationToken); if (operation is null) return; var pattern = CSharpUsePatternCombinatorsAnalyzer.Analyze(operation); if (pattern is null) return; // Avoid rewriting trivial patterns, such as a single relational or a constant pattern. if (IsTrivial(pattern)) return; // C# 9.0 does not support pattern variables under `not` and `or` combinators, // except for top-level `not` patterns. if (HasIllegalPatternVariables(pattern, isTopLevel: true)) return; context.ReportDiagnostic(DiagnosticHelper.Create( Descriptor, expression.GetLocation(), styleOption.Notification.Severity, additionalLocations: null, properties: null)); } private static bool HasIllegalPatternVariables(AnalyzedPattern pattern, bool permitDesignations = true, bool isTopLevel = false) { switch (pattern) { case Not p: return HasIllegalPatternVariables(p.Pattern, permitDesignations: isTopLevel); case Binary p: if (p.IsDisjunctive) permitDesignations = false; return HasIllegalPatternVariables(p.Left, permitDesignations) || HasIllegalPatternVariables(p.Right, permitDesignations); case Source p when !permitDesignations: return p.PatternSyntax.DescendantNodes() .OfType<SingleVariableDesignationSyntax>() .Any(variable => !variable.Identifier.IsMissing); default: return false; } } private static bool IsTopmostExpression(ExpressionSyntax node) { return node.WalkUpParentheses().Parent switch { LambdaExpressionSyntax _ => true, AssignmentExpressionSyntax _ => true, ConditionalExpressionSyntax _ => true, ExpressionSyntax _ => false, _ => true }; } private static bool IsTrivial(AnalyzedPattern pattern) { return pattern switch { Not { Pattern: Constant _ } => true, Not { Pattern: Source { PatternSyntax: ConstantPatternSyntax _ } } => true, Not _ => false, Binary _ => false, _ => true }; } public override DiagnosticAnalyzerCategory GetAnalyzerCategory() => DiagnosticAnalyzerCategory.SemanticSpanAnalysis; } }
// Licensed to the .NET Foundation under one or more agreements. // 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.CodeStyle; using Microsoft.CodeAnalysis.CSharp.CodeStyle; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Operations; namespace Microsoft.CodeAnalysis.CSharp.UsePatternCombinators { using static AnalyzedPattern; [DiagnosticAnalyzer(LanguageNames.CSharp)] internal sealed class CSharpUsePatternCombinatorsDiagnosticAnalyzer : AbstractBuiltInCodeStyleDiagnosticAnalyzer { private const string SafeKey = "safe"; private static readonly LocalizableResourceString s_safePatternTitle = new(nameof(CSharpAnalyzersResources.Use_pattern_matching), CSharpAnalyzersResources.ResourceManager, typeof(CSharpAnalyzersResources)); private static readonly LocalizableResourceString s_unsafePatternTitle = new(nameof(CSharpAnalyzersResources.Use_pattern_matching_may_change_code_meaning), CSharpAnalyzersResources.ResourceManager, typeof(CSharpAnalyzersResources)); private static readonly ImmutableDictionary<string, string> s_safeProperties = ImmutableDictionary<string, string>.Empty.Add(SafeKey, ""); private static readonly DiagnosticDescriptor s_unsafeDescriptor = CreateDescriptorWithId( IDEDiagnosticIds.UsePatternCombinatorsDiagnosticId, EnforceOnBuildValues.UsePatternCombinators, s_unsafePatternTitle); public CSharpUsePatternCombinatorsDiagnosticAnalyzer() : base(IDEDiagnosticIds.UsePatternCombinatorsDiagnosticId, EnforceOnBuildValues.UsePatternCombinators, CSharpCodeStyleOptions.PreferPatternMatching, LanguageNames.CSharp, s_safePatternTitle, s_safePatternTitle) { } public static bool IsSafe(Diagnostic diagnostic) => diagnostic.Properties.ContainsKey(SafeKey); protected override void InitializeWorker(AnalysisContext context) => context.RegisterSyntaxNodeAction(AnalyzeNode, SyntaxKind.LogicalAndExpression, SyntaxKind.LogicalOrExpression, SyntaxKind.LogicalNotExpression); private void AnalyzeNode(SyntaxNodeAnalysisContext context) { var expression = (ExpressionSyntax)context.Node; if (expression.GetDiagnostics().Any(diagnostic => diagnostic.Severity == DiagnosticSeverity.Error)) return; // Bail if this is not a topmost expression // to avoid overlapping diagnostics. if (!IsTopmostExpression(expression)) return; var syntaxTree = expression.SyntaxTree; if (((CSharpParseOptions)syntaxTree.Options).LanguageVersion < LanguageVersion.CSharp9) return; var cancellationToken = context.CancellationToken; var styleOption = context.Options.GetOption(CSharpCodeStyleOptions.PreferPatternMatching, syntaxTree, cancellationToken); if (!styleOption.Value) return; var semanticModel = context.SemanticModel; var expressionType = semanticModel.Compilation.GetTypeByMetadataName("System.Linq.Expressions.Expression`1"); if (expression.IsInExpressionTree(semanticModel, expressionType, cancellationToken)) return; var operation = semanticModel.GetOperation(expression, cancellationToken); if (operation is null) return; var pattern = CSharpUsePatternCombinatorsAnalyzer.Analyze(operation); if (pattern is null) return; // Avoid rewriting trivial patterns, such as a single relational or a constant pattern. if (IsTrivial(pattern)) return; // C# 9.0 does not support pattern variables under `not` and `or` combinators, // except for top-level `not` patterns. if (HasIllegalPatternVariables(pattern, isTopLevel: true)) return; // if the target (the common expression in the pattern) is a method call, // then we can't guarantee that the rewritting won't have side-effects, // so we should warn the user var isSafe = UnwrapImplicitConversion(pattern.Target) is not Operations.IInvocationOperation; context.ReportDiagnostic(DiagnosticHelper.Create( descriptor: isSafe ? this.Descriptor : s_unsafeDescriptor, expression.GetLocation(), styleOption.Notification.Severity, additionalLocations: null, properties: isSafe ? s_safeProperties : null)); } private static IOperation UnwrapImplicitConversion(IOperation operation) => operation is IConversionOperation conversion && conversion.IsImplicit ? conversion.Operand : operation; private static bool HasIllegalPatternVariables(AnalyzedPattern pattern, bool permitDesignations = true, bool isTopLevel = false) { switch (pattern) { case Not p: return HasIllegalPatternVariables(p.Pattern, permitDesignations: isTopLevel); case Binary p: if (p.IsDisjunctive) permitDesignations = false; return HasIllegalPatternVariables(p.Left, permitDesignations) || HasIllegalPatternVariables(p.Right, permitDesignations); case Source p when !permitDesignations: return p.PatternSyntax.DescendantNodes() .OfType<SingleVariableDesignationSyntax>() .Any(variable => !variable.Identifier.IsMissing); default: return false; } } private static bool IsTopmostExpression(ExpressionSyntax node) { return node.WalkUpParentheses().Parent switch { LambdaExpressionSyntax _ => true, AssignmentExpressionSyntax _ => true, ConditionalExpressionSyntax _ => true, ExpressionSyntax _ => false, _ => true }; } private static bool IsTrivial(AnalyzedPattern pattern) { return pattern switch { Not { Pattern: Constant _ } => true, Not { Pattern: Source { PatternSyntax: ConstantPatternSyntax _ } } => true, Not _ => false, Binary _ => false, _ => true }; } public override DiagnosticAnalyzerCategory GetAnalyzerCategory() => DiagnosticAnalyzerCategory.SemanticSpanAnalysis; } }
1
dotnet/roslyn
55,427
Fixes #50462
Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
Blokyk
2021-08-05T01:17:37Z
2021-08-25T05:42:59Z
fefb8c2110625bc4908db4bbdaa367b12bfb1069
fb4ac545a1f1f365e7df570637699d9085ea4f87
Fixes #50462. Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
./src/Analyzers/CSharp/Analyzers/xlf/CSharpAnalyzersResources.cs.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="cs" original="../CSharpAnalyzersResources.resx"> <body> <trans-unit id="Add_braces"> <source>Add braces</source> <target state="translated">Přidat složené závorky</target> <note /> </trans-unit> <trans-unit id="Add_braces_to_0_statement"> <source>Add braces to '{0}' statement.</source> <target state="translated">Přidat složené závorky do příkazu {0}.</target> <note /> </trans-unit> <trans-unit id="Blank_line_not_allowed_after_constructor_initializer_colon"> <source>Blank line not allowed after constructor initializer colon</source> <target state="translated">Za dvojtečkou inicializátoru konstruktoru se nepovoluje prázdný řádek.</target> <note /> </trans-unit> <trans-unit id="Consecutive_braces_must_not_have_a_blank_between_them"> <source>Consecutive braces must not have blank line between them</source> <target state="translated">Po sobě jdoucí závorky nesmí mít mezi sebou prázdný řádek.</target> <note /> </trans-unit> <trans-unit id="Convert_switch_statement_to_expression"> <source>Convert switch statement to expression</source> <target state="translated">Převést příkaz switch na výraz</target> <note /> </trans-unit> <trans-unit id="Convert_to_block_scoped_namespace"> <source>Convert to block scoped namespace</source> <target state="new">Convert to block scoped namespace</target> <note>{Locked="namespace"} "namespace" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="Convert_to_file_scoped_namespace"> <source>Convert to file-scoped namespace</source> <target state="new">Convert to file-scoped namespace</target> <note>{Locked="namespace"} "namespace" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="Deconstruct_variable_declaration"> <source>Deconstruct variable declaration</source> <target state="translated">Dekonstruovat deklaraci proměnné</target> <note /> </trans-unit> <trans-unit id="Delegate_invocation_can_be_simplified"> <source>Delegate invocation can be simplified.</source> <target state="translated">Volání delegáta může být zjednodušené.</target> <note /> </trans-unit> <trans-unit id="Discard_can_be_removed"> <source>Discard can be removed</source> <target state="translated">Proměnná typu discard se dá odebrat.</target> <note /> </trans-unit> <trans-unit id="Embedded_statements_must_be_on_their_own_line"> <source>Embedded statements must be on their own line</source> <target state="translated">Vložené příkazy musí mít svůj vlastní řádek.</target> <note /> </trans-unit> <trans-unit id="Indexing_can_be_simplified"> <source>Indexing can be simplified</source> <target state="translated">Indexování může být zjednodušené.</target> <note /> </trans-unit> <trans-unit id="Inline_variable_declaration"> <source>Inline variable declaration</source> <target state="translated">Vložená deklarace proměnné</target> <note /> </trans-unit> <trans-unit id="Misplaced_using_directive"> <source>Misplaced using directive</source> <target state="translated">Nesprávné umístění direktivy using</target> <note>{Locked="using"} "using" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="Move_misplaced_using_directives"> <source>Move misplaced using directives</source> <target state="translated">Přesunout nesprávně umístěné direktivy using</target> <note>{Locked="using"} "using" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="Make_readonly_fields_writable"> <source>Make readonly fields writable</source> <target state="translated">Umožnit zápis do polí jen pro čtení (readonly)</target> <note>{Locked="readonly"} "readonly" is C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="Local_function_can_be_made_static"> <source>Local function can be made static</source> <target state="translated">Místní funkce se dá nastavit jako statická.</target> <note /> </trans-unit> <trans-unit id="Make_local_function_static"> <source>Make local function 'static'</source> <target state="translated">Nastavit místní funkci jako statickou</target> <note /> </trans-unit> <trans-unit id="Negate_expression_changes_semantics"> <source>Negate expression (changes semantics)</source> <target state="translated">Negovat výraz (změní sémantiku)</target> <note /> </trans-unit> <trans-unit id="Null_check_can_be_clarified"> <source>Null check can be clarified</source> <target state="new">Null check can be clarified</target> <note /> </trans-unit> <trans-unit id="Prefer_null_check_over_type_check"> <source>Prefer 'null' check over type check</source> <target state="new">Prefer 'null' check over type check</target> <note /> </trans-unit> <trans-unit id="Remove_operator_preserves_semantics"> <source>Remove operator (preserves semantics)</source> <target state="translated">Odebrat operátor (zachová sémantiku)</target> <note /> </trans-unit> <trans-unit id="Remove_suppression_operators"> <source>Remove suppression operators</source> <target state="translated">Odebrat operátory potlačení</target> <note /> </trans-unit> <trans-unit id="Remove_unnecessary_suppression_operator"> <source>Remove unnecessary suppression operator</source> <target state="translated">Odebrat nepotřebný operátor potlačení</target> <note /> </trans-unit> <trans-unit id="Remove_unnessary_discard"> <source>Remove unnecessary discard</source> <target state="translated">Odebrat nepotřebnou proměnnou typu discard</target> <note /> </trans-unit> <trans-unit id="Simplify_default_expression"> <source>Simplify 'default' expression</source> <target state="translated">Zjednodušit výraz default</target> <note /> </trans-unit> <trans-unit id="Struct_contains_assignment_to_this_outside_of_constructor_Make_readonly_fields_writable"> <source>Struct contains assignment to 'this' outside of constructor. Make readonly fields writable.</source> <target state="translated">Struct obsahuje přiřazení do this mimo konstruktor. Nastavte pole určená jen pro čtení jako zapisovatelná.</target> <note>{Locked="Struct"}{Locked="this"} these are C#/VB keywords and should not be localized.</note> </trans-unit> <trans-unit id="Suppression_operator_has_no_effect_and_can_be_misinterpreted"> <source>Suppression operator has no effect and can be misinterpreted</source> <target state="translated">Operátor potlačení nemá žádný vliv a může být chybně interpretován.</target> <note /> </trans-unit> <trans-unit id="Unreachable_code_detected"> <source>Unreachable code detected</source> <target state="translated">Byl zjištěn nedosažitelný kód.</target> <note /> </trans-unit> <trans-unit id="Use_block_body_for_accessors"> <source>Use block body for accessors</source> <target state="translated">Pro přístupové objekty používat text bloku</target> <note /> </trans-unit> <trans-unit id="Use_block_body_for_constructors"> <source>Use block body for constructors</source> <target state="translated">Pro konstruktory používat text bloku</target> <note /> </trans-unit> <trans-unit id="Use_block_body_for_indexers"> <source>Use block body for indexers</source> <target state="translated">Pro indexery používat text bloku</target> <note /> </trans-unit> <trans-unit id="Use_block_body_for_local_functions"> <source>Use block body for local functions</source> <target state="translated">Pro místní funkce používat text bloku</target> <note /> </trans-unit> <trans-unit id="Use_block_body_for_methods"> <source>Use block body for methods</source> <target state="translated">Pro metody používat text bloku</target> <note /> </trans-unit> <trans-unit id="Use_block_body_for_operators"> <source>Use block body for operators</source> <target state="translated">Pro operátory používat text bloku</target> <note /> </trans-unit> <trans-unit id="Use_block_body_for_properties"> <source>Use block body for properties</source> <target state="translated">Pro vlastnosti používat text bloku</target> <note /> </trans-unit> <trans-unit id="Use_explicit_type"> <source>Use explicit type</source> <target state="translated">Použít explicitní typ</target> <note /> </trans-unit> <trans-unit id="Use_explicit_type_instead_of_var"> <source>Use explicit type instead of 'var'</source> <target state="translated">Použít explicitní typ místo var</target> <note /> </trans-unit> <trans-unit id="Use_expression_body_for_accessors"> <source>Use expression body for accessors</source> <target state="translated">Pro přístupové objekty používat text výrazu</target> <note /> </trans-unit> <trans-unit id="Use_expression_body_for_constructors"> <source>Use expression body for constructors</source> <target state="translated">Pro konstruktory používat text výrazu</target> <note /> </trans-unit> <trans-unit id="Use_expression_body_for_indexers"> <source>Use expression body for indexers</source> <target state="translated">Pro indexery používat text výrazu</target> <note /> </trans-unit> <trans-unit id="Use_expression_body_for_local_functions"> <source>Use expression body for local functions</source> <target state="translated">Pro místní funkce používat text výrazu</target> <note /> </trans-unit> <trans-unit id="Use_expression_body_for_methods"> <source>Use expression body for methods</source> <target state="translated">Pro metody používat text výrazu</target> <note /> </trans-unit> <trans-unit id="Use_expression_body_for_operators"> <source>Use expression body for operators</source> <target state="translated">Pro operátory používat text výrazu</target> <note /> </trans-unit> <trans-unit id="Use_expression_body_for_properties"> <source>Use expression body for properties</source> <target state="translated">Pro vlastnosti používat text výrazu</target> <note /> </trans-unit> <trans-unit id="Use_implicit_type"> <source>Use implicit type</source> <target state="translated">Použít implicitní typ</target> <note /> </trans-unit> <trans-unit id="Use_index_operator"> <source>Use index operator</source> <target state="translated">Použít operátor indexu</target> <note /> </trans-unit> <trans-unit id="Use_is_null_check"> <source>Use 'is null' check</source> <target state="translated">Použít kontrolu „is null“</target> <note /> </trans-unit> <trans-unit id="Use_local_function"> <source>Use local function</source> <target state="translated">Použít lokální funkci</target> <note /> </trans-unit> <trans-unit id="Use_new"> <source>Use 'new(...)'</source> <target state="translated">Použít new(...)</target> <note>{Locked="new(...)"} This is a C# construct and should not be localized.</note> </trans-unit> <trans-unit id="Use_pattern_matching"> <source>Use pattern matching</source> <target state="translated">Použít porovnávání vzorů</target> <note /> </trans-unit> <trans-unit id="Use_range_operator"> <source>Use range operator</source> <target state="translated">Použít operátor rozsahu</target> <note /> </trans-unit> <trans-unit id="Use_simple_using_statement"> <source>Use simple 'using' statement</source> <target state="translated">Použít jednoduchý příkaz using</target> <note /> </trans-unit> <trans-unit id="Use_switch_expression"> <source>Use 'switch' expression</source> <target state="translated">Použít výraz switch</target> <note /> </trans-unit> <trans-unit id="Using_directives_must_be_placed_inside_of_a_namespace_declaration"> <source>Using directives must be placed inside of a namespace declaration</source> <target state="translated">Direktivy using se musí umístit do deklarace namespace.</target> <note>{Locked="using"} "using" is a C# keyword and should not be localized. {Locked="namespace"} "namespace" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="Using_directives_must_be_placed_outside_of_a_namespace_declaration"> <source>Using directives must be placed outside of a namespace declaration</source> <target state="translated">Direktivy using se musí umístit mimo deklaraci namespace.</target> <note>{Locked="using"} "using" is a C# keyword and should not be localized. {Locked="namespace"} "namespace" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="Variable_declaration_can_be_deconstructed"> <source>Variable declaration can be deconstructed</source> <target state="translated">Deklaraci proměnné je možné dekonstruovat.</target> <note /> </trans-unit> <trans-unit id="Variable_declaration_can_be_inlined"> <source>Variable declaration can be inlined</source> <target state="translated">Deklaraci proměnné je možné vložit do řádku.</target> <note /> </trans-unit> <trans-unit id="Warning_colon_Moving_using_directives_may_change_code_meaning"> <source>Warning: Moving using directives may change code meaning.</source> <target state="translated">Upozornění: Přesunutí direktiv using může změnit význam kódu.</target> <note>{Locked="using"} "using" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="_0_can_be_simplified"> <source>{0} can be simplified</source> <target state="translated">{0} může být zjednodušený.</target> <note /> </trans-unit> <trans-unit id="default_expression_can_be_simplified"> <source>'default' expression can be simplified</source> <target state="translated">Výraz „default“ může být zjednodušený.</target> <note /> </trans-unit> <trans-unit id="if_statement_can_be_simplified"> <source>'if' statement can be simplified</source> <target state="translated">Příkaz if může být zjednodušený.</target> <note /> </trans-unit> <trans-unit id="new_expression_can_be_simplified"> <source>'new' expression can be simplified</source> <target state="translated">Výraz „new“ může být zjednodušený.</target> <note /> </trans-unit> <trans-unit id="typeof_can_be_converted_ to_nameof"> <source>'typeof' can be converted to 'nameof'</source> <target state="translated">typeof se dá převést na nameof.</target> <note /> </trans-unit> <trans-unit id="use_var_instead_of_explicit_type"> <source>use 'var' instead of explicit type</source> <target state="translated">Použít var místo explicitního typu</target> <note /> </trans-unit> <trans-unit id="Using_directive_is_unnecessary"> <source>Using directive is unnecessary.</source> <target state="translated">Direktiva Using není potřebná.</target> <note /> </trans-unit> <trans-unit id="using_statement_can_be_simplified"> <source>'using' statement can be simplified</source> <target state="translated">Příkaz using může být zjednodušený.</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="cs" original="../CSharpAnalyzersResources.resx"> <body> <trans-unit id="Add_braces"> <source>Add braces</source> <target state="translated">Přidat složené závorky</target> <note /> </trans-unit> <trans-unit id="Add_braces_to_0_statement"> <source>Add braces to '{0}' statement.</source> <target state="translated">Přidat složené závorky do příkazu {0}.</target> <note /> </trans-unit> <trans-unit id="Blank_line_not_allowed_after_constructor_initializer_colon"> <source>Blank line not allowed after constructor initializer colon</source> <target state="translated">Za dvojtečkou inicializátoru konstruktoru se nepovoluje prázdný řádek.</target> <note /> </trans-unit> <trans-unit id="Consecutive_braces_must_not_have_a_blank_between_them"> <source>Consecutive braces must not have blank line between them</source> <target state="translated">Po sobě jdoucí závorky nesmí mít mezi sebou prázdný řádek.</target> <note /> </trans-unit> <trans-unit id="Convert_switch_statement_to_expression"> <source>Convert switch statement to expression</source> <target state="translated">Převést příkaz switch na výraz</target> <note /> </trans-unit> <trans-unit id="Convert_to_block_scoped_namespace"> <source>Convert to block scoped namespace</source> <target state="new">Convert to block scoped namespace</target> <note>{Locked="namespace"} "namespace" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="Convert_to_file_scoped_namespace"> <source>Convert to file-scoped namespace</source> <target state="new">Convert to file-scoped namespace</target> <note>{Locked="namespace"} "namespace" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="Deconstruct_variable_declaration"> <source>Deconstruct variable declaration</source> <target state="translated">Dekonstruovat deklaraci proměnné</target> <note /> </trans-unit> <trans-unit id="Delegate_invocation_can_be_simplified"> <source>Delegate invocation can be simplified.</source> <target state="translated">Volání delegáta může být zjednodušené.</target> <note /> </trans-unit> <trans-unit id="Discard_can_be_removed"> <source>Discard can be removed</source> <target state="translated">Proměnná typu discard se dá odebrat.</target> <note /> </trans-unit> <trans-unit id="Embedded_statements_must_be_on_their_own_line"> <source>Embedded statements must be on their own line</source> <target state="translated">Vložené příkazy musí mít svůj vlastní řádek.</target> <note /> </trans-unit> <trans-unit id="Indexing_can_be_simplified"> <source>Indexing can be simplified</source> <target state="translated">Indexování může být zjednodušené.</target> <note /> </trans-unit> <trans-unit id="Inline_variable_declaration"> <source>Inline variable declaration</source> <target state="translated">Vložená deklarace proměnné</target> <note /> </trans-unit> <trans-unit id="Misplaced_using_directive"> <source>Misplaced using directive</source> <target state="translated">Nesprávné umístění direktivy using</target> <note>{Locked="using"} "using" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="Move_misplaced_using_directives"> <source>Move misplaced using directives</source> <target state="translated">Přesunout nesprávně umístěné direktivy using</target> <note>{Locked="using"} "using" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="Make_readonly_fields_writable"> <source>Make readonly fields writable</source> <target state="translated">Umožnit zápis do polí jen pro čtení (readonly)</target> <note>{Locked="readonly"} "readonly" is C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="Local_function_can_be_made_static"> <source>Local function can be made static</source> <target state="translated">Místní funkce se dá nastavit jako statická.</target> <note /> </trans-unit> <trans-unit id="Make_local_function_static"> <source>Make local function 'static'</source> <target state="translated">Nastavit místní funkci jako statickou</target> <note /> </trans-unit> <trans-unit id="Negate_expression_changes_semantics"> <source>Negate expression (changes semantics)</source> <target state="translated">Negovat výraz (změní sémantiku)</target> <note /> </trans-unit> <trans-unit id="Null_check_can_be_clarified"> <source>Null check can be clarified</source> <target state="new">Null check can be clarified</target> <note /> </trans-unit> <trans-unit id="Prefer_null_check_over_type_check"> <source>Prefer 'null' check over type check</source> <target state="new">Prefer 'null' check over type check</target> <note /> </trans-unit> <trans-unit id="Remove_operator_preserves_semantics"> <source>Remove operator (preserves semantics)</source> <target state="translated">Odebrat operátor (zachová sémantiku)</target> <note /> </trans-unit> <trans-unit id="Remove_suppression_operators"> <source>Remove suppression operators</source> <target state="translated">Odebrat operátory potlačení</target> <note /> </trans-unit> <trans-unit id="Remove_unnecessary_suppression_operator"> <source>Remove unnecessary suppression operator</source> <target state="translated">Odebrat nepotřebný operátor potlačení</target> <note /> </trans-unit> <trans-unit id="Remove_unnessary_discard"> <source>Remove unnecessary discard</source> <target state="translated">Odebrat nepotřebnou proměnnou typu discard</target> <note /> </trans-unit> <trans-unit id="Simplify_default_expression"> <source>Simplify 'default' expression</source> <target state="translated">Zjednodušit výraz default</target> <note /> </trans-unit> <trans-unit id="Struct_contains_assignment_to_this_outside_of_constructor_Make_readonly_fields_writable"> <source>Struct contains assignment to 'this' outside of constructor. Make readonly fields writable.</source> <target state="translated">Struct obsahuje přiřazení do this mimo konstruktor. Nastavte pole určená jen pro čtení jako zapisovatelná.</target> <note>{Locked="Struct"}{Locked="this"} these are C#/VB keywords and should not be localized.</note> </trans-unit> <trans-unit id="Suppression_operator_has_no_effect_and_can_be_misinterpreted"> <source>Suppression operator has no effect and can be misinterpreted</source> <target state="translated">Operátor potlačení nemá žádný vliv a může být chybně interpretován.</target> <note /> </trans-unit> <trans-unit id="Unreachable_code_detected"> <source>Unreachable code detected</source> <target state="translated">Byl zjištěn nedosažitelný kód.</target> <note /> </trans-unit> <trans-unit id="Use_block_body_for_accessors"> <source>Use block body for accessors</source> <target state="translated">Pro přístupové objekty používat text bloku</target> <note /> </trans-unit> <trans-unit id="Use_block_body_for_constructors"> <source>Use block body for constructors</source> <target state="translated">Pro konstruktory používat text bloku</target> <note /> </trans-unit> <trans-unit id="Use_block_body_for_indexers"> <source>Use block body for indexers</source> <target state="translated">Pro indexery používat text bloku</target> <note /> </trans-unit> <trans-unit id="Use_block_body_for_local_functions"> <source>Use block body for local functions</source> <target state="translated">Pro místní funkce používat text bloku</target> <note /> </trans-unit> <trans-unit id="Use_block_body_for_methods"> <source>Use block body for methods</source> <target state="translated">Pro metody používat text bloku</target> <note /> </trans-unit> <trans-unit id="Use_block_body_for_operators"> <source>Use block body for operators</source> <target state="translated">Pro operátory používat text bloku</target> <note /> </trans-unit> <trans-unit id="Use_block_body_for_properties"> <source>Use block body for properties</source> <target state="translated">Pro vlastnosti používat text bloku</target> <note /> </trans-unit> <trans-unit id="Use_explicit_type"> <source>Use explicit type</source> <target state="translated">Použít explicitní typ</target> <note /> </trans-unit> <trans-unit id="Use_explicit_type_instead_of_var"> <source>Use explicit type instead of 'var'</source> <target state="translated">Použít explicitní typ místo var</target> <note /> </trans-unit> <trans-unit id="Use_expression_body_for_accessors"> <source>Use expression body for accessors</source> <target state="translated">Pro přístupové objekty používat text výrazu</target> <note /> </trans-unit> <trans-unit id="Use_expression_body_for_constructors"> <source>Use expression body for constructors</source> <target state="translated">Pro konstruktory používat text výrazu</target> <note /> </trans-unit> <trans-unit id="Use_expression_body_for_indexers"> <source>Use expression body for indexers</source> <target state="translated">Pro indexery používat text výrazu</target> <note /> </trans-unit> <trans-unit id="Use_expression_body_for_local_functions"> <source>Use expression body for local functions</source> <target state="translated">Pro místní funkce používat text výrazu</target> <note /> </trans-unit> <trans-unit id="Use_expression_body_for_methods"> <source>Use expression body for methods</source> <target state="translated">Pro metody používat text výrazu</target> <note /> </trans-unit> <trans-unit id="Use_expression_body_for_operators"> <source>Use expression body for operators</source> <target state="translated">Pro operátory používat text výrazu</target> <note /> </trans-unit> <trans-unit id="Use_expression_body_for_properties"> <source>Use expression body for properties</source> <target state="translated">Pro vlastnosti používat text výrazu</target> <note /> </trans-unit> <trans-unit id="Use_implicit_type"> <source>Use implicit type</source> <target state="translated">Použít implicitní typ</target> <note /> </trans-unit> <trans-unit id="Use_index_operator"> <source>Use index operator</source> <target state="translated">Použít operátor indexu</target> <note /> </trans-unit> <trans-unit id="Use_is_null_check"> <source>Use 'is null' check</source> <target state="translated">Použít kontrolu „is null“</target> <note /> </trans-unit> <trans-unit id="Use_local_function"> <source>Use local function</source> <target state="translated">Použít lokální funkci</target> <note /> </trans-unit> <trans-unit id="Use_new"> <source>Use 'new(...)'</source> <target state="translated">Použít new(...)</target> <note>{Locked="new(...)"} This is a C# construct and should not be localized.</note> </trans-unit> <trans-unit id="Use_pattern_matching"> <source>Use pattern matching</source> <target state="translated">Použít porovnávání vzorů</target> <note /> </trans-unit> <trans-unit id="Use_pattern_matching_may_change_code_meaning"> <source>Use pattern matching (may change code meaning)</source> <target state="new">Use pattern matching (may change code meaning)</target> <note /> </trans-unit> <trans-unit id="Use_range_operator"> <source>Use range operator</source> <target state="translated">Použít operátor rozsahu</target> <note /> </trans-unit> <trans-unit id="Use_simple_using_statement"> <source>Use simple 'using' statement</source> <target state="translated">Použít jednoduchý příkaz using</target> <note /> </trans-unit> <trans-unit id="Use_switch_expression"> <source>Use 'switch' expression</source> <target state="translated">Použít výraz switch</target> <note /> </trans-unit> <trans-unit id="Using_directives_must_be_placed_inside_of_a_namespace_declaration"> <source>Using directives must be placed inside of a namespace declaration</source> <target state="translated">Direktivy using se musí umístit do deklarace namespace.</target> <note>{Locked="using"} "using" is a C# keyword and should not be localized. {Locked="namespace"} "namespace" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="Using_directives_must_be_placed_outside_of_a_namespace_declaration"> <source>Using directives must be placed outside of a namespace declaration</source> <target state="translated">Direktivy using se musí umístit mimo deklaraci namespace.</target> <note>{Locked="using"} "using" is a C# keyword and should not be localized. {Locked="namespace"} "namespace" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="Variable_declaration_can_be_deconstructed"> <source>Variable declaration can be deconstructed</source> <target state="translated">Deklaraci proměnné je možné dekonstruovat.</target> <note /> </trans-unit> <trans-unit id="Variable_declaration_can_be_inlined"> <source>Variable declaration can be inlined</source> <target state="translated">Deklaraci proměnné je možné vložit do řádku.</target> <note /> </trans-unit> <trans-unit id="Warning_colon_Moving_using_directives_may_change_code_meaning"> <source>Warning: Moving using directives may change code meaning.</source> <target state="translated">Upozornění: Přesunutí direktiv using může změnit význam kódu.</target> <note>{Locked="using"} "using" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="_0_can_be_simplified"> <source>{0} can be simplified</source> <target state="translated">{0} může být zjednodušený.</target> <note /> </trans-unit> <trans-unit id="default_expression_can_be_simplified"> <source>'default' expression can be simplified</source> <target state="translated">Výraz „default“ může být zjednodušený.</target> <note /> </trans-unit> <trans-unit id="if_statement_can_be_simplified"> <source>'if' statement can be simplified</source> <target state="translated">Příkaz if může být zjednodušený.</target> <note /> </trans-unit> <trans-unit id="new_expression_can_be_simplified"> <source>'new' expression can be simplified</source> <target state="translated">Výraz „new“ může být zjednodušený.</target> <note /> </trans-unit> <trans-unit id="typeof_can_be_converted_ to_nameof"> <source>'typeof' can be converted to 'nameof'</source> <target state="translated">typeof se dá převést na nameof.</target> <note /> </trans-unit> <trans-unit id="use_var_instead_of_explicit_type"> <source>use 'var' instead of explicit type</source> <target state="translated">Použít var místo explicitního typu</target> <note /> </trans-unit> <trans-unit id="Using_directive_is_unnecessary"> <source>Using directive is unnecessary.</source> <target state="translated">Direktiva Using není potřebná.</target> <note /> </trans-unit> <trans-unit id="using_statement_can_be_simplified"> <source>'using' statement can be simplified</source> <target state="translated">Příkaz using může být zjednodušený.</target> <note /> </trans-unit> </body> </file> </xliff>
1
dotnet/roslyn
55,427
Fixes #50462
Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
Blokyk
2021-08-05T01:17:37Z
2021-08-25T05:42:59Z
fefb8c2110625bc4908db4bbdaa367b12bfb1069
fb4ac545a1f1f365e7df570637699d9085ea4f87
Fixes #50462. Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
./src/Analyzers/CSharp/Analyzers/xlf/CSharpAnalyzersResources.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="../CSharpAnalyzersResources.resx"> <body> <trans-unit id="Add_braces"> <source>Add braces</source> <target state="translated">Geschweifte Klammern hinzufügen</target> <note /> </trans-unit> <trans-unit id="Add_braces_to_0_statement"> <source>Add braces to '{0}' statement.</source> <target state="translated">Der Anweisung "{0}" geschweifte Klammern hinzufügen</target> <note /> </trans-unit> <trans-unit id="Blank_line_not_allowed_after_constructor_initializer_colon"> <source>Blank line not allowed after constructor initializer colon</source> <target state="translated">Nach dem Doppelpunkt für den Initialisierer des Konstruktors ist keine leere Zeile zulässig.</target> <note /> </trans-unit> <trans-unit id="Consecutive_braces_must_not_have_a_blank_between_them"> <source>Consecutive braces must not have blank line between them</source> <target state="translated">Aufeinanderfolgende geschweifte Klammern dürfen keine leere Zeile einschließen.</target> <note /> </trans-unit> <trans-unit id="Convert_switch_statement_to_expression"> <source>Convert switch statement to expression</source> <target state="translated">Switch-Anweisung in Ausdruck konvertieren</target> <note /> </trans-unit> <trans-unit id="Convert_to_block_scoped_namespace"> <source>Convert to block scoped namespace</source> <target state="new">Convert to block scoped namespace</target> <note>{Locked="namespace"} "namespace" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="Convert_to_file_scoped_namespace"> <source>Convert to file-scoped namespace</source> <target state="new">Convert to file-scoped namespace</target> <note>{Locked="namespace"} "namespace" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="Deconstruct_variable_declaration"> <source>Deconstruct variable declaration</source> <target state="translated">Variablendeklaration dekonstruieren</target> <note /> </trans-unit> <trans-unit id="Delegate_invocation_can_be_simplified"> <source>Delegate invocation can be simplified.</source> <target state="translated">Der Delegataufruf kann vereinfacht werden.</target> <note /> </trans-unit> <trans-unit id="Discard_can_be_removed"> <source>Discard can be removed</source> <target state="translated">discard-Element kann entfernt werden.</target> <note /> </trans-unit> <trans-unit id="Embedded_statements_must_be_on_their_own_line"> <source>Embedded statements must be on their own line</source> <target state="translated">Eingebettete Anweisungen müssen in einer eigenen Zeile enthalten sein.</target> <note /> </trans-unit> <trans-unit id="Indexing_can_be_simplified"> <source>Indexing can be simplified</source> <target state="translated">Die Indizierung kann vereinfacht werden</target> <note /> </trans-unit> <trans-unit id="Inline_variable_declaration"> <source>Inline variable declaration</source> <target state="translated">Inlinevariablendeklaration</target> <note /> </trans-unit> <trans-unit id="Misplaced_using_directive"> <source>Misplaced using directive</source> <target state="translated">Die using-Anweisung wurde falsch platziert.</target> <note>{Locked="using"} "using" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="Move_misplaced_using_directives"> <source>Move misplaced using directives</source> <target state="translated">Falsch platzierte using-Anweisungen verschieben</target> <note>{Locked="using"} "using" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="Make_readonly_fields_writable"> <source>Make readonly fields writable</source> <target state="translated">readonly-Felder als schreibbar festlegen</target> <note>{Locked="readonly"} "readonly" is C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="Local_function_can_be_made_static"> <source>Local function can be made static</source> <target state="translated">Die lokale Funktion kann als statisch festgelegt werden.</target> <note /> </trans-unit> <trans-unit id="Make_local_function_static"> <source>Make local function 'static'</source> <target state="translated">Lokale Funktion als "static" festlegen</target> <note /> </trans-unit> <trans-unit id="Negate_expression_changes_semantics"> <source>Negate expression (changes semantics)</source> <target state="translated">Ausdruck negieren (Semantik ändern)</target> <note /> </trans-unit> <trans-unit id="Null_check_can_be_clarified"> <source>Null check can be clarified</source> <target state="new">Null check can be clarified</target> <note /> </trans-unit> <trans-unit id="Prefer_null_check_over_type_check"> <source>Prefer 'null' check over type check</source> <target state="new">Prefer 'null' check over type check</target> <note /> </trans-unit> <trans-unit id="Remove_operator_preserves_semantics"> <source>Remove operator (preserves semantics)</source> <target state="translated">Operator entfernen (Semantik beibehalten)</target> <note /> </trans-unit> <trans-unit id="Remove_suppression_operators"> <source>Remove suppression operators</source> <target state="translated">Unterdrückungsoperatoren entfernen</target> <note /> </trans-unit> <trans-unit id="Remove_unnecessary_suppression_operator"> <source>Remove unnecessary suppression operator</source> <target state="translated">Unnötigen Unterdrückungsoperator entfernen</target> <note /> </trans-unit> <trans-unit id="Remove_unnessary_discard"> <source>Remove unnecessary discard</source> <target state="translated">Nicht benötigtes discard-Element entfernen</target> <note /> </trans-unit> <trans-unit id="Simplify_default_expression"> <source>Simplify 'default' expression</source> <target state="translated">"default"-Ausdruck vereinfachen</target> <note /> </trans-unit> <trans-unit id="Struct_contains_assignment_to_this_outside_of_constructor_Make_readonly_fields_writable"> <source>Struct contains assignment to 'this' outside of constructor. Make readonly fields writable.</source> <target state="translated">"Struct" enthält außerhalb des Konstruktors eine Zuweisung zu "this". Legen Sie schreibgeschützte Felder als beschreibbar fest.</target> <note>{Locked="Struct"}{Locked="this"} these are C#/VB keywords and should not be localized.</note> </trans-unit> <trans-unit id="Suppression_operator_has_no_effect_and_can_be_misinterpreted"> <source>Suppression operator has no effect and can be misinterpreted</source> <target state="translated">Der Unterdrückungsoperator besitzt keine Auswirkungen und kann falsch interpretiert werden.</target> <note /> </trans-unit> <trans-unit id="Unreachable_code_detected"> <source>Unreachable code detected</source> <target state="translated">Unerreichbarer Code wurde entdeckt.</target> <note /> </trans-unit> <trans-unit id="Use_block_body_for_accessors"> <source>Use block body for accessors</source> <target state="translated">Blocktextkörper für Accessoren verwenden</target> <note /> </trans-unit> <trans-unit id="Use_block_body_for_constructors"> <source>Use block body for constructors</source> <target state="translated">Blocktextkörper für Konstruktoren verwenden</target> <note /> </trans-unit> <trans-unit id="Use_block_body_for_indexers"> <source>Use block body for indexers</source> <target state="translated">Blocktextkörper für Indexer verwenden</target> <note /> </trans-unit> <trans-unit id="Use_block_body_for_local_functions"> <source>Use block body for local functions</source> <target state="translated">Blocktextkörper für lokale Funktionen verwenden</target> <note /> </trans-unit> <trans-unit id="Use_block_body_for_methods"> <source>Use block body for methods</source> <target state="translated">Blocktextkörper für Methoden verwenden</target> <note /> </trans-unit> <trans-unit id="Use_block_body_for_operators"> <source>Use block body for operators</source> <target state="translated">Blocktextkörper für Operatoren verwenden</target> <note /> </trans-unit> <trans-unit id="Use_block_body_for_properties"> <source>Use block body for properties</source> <target state="translated">Blocktextkörper für Eigenschaften verwenden</target> <note /> </trans-unit> <trans-unit id="Use_explicit_type"> <source>Use explicit type</source> <target state="translated">Expliziten Typ verwenden</target> <note /> </trans-unit> <trans-unit id="Use_explicit_type_instead_of_var"> <source>Use explicit type instead of 'var'</source> <target state="translated">Expliziten Typ anstelle von "var" verwenden</target> <note /> </trans-unit> <trans-unit id="Use_expression_body_for_accessors"> <source>Use expression body for accessors</source> <target state="translated">Ausdruckskörper für Accessoren verwenden</target> <note /> </trans-unit> <trans-unit id="Use_expression_body_for_constructors"> <source>Use expression body for constructors</source> <target state="translated">Ausdruckskörper für Konstruktoren verwenden</target> <note /> </trans-unit> <trans-unit id="Use_expression_body_for_indexers"> <source>Use expression body for indexers</source> <target state="translated">Ausdruckskörper für Indexer verwenden</target> <note /> </trans-unit> <trans-unit id="Use_expression_body_for_local_functions"> <source>Use expression body for local functions</source> <target state="translated">Ausdruckstext für lokale Funktionen verwenden</target> <note /> </trans-unit> <trans-unit id="Use_expression_body_for_methods"> <source>Use expression body for methods</source> <target state="translated">Ausdruckskörper für Methoden verwenden</target> <note /> </trans-unit> <trans-unit id="Use_expression_body_for_operators"> <source>Use expression body for operators</source> <target state="translated">Ausdruckskörper für Operatoren verwenden</target> <note /> </trans-unit> <trans-unit id="Use_expression_body_for_properties"> <source>Use expression body for properties</source> <target state="translated">Ausdruckskörper für Eigenschaften verwenden</target> <note /> </trans-unit> <trans-unit id="Use_implicit_type"> <source>Use implicit type</source> <target state="translated">Impliziten Typ verwenden</target> <note /> </trans-unit> <trans-unit id="Use_index_operator"> <source>Use index operator</source> <target state="translated">Indexoperator verwenden</target> <note /> </trans-unit> <trans-unit id="Use_is_null_check"> <source>Use 'is null' check</source> <target state="translated">"Ist NULL"-Prüfung verwenden</target> <note /> </trans-unit> <trans-unit id="Use_local_function"> <source>Use local function</source> <target state="translated">Lokale Funktion verwenden</target> <note /> </trans-unit> <trans-unit id="Use_new"> <source>Use 'new(...)'</source> <target state="translated">"new(...)" verwenden</target> <note>{Locked="new(...)"} This is a C# construct and should not be localized.</note> </trans-unit> <trans-unit id="Use_pattern_matching"> <source>Use pattern matching</source> <target state="translated">Musterabgleich verwenden</target> <note /> </trans-unit> <trans-unit id="Use_range_operator"> <source>Use range operator</source> <target state="translated">Bereichsoperator verwenden</target> <note /> </trans-unit> <trans-unit id="Use_simple_using_statement"> <source>Use simple 'using' statement</source> <target state="translated">Einfache using-Anweisung verwenden</target> <note /> </trans-unit> <trans-unit id="Use_switch_expression"> <source>Use 'switch' expression</source> <target state="translated">Switch-Ausdruck verwenden</target> <note /> </trans-unit> <trans-unit id="Using_directives_must_be_placed_inside_of_a_namespace_declaration"> <source>Using directives must be placed inside of a namespace declaration</source> <target state="translated">Using-Anweisungen müssen in einer namespace-Deklaration platziert werden.</target> <note>{Locked="using"} "using" is a C# keyword and should not be localized. {Locked="namespace"} "namespace" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="Using_directives_must_be_placed_outside_of_a_namespace_declaration"> <source>Using directives must be placed outside of a namespace declaration</source> <target state="translated">Using-Anweisungen müssen außerhalb einer namespace-Deklaration platziert werden.</target> <note>{Locked="using"} "using" is a C# keyword and should not be localized. {Locked="namespace"} "namespace" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="Variable_declaration_can_be_deconstructed"> <source>Variable declaration can be deconstructed</source> <target state="translated">Die Variablendeklaration kann dekonstruiert werden.</target> <note /> </trans-unit> <trans-unit id="Variable_declaration_can_be_inlined"> <source>Variable declaration can be inlined</source> <target state="translated">Variablendeklaration kann inline erfolgen.</target> <note /> </trans-unit> <trans-unit id="Warning_colon_Moving_using_directives_may_change_code_meaning"> <source>Warning: Moving using directives may change code meaning.</source> <target state="translated">Warnung: Durch das Verschieben von using-Anweisungen kann sich die Codebedeutung ändern.</target> <note>{Locked="using"} "using" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="_0_can_be_simplified"> <source>{0} can be simplified</source> <target state="translated">{0} kann vereinfacht werden</target> <note /> </trans-unit> <trans-unit id="default_expression_can_be_simplified"> <source>'default' expression can be simplified</source> <target state="translated">'"default"-Ausdruck kann vereinfacht werden</target> <note /> </trans-unit> <trans-unit id="if_statement_can_be_simplified"> <source>'if' statement can be simplified</source> <target state="translated">Die If-Anweisung kann vereinfacht werden.</target> <note /> </trans-unit> <trans-unit id="new_expression_can_be_simplified"> <source>'new' expression can be simplified</source> <target state="translated">new-Ausdruck kann vereinfacht werden</target> <note /> </trans-unit> <trans-unit id="typeof_can_be_converted_ to_nameof"> <source>'typeof' can be converted to 'nameof'</source> <target state="translated">"typeof" kann in "nameof" konvertiert werden.</target> <note /> </trans-unit> <trans-unit id="use_var_instead_of_explicit_type"> <source>use 'var' instead of explicit type</source> <target state="translated">"var" anstelle des expliziten Typs verwenden</target> <note /> </trans-unit> <trans-unit id="Using_directive_is_unnecessary"> <source>Using directive is unnecessary.</source> <target state="translated">Using-Direktive ist unnötig.</target> <note /> </trans-unit> <trans-unit id="using_statement_can_be_simplified"> <source>'using' statement can be simplified</source> <target state="translated">Die using-Anweisung kann vereinfacht werden.</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="../CSharpAnalyzersResources.resx"> <body> <trans-unit id="Add_braces"> <source>Add braces</source> <target state="translated">Geschweifte Klammern hinzufügen</target> <note /> </trans-unit> <trans-unit id="Add_braces_to_0_statement"> <source>Add braces to '{0}' statement.</source> <target state="translated">Der Anweisung "{0}" geschweifte Klammern hinzufügen</target> <note /> </trans-unit> <trans-unit id="Blank_line_not_allowed_after_constructor_initializer_colon"> <source>Blank line not allowed after constructor initializer colon</source> <target state="translated">Nach dem Doppelpunkt für den Initialisierer des Konstruktors ist keine leere Zeile zulässig.</target> <note /> </trans-unit> <trans-unit id="Consecutive_braces_must_not_have_a_blank_between_them"> <source>Consecutive braces must not have blank line between them</source> <target state="translated">Aufeinanderfolgende geschweifte Klammern dürfen keine leere Zeile einschließen.</target> <note /> </trans-unit> <trans-unit id="Convert_switch_statement_to_expression"> <source>Convert switch statement to expression</source> <target state="translated">Switch-Anweisung in Ausdruck konvertieren</target> <note /> </trans-unit> <trans-unit id="Convert_to_block_scoped_namespace"> <source>Convert to block scoped namespace</source> <target state="new">Convert to block scoped namespace</target> <note>{Locked="namespace"} "namespace" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="Convert_to_file_scoped_namespace"> <source>Convert to file-scoped namespace</source> <target state="new">Convert to file-scoped namespace</target> <note>{Locked="namespace"} "namespace" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="Deconstruct_variable_declaration"> <source>Deconstruct variable declaration</source> <target state="translated">Variablendeklaration dekonstruieren</target> <note /> </trans-unit> <trans-unit id="Delegate_invocation_can_be_simplified"> <source>Delegate invocation can be simplified.</source> <target state="translated">Der Delegataufruf kann vereinfacht werden.</target> <note /> </trans-unit> <trans-unit id="Discard_can_be_removed"> <source>Discard can be removed</source> <target state="translated">discard-Element kann entfernt werden.</target> <note /> </trans-unit> <trans-unit id="Embedded_statements_must_be_on_their_own_line"> <source>Embedded statements must be on their own line</source> <target state="translated">Eingebettete Anweisungen müssen in einer eigenen Zeile enthalten sein.</target> <note /> </trans-unit> <trans-unit id="Indexing_can_be_simplified"> <source>Indexing can be simplified</source> <target state="translated">Die Indizierung kann vereinfacht werden</target> <note /> </trans-unit> <trans-unit id="Inline_variable_declaration"> <source>Inline variable declaration</source> <target state="translated">Inlinevariablendeklaration</target> <note /> </trans-unit> <trans-unit id="Misplaced_using_directive"> <source>Misplaced using directive</source> <target state="translated">Die using-Anweisung wurde falsch platziert.</target> <note>{Locked="using"} "using" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="Move_misplaced_using_directives"> <source>Move misplaced using directives</source> <target state="translated">Falsch platzierte using-Anweisungen verschieben</target> <note>{Locked="using"} "using" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="Make_readonly_fields_writable"> <source>Make readonly fields writable</source> <target state="translated">readonly-Felder als schreibbar festlegen</target> <note>{Locked="readonly"} "readonly" is C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="Local_function_can_be_made_static"> <source>Local function can be made static</source> <target state="translated">Die lokale Funktion kann als statisch festgelegt werden.</target> <note /> </trans-unit> <trans-unit id="Make_local_function_static"> <source>Make local function 'static'</source> <target state="translated">Lokale Funktion als "static" festlegen</target> <note /> </trans-unit> <trans-unit id="Negate_expression_changes_semantics"> <source>Negate expression (changes semantics)</source> <target state="translated">Ausdruck negieren (Semantik ändern)</target> <note /> </trans-unit> <trans-unit id="Null_check_can_be_clarified"> <source>Null check can be clarified</source> <target state="new">Null check can be clarified</target> <note /> </trans-unit> <trans-unit id="Prefer_null_check_over_type_check"> <source>Prefer 'null' check over type check</source> <target state="new">Prefer 'null' check over type check</target> <note /> </trans-unit> <trans-unit id="Remove_operator_preserves_semantics"> <source>Remove operator (preserves semantics)</source> <target state="translated">Operator entfernen (Semantik beibehalten)</target> <note /> </trans-unit> <trans-unit id="Remove_suppression_operators"> <source>Remove suppression operators</source> <target state="translated">Unterdrückungsoperatoren entfernen</target> <note /> </trans-unit> <trans-unit id="Remove_unnecessary_suppression_operator"> <source>Remove unnecessary suppression operator</source> <target state="translated">Unnötigen Unterdrückungsoperator entfernen</target> <note /> </trans-unit> <trans-unit id="Remove_unnessary_discard"> <source>Remove unnecessary discard</source> <target state="translated">Nicht benötigtes discard-Element entfernen</target> <note /> </trans-unit> <trans-unit id="Simplify_default_expression"> <source>Simplify 'default' expression</source> <target state="translated">"default"-Ausdruck vereinfachen</target> <note /> </trans-unit> <trans-unit id="Struct_contains_assignment_to_this_outside_of_constructor_Make_readonly_fields_writable"> <source>Struct contains assignment to 'this' outside of constructor. Make readonly fields writable.</source> <target state="translated">"Struct" enthält außerhalb des Konstruktors eine Zuweisung zu "this". Legen Sie schreibgeschützte Felder als beschreibbar fest.</target> <note>{Locked="Struct"}{Locked="this"} these are C#/VB keywords and should not be localized.</note> </trans-unit> <trans-unit id="Suppression_operator_has_no_effect_and_can_be_misinterpreted"> <source>Suppression operator has no effect and can be misinterpreted</source> <target state="translated">Der Unterdrückungsoperator besitzt keine Auswirkungen und kann falsch interpretiert werden.</target> <note /> </trans-unit> <trans-unit id="Unreachable_code_detected"> <source>Unreachable code detected</source> <target state="translated">Unerreichbarer Code wurde entdeckt.</target> <note /> </trans-unit> <trans-unit id="Use_block_body_for_accessors"> <source>Use block body for accessors</source> <target state="translated">Blocktextkörper für Accessoren verwenden</target> <note /> </trans-unit> <trans-unit id="Use_block_body_for_constructors"> <source>Use block body for constructors</source> <target state="translated">Blocktextkörper für Konstruktoren verwenden</target> <note /> </trans-unit> <trans-unit id="Use_block_body_for_indexers"> <source>Use block body for indexers</source> <target state="translated">Blocktextkörper für Indexer verwenden</target> <note /> </trans-unit> <trans-unit id="Use_block_body_for_local_functions"> <source>Use block body for local functions</source> <target state="translated">Blocktextkörper für lokale Funktionen verwenden</target> <note /> </trans-unit> <trans-unit id="Use_block_body_for_methods"> <source>Use block body for methods</source> <target state="translated">Blocktextkörper für Methoden verwenden</target> <note /> </trans-unit> <trans-unit id="Use_block_body_for_operators"> <source>Use block body for operators</source> <target state="translated">Blocktextkörper für Operatoren verwenden</target> <note /> </trans-unit> <trans-unit id="Use_block_body_for_properties"> <source>Use block body for properties</source> <target state="translated">Blocktextkörper für Eigenschaften verwenden</target> <note /> </trans-unit> <trans-unit id="Use_explicit_type"> <source>Use explicit type</source> <target state="translated">Expliziten Typ verwenden</target> <note /> </trans-unit> <trans-unit id="Use_explicit_type_instead_of_var"> <source>Use explicit type instead of 'var'</source> <target state="translated">Expliziten Typ anstelle von "var" verwenden</target> <note /> </trans-unit> <trans-unit id="Use_expression_body_for_accessors"> <source>Use expression body for accessors</source> <target state="translated">Ausdruckskörper für Accessoren verwenden</target> <note /> </trans-unit> <trans-unit id="Use_expression_body_for_constructors"> <source>Use expression body for constructors</source> <target state="translated">Ausdruckskörper für Konstruktoren verwenden</target> <note /> </trans-unit> <trans-unit id="Use_expression_body_for_indexers"> <source>Use expression body for indexers</source> <target state="translated">Ausdruckskörper für Indexer verwenden</target> <note /> </trans-unit> <trans-unit id="Use_expression_body_for_local_functions"> <source>Use expression body for local functions</source> <target state="translated">Ausdruckstext für lokale Funktionen verwenden</target> <note /> </trans-unit> <trans-unit id="Use_expression_body_for_methods"> <source>Use expression body for methods</source> <target state="translated">Ausdruckskörper für Methoden verwenden</target> <note /> </trans-unit> <trans-unit id="Use_expression_body_for_operators"> <source>Use expression body for operators</source> <target state="translated">Ausdruckskörper für Operatoren verwenden</target> <note /> </trans-unit> <trans-unit id="Use_expression_body_for_properties"> <source>Use expression body for properties</source> <target state="translated">Ausdruckskörper für Eigenschaften verwenden</target> <note /> </trans-unit> <trans-unit id="Use_implicit_type"> <source>Use implicit type</source> <target state="translated">Impliziten Typ verwenden</target> <note /> </trans-unit> <trans-unit id="Use_index_operator"> <source>Use index operator</source> <target state="translated">Indexoperator verwenden</target> <note /> </trans-unit> <trans-unit id="Use_is_null_check"> <source>Use 'is null' check</source> <target state="translated">"Ist NULL"-Prüfung verwenden</target> <note /> </trans-unit> <trans-unit id="Use_local_function"> <source>Use local function</source> <target state="translated">Lokale Funktion verwenden</target> <note /> </trans-unit> <trans-unit id="Use_new"> <source>Use 'new(...)'</source> <target state="translated">"new(...)" verwenden</target> <note>{Locked="new(...)"} This is a C# construct and should not be localized.</note> </trans-unit> <trans-unit id="Use_pattern_matching"> <source>Use pattern matching</source> <target state="translated">Musterabgleich verwenden</target> <note /> </trans-unit> <trans-unit id="Use_pattern_matching_may_change_code_meaning"> <source>Use pattern matching (may change code meaning)</source> <target state="new">Use pattern matching (may change code meaning)</target> <note /> </trans-unit> <trans-unit id="Use_range_operator"> <source>Use range operator</source> <target state="translated">Bereichsoperator verwenden</target> <note /> </trans-unit> <trans-unit id="Use_simple_using_statement"> <source>Use simple 'using' statement</source> <target state="translated">Einfache using-Anweisung verwenden</target> <note /> </trans-unit> <trans-unit id="Use_switch_expression"> <source>Use 'switch' expression</source> <target state="translated">Switch-Ausdruck verwenden</target> <note /> </trans-unit> <trans-unit id="Using_directives_must_be_placed_inside_of_a_namespace_declaration"> <source>Using directives must be placed inside of a namespace declaration</source> <target state="translated">Using-Anweisungen müssen in einer namespace-Deklaration platziert werden.</target> <note>{Locked="using"} "using" is a C# keyword and should not be localized. {Locked="namespace"} "namespace" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="Using_directives_must_be_placed_outside_of_a_namespace_declaration"> <source>Using directives must be placed outside of a namespace declaration</source> <target state="translated">Using-Anweisungen müssen außerhalb einer namespace-Deklaration platziert werden.</target> <note>{Locked="using"} "using" is a C# keyword and should not be localized. {Locked="namespace"} "namespace" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="Variable_declaration_can_be_deconstructed"> <source>Variable declaration can be deconstructed</source> <target state="translated">Die Variablendeklaration kann dekonstruiert werden.</target> <note /> </trans-unit> <trans-unit id="Variable_declaration_can_be_inlined"> <source>Variable declaration can be inlined</source> <target state="translated">Variablendeklaration kann inline erfolgen.</target> <note /> </trans-unit> <trans-unit id="Warning_colon_Moving_using_directives_may_change_code_meaning"> <source>Warning: Moving using directives may change code meaning.</source> <target state="translated">Warnung: Durch das Verschieben von using-Anweisungen kann sich die Codebedeutung ändern.</target> <note>{Locked="using"} "using" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="_0_can_be_simplified"> <source>{0} can be simplified</source> <target state="translated">{0} kann vereinfacht werden</target> <note /> </trans-unit> <trans-unit id="default_expression_can_be_simplified"> <source>'default' expression can be simplified</source> <target state="translated">'"default"-Ausdruck kann vereinfacht werden</target> <note /> </trans-unit> <trans-unit id="if_statement_can_be_simplified"> <source>'if' statement can be simplified</source> <target state="translated">Die If-Anweisung kann vereinfacht werden.</target> <note /> </trans-unit> <trans-unit id="new_expression_can_be_simplified"> <source>'new' expression can be simplified</source> <target state="translated">new-Ausdruck kann vereinfacht werden</target> <note /> </trans-unit> <trans-unit id="typeof_can_be_converted_ to_nameof"> <source>'typeof' can be converted to 'nameof'</source> <target state="translated">"typeof" kann in "nameof" konvertiert werden.</target> <note /> </trans-unit> <trans-unit id="use_var_instead_of_explicit_type"> <source>use 'var' instead of explicit type</source> <target state="translated">"var" anstelle des expliziten Typs verwenden</target> <note /> </trans-unit> <trans-unit id="Using_directive_is_unnecessary"> <source>Using directive is unnecessary.</source> <target state="translated">Using-Direktive ist unnötig.</target> <note /> </trans-unit> <trans-unit id="using_statement_can_be_simplified"> <source>'using' statement can be simplified</source> <target state="translated">Die using-Anweisung kann vereinfacht werden.</target> <note /> </trans-unit> </body> </file> </xliff>
1
dotnet/roslyn
55,427
Fixes #50462
Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
Blokyk
2021-08-05T01:17:37Z
2021-08-25T05:42:59Z
fefb8c2110625bc4908db4bbdaa367b12bfb1069
fb4ac545a1f1f365e7df570637699d9085ea4f87
Fixes #50462. Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
./src/Analyzers/CSharp/Analyzers/xlf/CSharpAnalyzersResources.es.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="es" original="../CSharpAnalyzersResources.resx"> <body> <trans-unit id="Add_braces"> <source>Add braces</source> <target state="translated">Agregar llaves</target> <note /> </trans-unit> <trans-unit id="Add_braces_to_0_statement"> <source>Add braces to '{0}' statement.</source> <target state="translated">Agregar llaves a la instrucción '{0}'.</target> <note /> </trans-unit> <trans-unit id="Blank_line_not_allowed_after_constructor_initializer_colon"> <source>Blank line not allowed after constructor initializer colon</source> <target state="translated">No se permite una línea en blanco después del signo de dos puntos del inicializador del constructor</target> <note /> </trans-unit> <trans-unit id="Consecutive_braces_must_not_have_a_blank_between_them"> <source>Consecutive braces must not have blank line between them</source> <target state="translated">Las llaves consecutivas no deben tener una línea en blanco entre ellas</target> <note /> </trans-unit> <trans-unit id="Convert_switch_statement_to_expression"> <source>Convert switch statement to expression</source> <target state="translated">Convertir una instrucción switch en expresión</target> <note /> </trans-unit> <trans-unit id="Convert_to_block_scoped_namespace"> <source>Convert to block scoped namespace</source> <target state="new">Convert to block scoped namespace</target> <note>{Locked="namespace"} "namespace" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="Convert_to_file_scoped_namespace"> <source>Convert to file-scoped namespace</source> <target state="new">Convert to file-scoped namespace</target> <note>{Locked="namespace"} "namespace" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="Deconstruct_variable_declaration"> <source>Deconstruct variable declaration</source> <target state="translated">Desconstruir la declaración de variable</target> <note /> </trans-unit> <trans-unit id="Delegate_invocation_can_be_simplified"> <source>Delegate invocation can be simplified.</source> <target state="translated">La invocación del delegado se puede simplificar.</target> <note /> </trans-unit> <trans-unit id="Discard_can_be_removed"> <source>Discard can be removed</source> <target state="translated">El descarte se puede quitar.</target> <note /> </trans-unit> <trans-unit id="Embedded_statements_must_be_on_their_own_line"> <source>Embedded statements must be on their own line</source> <target state="translated">Las instrucciones incrustadas deben estar en su propia línea</target> <note /> </trans-unit> <trans-unit id="Indexing_can_be_simplified"> <source>Indexing can be simplified</source> <target state="translated">La indexación de direcciones se puede simplificar</target> <note /> </trans-unit> <trans-unit id="Inline_variable_declaration"> <source>Inline variable declaration</source> <target state="translated">Declaración de variables alineada</target> <note /> </trans-unit> <trans-unit id="Misplaced_using_directive"> <source>Misplaced using directive</source> <target state="translated">Directiva using mal colocada</target> <note>{Locked="using"} "using" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="Move_misplaced_using_directives"> <source>Move misplaced using directives</source> <target state="translated">Mover directivas using mal colocadas</target> <note>{Locked="using"} "using" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="Make_readonly_fields_writable"> <source>Make readonly fields writable</source> <target state="translated">Convertir en editables los campos readonly</target> <note>{Locked="readonly"} "readonly" is C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="Local_function_can_be_made_static"> <source>Local function can be made static</source> <target state="translated">La función local se puede convertir en estática</target> <note /> </trans-unit> <trans-unit id="Make_local_function_static"> <source>Make local function 'static'</source> <target state="translated">Convertir la función local "static"</target> <note /> </trans-unit> <trans-unit id="Negate_expression_changes_semantics"> <source>Negate expression (changes semantics)</source> <target state="translated">Negar expresión (cambia la semántica)</target> <note /> </trans-unit> <trans-unit id="Null_check_can_be_clarified"> <source>Null check can be clarified</source> <target state="new">Null check can be clarified</target> <note /> </trans-unit> <trans-unit id="Prefer_null_check_over_type_check"> <source>Prefer 'null' check over type check</source> <target state="new">Prefer 'null' check over type check</target> <note /> </trans-unit> <trans-unit id="Remove_operator_preserves_semantics"> <source>Remove operator (preserves semantics)</source> <target state="translated">Quitar operador (conserva la semántica)</target> <note /> </trans-unit> <trans-unit id="Remove_suppression_operators"> <source>Remove suppression operators</source> <target state="translated">Quitar operadores de supresión</target> <note /> </trans-unit> <trans-unit id="Remove_unnecessary_suppression_operator"> <source>Remove unnecessary suppression operator</source> <target state="translated">Quitar operador de supresión innecesario</target> <note /> </trans-unit> <trans-unit id="Remove_unnessary_discard"> <source>Remove unnecessary discard</source> <target state="translated">Quitar un descarte innecesario</target> <note /> </trans-unit> <trans-unit id="Simplify_default_expression"> <source>Simplify 'default' expression</source> <target state="translated">Simplificar la expresión "predeterminada"</target> <note /> </trans-unit> <trans-unit id="Struct_contains_assignment_to_this_outside_of_constructor_Make_readonly_fields_writable"> <source>Struct contains assignment to 'this' outside of constructor. Make readonly fields writable.</source> <target state="translated">Struct contiene una asignación a "this" fuera del constructor. Convierta en editables los campos de solo lectura.</target> <note>{Locked="Struct"}{Locked="this"} these are C#/VB keywords and should not be localized.</note> </trans-unit> <trans-unit id="Suppression_operator_has_no_effect_and_can_be_misinterpreted"> <source>Suppression operator has no effect and can be misinterpreted</source> <target state="translated">El operador de supresión no tiene efecto y se puede interpretar incorrectamente</target> <note /> </trans-unit> <trans-unit id="Unreachable_code_detected"> <source>Unreachable code detected</source> <target state="translated">Se detectó código inaccesible</target> <note /> </trans-unit> <trans-unit id="Use_block_body_for_accessors"> <source>Use block body for accessors</source> <target state="translated">Usar cuerpo del bloque para los descriptores de acceso</target> <note /> </trans-unit> <trans-unit id="Use_block_body_for_constructors"> <source>Use block body for constructors</source> <target state="translated">Usar cuerpo del bloque para los constructores</target> <note /> </trans-unit> <trans-unit id="Use_block_body_for_indexers"> <source>Use block body for indexers</source> <target state="translated">Usar cuerpo del bloque para los indizadores</target> <note /> </trans-unit> <trans-unit id="Use_block_body_for_local_functions"> <source>Use block body for local functions</source> <target state="translated">Usar cuerpo del bloque para las funciones locales</target> <note /> </trans-unit> <trans-unit id="Use_block_body_for_methods"> <source>Use block body for methods</source> <target state="translated">Usar cuerpo del bloque para los métodos</target> <note /> </trans-unit> <trans-unit id="Use_block_body_for_operators"> <source>Use block body for operators</source> <target state="translated">Usar cuerpo del bloque para los operadores</target> <note /> </trans-unit> <trans-unit id="Use_block_body_for_properties"> <source>Use block body for properties</source> <target state="translated">Usar cuerpo del bloque para las propiedades</target> <note /> </trans-unit> <trans-unit id="Use_explicit_type"> <source>Use explicit type</source> <target state="translated">Usar un tipo explícito</target> <note /> </trans-unit> <trans-unit id="Use_explicit_type_instead_of_var"> <source>Use explicit type instead of 'var'</source> <target state="translated">Usar un tipo explícito en lugar de 'var'</target> <note /> </trans-unit> <trans-unit id="Use_expression_body_for_accessors"> <source>Use expression body for accessors</source> <target state="translated">Usar cuerpo de expresiones para los descriptores de acceso</target> <note /> </trans-unit> <trans-unit id="Use_expression_body_for_constructors"> <source>Use expression body for constructors</source> <target state="translated">Usar cuerpo de expresiones para los constructores</target> <note /> </trans-unit> <trans-unit id="Use_expression_body_for_indexers"> <source>Use expression body for indexers</source> <target state="translated">Usar cuerpo de expresiones para los indizadores</target> <note /> </trans-unit> <trans-unit id="Use_expression_body_for_local_functions"> <source>Use expression body for local functions</source> <target state="translated">Usar el cuerpo de la expresión para las funciones locales</target> <note /> </trans-unit> <trans-unit id="Use_expression_body_for_methods"> <source>Use expression body for methods</source> <target state="translated">Usar cuerpo de expresiones para los métodos</target> <note /> </trans-unit> <trans-unit id="Use_expression_body_for_operators"> <source>Use expression body for operators</source> <target state="translated">Usar cuerpo de expresiones para los operadores</target> <note /> </trans-unit> <trans-unit id="Use_expression_body_for_properties"> <source>Use expression body for properties</source> <target state="translated">Usar cuerpo de expresiones para las propiedades</target> <note /> </trans-unit> <trans-unit id="Use_implicit_type"> <source>Use implicit type</source> <target state="translated">Usar un tipo implícito</target> <note /> </trans-unit> <trans-unit id="Use_index_operator"> <source>Use index operator</source> <target state="translated">Usar operador de índice</target> <note /> </trans-unit> <trans-unit id="Use_is_null_check"> <source>Use 'is null' check</source> <target state="translated">Usar comprobación "is null"</target> <note /> </trans-unit> <trans-unit id="Use_local_function"> <source>Use local function</source> <target state="translated">Usar función local</target> <note /> </trans-unit> <trans-unit id="Use_new"> <source>Use 'new(...)'</source> <target state="translated">Usar "new(...)"</target> <note>{Locked="new(...)"} This is a C# construct and should not be localized.</note> </trans-unit> <trans-unit id="Use_pattern_matching"> <source>Use pattern matching</source> <target state="translated">Usar coincidencia de patrones</target> <note /> </trans-unit> <trans-unit id="Use_range_operator"> <source>Use range operator</source> <target state="translated">Usar el operador de intervalo</target> <note /> </trans-unit> <trans-unit id="Use_simple_using_statement"> <source>Use simple 'using' statement</source> <target state="translated">Use la instrucción "using" simple</target> <note /> </trans-unit> <trans-unit id="Use_switch_expression"> <source>Use 'switch' expression</source> <target state="translated">Usar la expresión "switch"</target> <note /> </trans-unit> <trans-unit id="Using_directives_must_be_placed_inside_of_a_namespace_declaration"> <source>Using directives must be placed inside of a namespace declaration</source> <target state="translated">Las directivas using deben colocarse dentro de una declaración de namespace</target> <note>{Locked="using"} "using" is a C# keyword and should not be localized. {Locked="namespace"} "namespace" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="Using_directives_must_be_placed_outside_of_a_namespace_declaration"> <source>Using directives must be placed outside of a namespace declaration</source> <target state="translated">Las directivas using deben colocarse fuera de una declaración de namespace</target> <note>{Locked="using"} "using" is a C# keyword and should not be localized. {Locked="namespace"} "namespace" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="Variable_declaration_can_be_deconstructed"> <source>Variable declaration can be deconstructed</source> <target state="translated">La declaración de variables se puede desconstruir.</target> <note /> </trans-unit> <trans-unit id="Variable_declaration_can_be_inlined"> <source>Variable declaration can be inlined</source> <target state="translated">La declaración de variables se puede insertar</target> <note /> </trans-unit> <trans-unit id="Warning_colon_Moving_using_directives_may_change_code_meaning"> <source>Warning: Moving using directives may change code meaning.</source> <target state="translated">Advertencia: El movimiento de directivas using puede cambiar el significado del código.</target> <note>{Locked="using"} "using" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="_0_can_be_simplified"> <source>{0} can be simplified</source> <target state="translated">{0} se puede simplificar.</target> <note /> </trans-unit> <trans-unit id="default_expression_can_be_simplified"> <source>'default' expression can be simplified</source> <target state="translated">'La expresión "predeterminada" se puede simplificar</target> <note /> </trans-unit> <trans-unit id="if_statement_can_be_simplified"> <source>'if' statement can be simplified</source> <target state="translated">La instrucción "if" se puede simplificar</target> <note /> </trans-unit> <trans-unit id="new_expression_can_be_simplified"> <source>'new' expression can be simplified</source> <target state="translated">La expresión "new" se puede simplificar.</target> <note /> </trans-unit> <trans-unit id="typeof_can_be_converted_ to_nameof"> <source>'typeof' can be converted to 'nameof'</source> <target state="translated">"typeof" puede convertirse en "nameof"</target> <note /> </trans-unit> <trans-unit id="use_var_instead_of_explicit_type"> <source>use 'var' instead of explicit type</source> <target state="translated">Usar 'var' en lugar de un tipo explícito</target> <note /> </trans-unit> <trans-unit id="Using_directive_is_unnecessary"> <source>Using directive is unnecessary.</source> <target state="translated">El uso de la directiva no es necesario.</target> <note /> </trans-unit> <trans-unit id="using_statement_can_be_simplified"> <source>'using' statement can be simplified</source> <target state="translated">La instrucción "using" se puede simplificar</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="es" original="../CSharpAnalyzersResources.resx"> <body> <trans-unit id="Add_braces"> <source>Add braces</source> <target state="translated">Agregar llaves</target> <note /> </trans-unit> <trans-unit id="Add_braces_to_0_statement"> <source>Add braces to '{0}' statement.</source> <target state="translated">Agregar llaves a la instrucción '{0}'.</target> <note /> </trans-unit> <trans-unit id="Blank_line_not_allowed_after_constructor_initializer_colon"> <source>Blank line not allowed after constructor initializer colon</source> <target state="translated">No se permite una línea en blanco después del signo de dos puntos del inicializador del constructor</target> <note /> </trans-unit> <trans-unit id="Consecutive_braces_must_not_have_a_blank_between_them"> <source>Consecutive braces must not have blank line between them</source> <target state="translated">Las llaves consecutivas no deben tener una línea en blanco entre ellas</target> <note /> </trans-unit> <trans-unit id="Convert_switch_statement_to_expression"> <source>Convert switch statement to expression</source> <target state="translated">Convertir una instrucción switch en expresión</target> <note /> </trans-unit> <trans-unit id="Convert_to_block_scoped_namespace"> <source>Convert to block scoped namespace</source> <target state="new">Convert to block scoped namespace</target> <note>{Locked="namespace"} "namespace" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="Convert_to_file_scoped_namespace"> <source>Convert to file-scoped namespace</source> <target state="new">Convert to file-scoped namespace</target> <note>{Locked="namespace"} "namespace" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="Deconstruct_variable_declaration"> <source>Deconstruct variable declaration</source> <target state="translated">Desconstruir la declaración de variable</target> <note /> </trans-unit> <trans-unit id="Delegate_invocation_can_be_simplified"> <source>Delegate invocation can be simplified.</source> <target state="translated">La invocación del delegado se puede simplificar.</target> <note /> </trans-unit> <trans-unit id="Discard_can_be_removed"> <source>Discard can be removed</source> <target state="translated">El descarte se puede quitar.</target> <note /> </trans-unit> <trans-unit id="Embedded_statements_must_be_on_their_own_line"> <source>Embedded statements must be on their own line</source> <target state="translated">Las instrucciones incrustadas deben estar en su propia línea</target> <note /> </trans-unit> <trans-unit id="Indexing_can_be_simplified"> <source>Indexing can be simplified</source> <target state="translated">La indexación de direcciones se puede simplificar</target> <note /> </trans-unit> <trans-unit id="Inline_variable_declaration"> <source>Inline variable declaration</source> <target state="translated">Declaración de variables alineada</target> <note /> </trans-unit> <trans-unit id="Misplaced_using_directive"> <source>Misplaced using directive</source> <target state="translated">Directiva using mal colocada</target> <note>{Locked="using"} "using" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="Move_misplaced_using_directives"> <source>Move misplaced using directives</source> <target state="translated">Mover directivas using mal colocadas</target> <note>{Locked="using"} "using" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="Make_readonly_fields_writable"> <source>Make readonly fields writable</source> <target state="translated">Convertir en editables los campos readonly</target> <note>{Locked="readonly"} "readonly" is C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="Local_function_can_be_made_static"> <source>Local function can be made static</source> <target state="translated">La función local se puede convertir en estática</target> <note /> </trans-unit> <trans-unit id="Make_local_function_static"> <source>Make local function 'static'</source> <target state="translated">Convertir la función local "static"</target> <note /> </trans-unit> <trans-unit id="Negate_expression_changes_semantics"> <source>Negate expression (changes semantics)</source> <target state="translated">Negar expresión (cambia la semántica)</target> <note /> </trans-unit> <trans-unit id="Null_check_can_be_clarified"> <source>Null check can be clarified</source> <target state="new">Null check can be clarified</target> <note /> </trans-unit> <trans-unit id="Prefer_null_check_over_type_check"> <source>Prefer 'null' check over type check</source> <target state="new">Prefer 'null' check over type check</target> <note /> </trans-unit> <trans-unit id="Remove_operator_preserves_semantics"> <source>Remove operator (preserves semantics)</source> <target state="translated">Quitar operador (conserva la semántica)</target> <note /> </trans-unit> <trans-unit id="Remove_suppression_operators"> <source>Remove suppression operators</source> <target state="translated">Quitar operadores de supresión</target> <note /> </trans-unit> <trans-unit id="Remove_unnecessary_suppression_operator"> <source>Remove unnecessary suppression operator</source> <target state="translated">Quitar operador de supresión innecesario</target> <note /> </trans-unit> <trans-unit id="Remove_unnessary_discard"> <source>Remove unnecessary discard</source> <target state="translated">Quitar un descarte innecesario</target> <note /> </trans-unit> <trans-unit id="Simplify_default_expression"> <source>Simplify 'default' expression</source> <target state="translated">Simplificar la expresión "predeterminada"</target> <note /> </trans-unit> <trans-unit id="Struct_contains_assignment_to_this_outside_of_constructor_Make_readonly_fields_writable"> <source>Struct contains assignment to 'this' outside of constructor. Make readonly fields writable.</source> <target state="translated">Struct contiene una asignación a "this" fuera del constructor. Convierta en editables los campos de solo lectura.</target> <note>{Locked="Struct"}{Locked="this"} these are C#/VB keywords and should not be localized.</note> </trans-unit> <trans-unit id="Suppression_operator_has_no_effect_and_can_be_misinterpreted"> <source>Suppression operator has no effect and can be misinterpreted</source> <target state="translated">El operador de supresión no tiene efecto y se puede interpretar incorrectamente</target> <note /> </trans-unit> <trans-unit id="Unreachable_code_detected"> <source>Unreachable code detected</source> <target state="translated">Se detectó código inaccesible</target> <note /> </trans-unit> <trans-unit id="Use_block_body_for_accessors"> <source>Use block body for accessors</source> <target state="translated">Usar cuerpo del bloque para los descriptores de acceso</target> <note /> </trans-unit> <trans-unit id="Use_block_body_for_constructors"> <source>Use block body for constructors</source> <target state="translated">Usar cuerpo del bloque para los constructores</target> <note /> </trans-unit> <trans-unit id="Use_block_body_for_indexers"> <source>Use block body for indexers</source> <target state="translated">Usar cuerpo del bloque para los indizadores</target> <note /> </trans-unit> <trans-unit id="Use_block_body_for_local_functions"> <source>Use block body for local functions</source> <target state="translated">Usar cuerpo del bloque para las funciones locales</target> <note /> </trans-unit> <trans-unit id="Use_block_body_for_methods"> <source>Use block body for methods</source> <target state="translated">Usar cuerpo del bloque para los métodos</target> <note /> </trans-unit> <trans-unit id="Use_block_body_for_operators"> <source>Use block body for operators</source> <target state="translated">Usar cuerpo del bloque para los operadores</target> <note /> </trans-unit> <trans-unit id="Use_block_body_for_properties"> <source>Use block body for properties</source> <target state="translated">Usar cuerpo del bloque para las propiedades</target> <note /> </trans-unit> <trans-unit id="Use_explicit_type"> <source>Use explicit type</source> <target state="translated">Usar un tipo explícito</target> <note /> </trans-unit> <trans-unit id="Use_explicit_type_instead_of_var"> <source>Use explicit type instead of 'var'</source> <target state="translated">Usar un tipo explícito en lugar de 'var'</target> <note /> </trans-unit> <trans-unit id="Use_expression_body_for_accessors"> <source>Use expression body for accessors</source> <target state="translated">Usar cuerpo de expresiones para los descriptores de acceso</target> <note /> </trans-unit> <trans-unit id="Use_expression_body_for_constructors"> <source>Use expression body for constructors</source> <target state="translated">Usar cuerpo de expresiones para los constructores</target> <note /> </trans-unit> <trans-unit id="Use_expression_body_for_indexers"> <source>Use expression body for indexers</source> <target state="translated">Usar cuerpo de expresiones para los indizadores</target> <note /> </trans-unit> <trans-unit id="Use_expression_body_for_local_functions"> <source>Use expression body for local functions</source> <target state="translated">Usar el cuerpo de la expresión para las funciones locales</target> <note /> </trans-unit> <trans-unit id="Use_expression_body_for_methods"> <source>Use expression body for methods</source> <target state="translated">Usar cuerpo de expresiones para los métodos</target> <note /> </trans-unit> <trans-unit id="Use_expression_body_for_operators"> <source>Use expression body for operators</source> <target state="translated">Usar cuerpo de expresiones para los operadores</target> <note /> </trans-unit> <trans-unit id="Use_expression_body_for_properties"> <source>Use expression body for properties</source> <target state="translated">Usar cuerpo de expresiones para las propiedades</target> <note /> </trans-unit> <trans-unit id="Use_implicit_type"> <source>Use implicit type</source> <target state="translated">Usar un tipo implícito</target> <note /> </trans-unit> <trans-unit id="Use_index_operator"> <source>Use index operator</source> <target state="translated">Usar operador de índice</target> <note /> </trans-unit> <trans-unit id="Use_is_null_check"> <source>Use 'is null' check</source> <target state="translated">Usar comprobación "is null"</target> <note /> </trans-unit> <trans-unit id="Use_local_function"> <source>Use local function</source> <target state="translated">Usar función local</target> <note /> </trans-unit> <trans-unit id="Use_new"> <source>Use 'new(...)'</source> <target state="translated">Usar "new(...)"</target> <note>{Locked="new(...)"} This is a C# construct and should not be localized.</note> </trans-unit> <trans-unit id="Use_pattern_matching"> <source>Use pattern matching</source> <target state="translated">Usar coincidencia de patrones</target> <note /> </trans-unit> <trans-unit id="Use_pattern_matching_may_change_code_meaning"> <source>Use pattern matching (may change code meaning)</source> <target state="new">Use pattern matching (may change code meaning)</target> <note /> </trans-unit> <trans-unit id="Use_range_operator"> <source>Use range operator</source> <target state="translated">Usar el operador de intervalo</target> <note /> </trans-unit> <trans-unit id="Use_simple_using_statement"> <source>Use simple 'using' statement</source> <target state="translated">Use la instrucción "using" simple</target> <note /> </trans-unit> <trans-unit id="Use_switch_expression"> <source>Use 'switch' expression</source> <target state="translated">Usar la expresión "switch"</target> <note /> </trans-unit> <trans-unit id="Using_directives_must_be_placed_inside_of_a_namespace_declaration"> <source>Using directives must be placed inside of a namespace declaration</source> <target state="translated">Las directivas using deben colocarse dentro de una declaración de namespace</target> <note>{Locked="using"} "using" is a C# keyword and should not be localized. {Locked="namespace"} "namespace" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="Using_directives_must_be_placed_outside_of_a_namespace_declaration"> <source>Using directives must be placed outside of a namespace declaration</source> <target state="translated">Las directivas using deben colocarse fuera de una declaración de namespace</target> <note>{Locked="using"} "using" is a C# keyword and should not be localized. {Locked="namespace"} "namespace" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="Variable_declaration_can_be_deconstructed"> <source>Variable declaration can be deconstructed</source> <target state="translated">La declaración de variables se puede desconstruir.</target> <note /> </trans-unit> <trans-unit id="Variable_declaration_can_be_inlined"> <source>Variable declaration can be inlined</source> <target state="translated">La declaración de variables se puede insertar</target> <note /> </trans-unit> <trans-unit id="Warning_colon_Moving_using_directives_may_change_code_meaning"> <source>Warning: Moving using directives may change code meaning.</source> <target state="translated">Advertencia: El movimiento de directivas using puede cambiar el significado del código.</target> <note>{Locked="using"} "using" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="_0_can_be_simplified"> <source>{0} can be simplified</source> <target state="translated">{0} se puede simplificar.</target> <note /> </trans-unit> <trans-unit id="default_expression_can_be_simplified"> <source>'default' expression can be simplified</source> <target state="translated">'La expresión "predeterminada" se puede simplificar</target> <note /> </trans-unit> <trans-unit id="if_statement_can_be_simplified"> <source>'if' statement can be simplified</source> <target state="translated">La instrucción "if" se puede simplificar</target> <note /> </trans-unit> <trans-unit id="new_expression_can_be_simplified"> <source>'new' expression can be simplified</source> <target state="translated">La expresión "new" se puede simplificar.</target> <note /> </trans-unit> <trans-unit id="typeof_can_be_converted_ to_nameof"> <source>'typeof' can be converted to 'nameof'</source> <target state="translated">"typeof" puede convertirse en "nameof"</target> <note /> </trans-unit> <trans-unit id="use_var_instead_of_explicit_type"> <source>use 'var' instead of explicit type</source> <target state="translated">Usar 'var' en lugar de un tipo explícito</target> <note /> </trans-unit> <trans-unit id="Using_directive_is_unnecessary"> <source>Using directive is unnecessary.</source> <target state="translated">El uso de la directiva no es necesario.</target> <note /> </trans-unit> <trans-unit id="using_statement_can_be_simplified"> <source>'using' statement can be simplified</source> <target state="translated">La instrucción "using" se puede simplificar</target> <note /> </trans-unit> </body> </file> </xliff>
1
dotnet/roslyn
55,427
Fixes #50462
Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
Blokyk
2021-08-05T01:17:37Z
2021-08-25T05:42:59Z
fefb8c2110625bc4908db4bbdaa367b12bfb1069
fb4ac545a1f1f365e7df570637699d9085ea4f87
Fixes #50462. Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
./src/Analyzers/CSharp/Analyzers/xlf/CSharpAnalyzersResources.fr.xlf
<?xml version="1.0" encoding="utf-8"?> <xliff xmlns="urn:oasis:names:tc:xliff:document:1.2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="1.2" xsi:schemaLocation="urn:oasis:names:tc:xliff:document:1.2 xliff-core-1.2-transitional.xsd"> <file datatype="xml" source-language="en" target-language="fr" original="../CSharpAnalyzersResources.resx"> <body> <trans-unit id="Add_braces"> <source>Add braces</source> <target state="translated">Ajouter des accolades</target> <note /> </trans-unit> <trans-unit id="Add_braces_to_0_statement"> <source>Add braces to '{0}' statement.</source> <target state="translated">Ajouter des accolades à l'instruction '{0}'.</target> <note /> </trans-unit> <trans-unit id="Blank_line_not_allowed_after_constructor_initializer_colon"> <source>Blank line not allowed after constructor initializer colon</source> <target state="translated">Ligne vide non autorisée après le signe des deux-points de l'initialiseur du constructeur</target> <note /> </trans-unit> <trans-unit id="Consecutive_braces_must_not_have_a_blank_between_them"> <source>Consecutive braces must not have blank line between them</source> <target state="translated">Les accolades consécutives ne doivent pas avoir de ligne vide entre elles</target> <note /> </trans-unit> <trans-unit id="Convert_switch_statement_to_expression"> <source>Convert switch statement to expression</source> <target state="translated">Convertir l'instruction switch en expression</target> <note /> </trans-unit> <trans-unit id="Convert_to_block_scoped_namespace"> <source>Convert to block scoped namespace</source> <target state="new">Convert to block scoped namespace</target> <note>{Locked="namespace"} "namespace" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="Convert_to_file_scoped_namespace"> <source>Convert to file-scoped namespace</source> <target state="new">Convert to file-scoped namespace</target> <note>{Locked="namespace"} "namespace" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="Deconstruct_variable_declaration"> <source>Deconstruct variable declaration</source> <target state="translated">Déconstruire la déclaration de variable</target> <note /> </trans-unit> <trans-unit id="Delegate_invocation_can_be_simplified"> <source>Delegate invocation can be simplified.</source> <target state="translated">L'appel de délégué peut être simplifié.</target> <note /> </trans-unit> <trans-unit id="Discard_can_be_removed"> <source>Discard can be removed</source> <target state="translated">Vous pouvez supprimer le discard</target> <note /> </trans-unit> <trans-unit id="Embedded_statements_must_be_on_their_own_line"> <source>Embedded statements must be on their own line</source> <target state="translated">Les instructions imbriquées doivent être placées sur leur propre ligne</target> <note /> </trans-unit> <trans-unit id="Indexing_can_be_simplified"> <source>Indexing can be simplified</source> <target state="translated">L'indexation peut être simplifiée</target> <note /> </trans-unit> <trans-unit id="Inline_variable_declaration"> <source>Inline variable declaration</source> <target state="translated">Déclaration de variable inline</target> <note /> </trans-unit> <trans-unit id="Misplaced_using_directive"> <source>Misplaced using directive</source> <target state="translated">Directive using mal placée</target> <note>{Locked="using"} "using" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="Move_misplaced_using_directives"> <source>Move misplaced using directives</source> <target state="translated">Déplacer les directives using mal placées</target> <note>{Locked="using"} "using" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="Make_readonly_fields_writable"> <source>Make readonly fields writable</source> <target state="translated">Rendre les champs readonly accessibles en écriture</target> <note>{Locked="readonly"} "readonly" is C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="Local_function_can_be_made_static"> <source>Local function can be made static</source> <target state="translated">Une fonction locale peut être rendue statique</target> <note /> </trans-unit> <trans-unit id="Make_local_function_static"> <source>Make local function 'static'</source> <target state="translated">Rendre la fonction locale 'static'</target> <note /> </trans-unit> <trans-unit id="Negate_expression_changes_semantics"> <source>Negate expression (changes semantics)</source> <target state="translated">Inverser l'expression (change la sémantique)</target> <note /> </trans-unit> <trans-unit id="Null_check_can_be_clarified"> <source>Null check can be clarified</source> <target state="new">Null check can be clarified</target> <note /> </trans-unit> <trans-unit id="Prefer_null_check_over_type_check"> <source>Prefer 'null' check over type check</source> <target state="new">Prefer 'null' check over type check</target> <note /> </trans-unit> <trans-unit id="Remove_operator_preserves_semantics"> <source>Remove operator (preserves semantics)</source> <target state="translated">Supprimer l'opérateur (préserve la sémantique)</target> <note /> </trans-unit> <trans-unit id="Remove_suppression_operators"> <source>Remove suppression operators</source> <target state="translated">Supprimer les opérateurs de suppression</target> <note /> </trans-unit> <trans-unit id="Remove_unnecessary_suppression_operator"> <source>Remove unnecessary suppression operator</source> <target state="translated">Supprimer l'opérateur de suppression inutile</target> <note /> </trans-unit> <trans-unit id="Remove_unnessary_discard"> <source>Remove unnecessary discard</source> <target state="translated">Supprimer tout discard inutile</target> <note /> </trans-unit> <trans-unit id="Simplify_default_expression"> <source>Simplify 'default' expression</source> <target state="translated">Simplifier l'expression 'default'</target> <note /> </trans-unit> <trans-unit id="Struct_contains_assignment_to_this_outside_of_constructor_Make_readonly_fields_writable"> <source>Struct contains assignment to 'this' outside of constructor. Make readonly fields writable.</source> <target state="translated">Struct contient une assignation à 'this' en dehors du constructeur. Rend les champs readonly accessibles en écriture.</target> <note>{Locked="Struct"}{Locked="this"} these are C#/VB keywords and should not be localized.</note> </trans-unit> <trans-unit id="Suppression_operator_has_no_effect_and_can_be_misinterpreted"> <source>Suppression operator has no effect and can be misinterpreted</source> <target state="translated">L'opérateur de suppression n'a aucun effet et peut être mal interprété</target> <note /> </trans-unit> <trans-unit id="Unreachable_code_detected"> <source>Unreachable code detected</source> <target state="translated">Code inaccessible détecté</target> <note /> </trans-unit> <trans-unit id="Use_block_body_for_accessors"> <source>Use block body for accessors</source> <target state="translated">Utiliser un corps de bloc pour les accesseurs</target> <note /> </trans-unit> <trans-unit id="Use_block_body_for_constructors"> <source>Use block body for constructors</source> <target state="translated">Utiliser un corps de bloc pour les constructeurs</target> <note /> </trans-unit> <trans-unit id="Use_block_body_for_indexers"> <source>Use block body for indexers</source> <target state="translated">Utiliser un corps de bloc pour les indexeurs</target> <note /> </trans-unit> <trans-unit id="Use_block_body_for_local_functions"> <source>Use block body for local functions</source> <target state="translated">Utiliser le corps de bloc pour les fonctions locales</target> <note /> </trans-unit> <trans-unit id="Use_block_body_for_methods"> <source>Use block body for methods</source> <target state="translated">Utiliser un corps de bloc pour les méthodes</target> <note /> </trans-unit> <trans-unit id="Use_block_body_for_operators"> <source>Use block body for operators</source> <target state="translated">Utiliser un corps de bloc pour les opérateurs</target> <note /> </trans-unit> <trans-unit id="Use_block_body_for_properties"> <source>Use block body for properties</source> <target state="translated">Utiliser un corps de bloc pour les propriétés</target> <note /> </trans-unit> <trans-unit id="Use_explicit_type"> <source>Use explicit type</source> <target state="translated">Utiliser un type explicite</target> <note /> </trans-unit> <trans-unit id="Use_explicit_type_instead_of_var"> <source>Use explicit type instead of 'var'</source> <target state="translated">Utiliser un type explicite au lieu de 'var'</target> <note /> </trans-unit> <trans-unit id="Use_expression_body_for_accessors"> <source>Use expression body for accessors</source> <target state="translated">Utiliser un corps d'expression pour les accesseurs</target> <note /> </trans-unit> <trans-unit id="Use_expression_body_for_constructors"> <source>Use expression body for constructors</source> <target state="translated">Utiliser un corps d'expression pour les constructeurs</target> <note /> </trans-unit> <trans-unit id="Use_expression_body_for_indexers"> <source>Use expression body for indexers</source> <target state="translated">Utiliser un corps d'expression pour les indexeurs</target> <note /> </trans-unit> <trans-unit id="Use_expression_body_for_local_functions"> <source>Use expression body for local functions</source> <target state="translated">Utiliser le corps d'expression pour des fonctions locales</target> <note /> </trans-unit> <trans-unit id="Use_expression_body_for_methods"> <source>Use expression body for methods</source> <target state="translated">Utiliser un corps d'expression pour les méthodes</target> <note /> </trans-unit> <trans-unit id="Use_expression_body_for_operators"> <source>Use expression body for operators</source> <target state="translated">Utiliser un corps d'expression pour les opérateurs</target> <note /> </trans-unit> <trans-unit id="Use_expression_body_for_properties"> <source>Use expression body for properties</source> <target state="translated">Utiliser un corps d'expression pour les propriétés</target> <note /> </trans-unit> <trans-unit id="Use_implicit_type"> <source>Use implicit type</source> <target state="translated">Utiliser un type implicite</target> <note /> </trans-unit> <trans-unit id="Use_index_operator"> <source>Use index operator</source> <target state="translated">Utiliser l'opérateur d'index</target> <note /> </trans-unit> <trans-unit id="Use_is_null_check"> <source>Use 'is null' check</source> <target state="translated">Utiliser la vérification 'is null'</target> <note /> </trans-unit> <trans-unit id="Use_local_function"> <source>Use local function</source> <target state="translated">Utiliser une fonction locale</target> <note /> </trans-unit> <trans-unit id="Use_new"> <source>Use 'new(...)'</source> <target state="translated">Utiliser 'new(...)'</target> <note>{Locked="new(...)"} This is a C# construct and should not be localized.</note> </trans-unit> <trans-unit id="Use_pattern_matching"> <source>Use pattern matching</source> <target state="translated">Utiliser les critères spéciaux</target> <note /> </trans-unit> <trans-unit id="Use_range_operator"> <source>Use range operator</source> <target state="translated">Utiliser l'opérateur de plage</target> <note /> </trans-unit> <trans-unit id="Use_simple_using_statement"> <source>Use simple 'using' statement</source> <target state="translated">Utiliser une instruction 'using' simple</target> <note /> </trans-unit> <trans-unit id="Use_switch_expression"> <source>Use 'switch' expression</source> <target state="translated">Utiliser l'expression 'switch'</target> <note /> </trans-unit> <trans-unit id="Using_directives_must_be_placed_inside_of_a_namespace_declaration"> <source>Using directives must be placed inside of a namespace declaration</source> <target state="translated">Les directives using doivent être placées dans une déclaration namespace</target> <note>{Locked="using"} "using" is a C# keyword and should not be localized. {Locked="namespace"} "namespace" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="Using_directives_must_be_placed_outside_of_a_namespace_declaration"> <source>Using directives must be placed outside of a namespace declaration</source> <target state="translated">Les directives using doivent être placées en dehors d'une déclaration namespace</target> <note>{Locked="using"} "using" is a C# keyword and should not be localized. {Locked="namespace"} "namespace" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="Variable_declaration_can_be_deconstructed"> <source>Variable declaration can be deconstructed</source> <target state="translated">La déclaration de variable peut être déconstruite</target> <note /> </trans-unit> <trans-unit id="Variable_declaration_can_be_inlined"> <source>Variable declaration can be inlined</source> <target state="translated">La déclaration de variable peut être inlined</target> <note /> </trans-unit> <trans-unit id="Warning_colon_Moving_using_directives_may_change_code_meaning"> <source>Warning: Moving using directives may change code meaning.</source> <target state="translated">Avertissement : Le déplacement des directives using peut changer la signification du code.</target> <note>{Locked="using"} "using" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="_0_can_be_simplified"> <source>{0} can be simplified</source> <target state="translated">{0} peut être simplifié</target> <note /> </trans-unit> <trans-unit id="default_expression_can_be_simplified"> <source>'default' expression can be simplified</source> <target state="translated">'l'expression 'default' peut être simplifiée</target> <note /> </trans-unit> <trans-unit id="if_statement_can_be_simplified"> <source>'if' statement can be simplified</source> <target state="translated">L'instruction 'if' peut être simplifiée</target> <note /> </trans-unit> <trans-unit id="new_expression_can_be_simplified"> <source>'new' expression can be simplified</source> <target state="translated">L'expression 'new' peut être simplifiée</target> <note /> </trans-unit> <trans-unit id="typeof_can_be_converted_ to_nameof"> <source>'typeof' can be converted to 'nameof'</source> <target state="translated">'typeof' peut être converti en 'nameof'</target> <note /> </trans-unit> <trans-unit id="use_var_instead_of_explicit_type"> <source>use 'var' instead of explicit type</source> <target state="translated">utiliser 'var' au lieu d'un type explicite</target> <note /> </trans-unit> <trans-unit id="Using_directive_is_unnecessary"> <source>Using directive is unnecessary.</source> <target state="translated">La directive using n'est pas nécessaire.</target> <note /> </trans-unit> <trans-unit id="using_statement_can_be_simplified"> <source>'using' statement can be simplified</source> <target state="translated">L'instruction 'using' peut être simplifiée</target> <note /> </trans-unit> </body> </file> </xliff>
<?xml version="1.0" encoding="utf-8"?> <xliff xmlns="urn:oasis:names:tc:xliff:document:1.2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="1.2" xsi:schemaLocation="urn:oasis:names:tc:xliff:document:1.2 xliff-core-1.2-transitional.xsd"> <file datatype="xml" source-language="en" target-language="fr" original="../CSharpAnalyzersResources.resx"> <body> <trans-unit id="Add_braces"> <source>Add braces</source> <target state="translated">Ajouter des accolades</target> <note /> </trans-unit> <trans-unit id="Add_braces_to_0_statement"> <source>Add braces to '{0}' statement.</source> <target state="translated">Ajouter des accolades à l'instruction '{0}'.</target> <note /> </trans-unit> <trans-unit id="Blank_line_not_allowed_after_constructor_initializer_colon"> <source>Blank line not allowed after constructor initializer colon</source> <target state="translated">Ligne vide non autorisée après le signe des deux-points de l'initialiseur du constructeur</target> <note /> </trans-unit> <trans-unit id="Consecutive_braces_must_not_have_a_blank_between_them"> <source>Consecutive braces must not have blank line between them</source> <target state="translated">Les accolades consécutives ne doivent pas avoir de ligne vide entre elles</target> <note /> </trans-unit> <trans-unit id="Convert_switch_statement_to_expression"> <source>Convert switch statement to expression</source> <target state="translated">Convertir l'instruction switch en expression</target> <note /> </trans-unit> <trans-unit id="Convert_to_block_scoped_namespace"> <source>Convert to block scoped namespace</source> <target state="new">Convert to block scoped namespace</target> <note>{Locked="namespace"} "namespace" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="Convert_to_file_scoped_namespace"> <source>Convert to file-scoped namespace</source> <target state="new">Convert to file-scoped namespace</target> <note>{Locked="namespace"} "namespace" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="Deconstruct_variable_declaration"> <source>Deconstruct variable declaration</source> <target state="translated">Déconstruire la déclaration de variable</target> <note /> </trans-unit> <trans-unit id="Delegate_invocation_can_be_simplified"> <source>Delegate invocation can be simplified.</source> <target state="translated">L'appel de délégué peut être simplifié.</target> <note /> </trans-unit> <trans-unit id="Discard_can_be_removed"> <source>Discard can be removed</source> <target state="translated">Vous pouvez supprimer le discard</target> <note /> </trans-unit> <trans-unit id="Embedded_statements_must_be_on_their_own_line"> <source>Embedded statements must be on their own line</source> <target state="translated">Les instructions imbriquées doivent être placées sur leur propre ligne</target> <note /> </trans-unit> <trans-unit id="Indexing_can_be_simplified"> <source>Indexing can be simplified</source> <target state="translated">L'indexation peut être simplifiée</target> <note /> </trans-unit> <trans-unit id="Inline_variable_declaration"> <source>Inline variable declaration</source> <target state="translated">Déclaration de variable inline</target> <note /> </trans-unit> <trans-unit id="Misplaced_using_directive"> <source>Misplaced using directive</source> <target state="translated">Directive using mal placée</target> <note>{Locked="using"} "using" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="Move_misplaced_using_directives"> <source>Move misplaced using directives</source> <target state="translated">Déplacer les directives using mal placées</target> <note>{Locked="using"} "using" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="Make_readonly_fields_writable"> <source>Make readonly fields writable</source> <target state="translated">Rendre les champs readonly accessibles en écriture</target> <note>{Locked="readonly"} "readonly" is C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="Local_function_can_be_made_static"> <source>Local function can be made static</source> <target state="translated">Une fonction locale peut être rendue statique</target> <note /> </trans-unit> <trans-unit id="Make_local_function_static"> <source>Make local function 'static'</source> <target state="translated">Rendre la fonction locale 'static'</target> <note /> </trans-unit> <trans-unit id="Negate_expression_changes_semantics"> <source>Negate expression (changes semantics)</source> <target state="translated">Inverser l'expression (change la sémantique)</target> <note /> </trans-unit> <trans-unit id="Null_check_can_be_clarified"> <source>Null check can be clarified</source> <target state="new">Null check can be clarified</target> <note /> </trans-unit> <trans-unit id="Prefer_null_check_over_type_check"> <source>Prefer 'null' check over type check</source> <target state="new">Prefer 'null' check over type check</target> <note /> </trans-unit> <trans-unit id="Remove_operator_preserves_semantics"> <source>Remove operator (preserves semantics)</source> <target state="translated">Supprimer l'opérateur (préserve la sémantique)</target> <note /> </trans-unit> <trans-unit id="Remove_suppression_operators"> <source>Remove suppression operators</source> <target state="translated">Supprimer les opérateurs de suppression</target> <note /> </trans-unit> <trans-unit id="Remove_unnecessary_suppression_operator"> <source>Remove unnecessary suppression operator</source> <target state="translated">Supprimer l'opérateur de suppression inutile</target> <note /> </trans-unit> <trans-unit id="Remove_unnessary_discard"> <source>Remove unnecessary discard</source> <target state="translated">Supprimer tout discard inutile</target> <note /> </trans-unit> <trans-unit id="Simplify_default_expression"> <source>Simplify 'default' expression</source> <target state="translated">Simplifier l'expression 'default'</target> <note /> </trans-unit> <trans-unit id="Struct_contains_assignment_to_this_outside_of_constructor_Make_readonly_fields_writable"> <source>Struct contains assignment to 'this' outside of constructor. Make readonly fields writable.</source> <target state="translated">Struct contient une assignation à 'this' en dehors du constructeur. Rend les champs readonly accessibles en écriture.</target> <note>{Locked="Struct"}{Locked="this"} these are C#/VB keywords and should not be localized.</note> </trans-unit> <trans-unit id="Suppression_operator_has_no_effect_and_can_be_misinterpreted"> <source>Suppression operator has no effect and can be misinterpreted</source> <target state="translated">L'opérateur de suppression n'a aucun effet et peut être mal interprété</target> <note /> </trans-unit> <trans-unit id="Unreachable_code_detected"> <source>Unreachable code detected</source> <target state="translated">Code inaccessible détecté</target> <note /> </trans-unit> <trans-unit id="Use_block_body_for_accessors"> <source>Use block body for accessors</source> <target state="translated">Utiliser un corps de bloc pour les accesseurs</target> <note /> </trans-unit> <trans-unit id="Use_block_body_for_constructors"> <source>Use block body for constructors</source> <target state="translated">Utiliser un corps de bloc pour les constructeurs</target> <note /> </trans-unit> <trans-unit id="Use_block_body_for_indexers"> <source>Use block body for indexers</source> <target state="translated">Utiliser un corps de bloc pour les indexeurs</target> <note /> </trans-unit> <trans-unit id="Use_block_body_for_local_functions"> <source>Use block body for local functions</source> <target state="translated">Utiliser le corps de bloc pour les fonctions locales</target> <note /> </trans-unit> <trans-unit id="Use_block_body_for_methods"> <source>Use block body for methods</source> <target state="translated">Utiliser un corps de bloc pour les méthodes</target> <note /> </trans-unit> <trans-unit id="Use_block_body_for_operators"> <source>Use block body for operators</source> <target state="translated">Utiliser un corps de bloc pour les opérateurs</target> <note /> </trans-unit> <trans-unit id="Use_block_body_for_properties"> <source>Use block body for properties</source> <target state="translated">Utiliser un corps de bloc pour les propriétés</target> <note /> </trans-unit> <trans-unit id="Use_explicit_type"> <source>Use explicit type</source> <target state="translated">Utiliser un type explicite</target> <note /> </trans-unit> <trans-unit id="Use_explicit_type_instead_of_var"> <source>Use explicit type instead of 'var'</source> <target state="translated">Utiliser un type explicite au lieu de 'var'</target> <note /> </trans-unit> <trans-unit id="Use_expression_body_for_accessors"> <source>Use expression body for accessors</source> <target state="translated">Utiliser un corps d'expression pour les accesseurs</target> <note /> </trans-unit> <trans-unit id="Use_expression_body_for_constructors"> <source>Use expression body for constructors</source> <target state="translated">Utiliser un corps d'expression pour les constructeurs</target> <note /> </trans-unit> <trans-unit id="Use_expression_body_for_indexers"> <source>Use expression body for indexers</source> <target state="translated">Utiliser un corps d'expression pour les indexeurs</target> <note /> </trans-unit> <trans-unit id="Use_expression_body_for_local_functions"> <source>Use expression body for local functions</source> <target state="translated">Utiliser le corps d'expression pour des fonctions locales</target> <note /> </trans-unit> <trans-unit id="Use_expression_body_for_methods"> <source>Use expression body for methods</source> <target state="translated">Utiliser un corps d'expression pour les méthodes</target> <note /> </trans-unit> <trans-unit id="Use_expression_body_for_operators"> <source>Use expression body for operators</source> <target state="translated">Utiliser un corps d'expression pour les opérateurs</target> <note /> </trans-unit> <trans-unit id="Use_expression_body_for_properties"> <source>Use expression body for properties</source> <target state="translated">Utiliser un corps d'expression pour les propriétés</target> <note /> </trans-unit> <trans-unit id="Use_implicit_type"> <source>Use implicit type</source> <target state="translated">Utiliser un type implicite</target> <note /> </trans-unit> <trans-unit id="Use_index_operator"> <source>Use index operator</source> <target state="translated">Utiliser l'opérateur d'index</target> <note /> </trans-unit> <trans-unit id="Use_is_null_check"> <source>Use 'is null' check</source> <target state="translated">Utiliser la vérification 'is null'</target> <note /> </trans-unit> <trans-unit id="Use_local_function"> <source>Use local function</source> <target state="translated">Utiliser une fonction locale</target> <note /> </trans-unit> <trans-unit id="Use_new"> <source>Use 'new(...)'</source> <target state="translated">Utiliser 'new(...)'</target> <note>{Locked="new(...)"} This is a C# construct and should not be localized.</note> </trans-unit> <trans-unit id="Use_pattern_matching"> <source>Use pattern matching</source> <target state="translated">Utiliser les critères spéciaux</target> <note /> </trans-unit> <trans-unit id="Use_pattern_matching_may_change_code_meaning"> <source>Use pattern matching (may change code meaning)</source> <target state="new">Use pattern matching (may change code meaning)</target> <note /> </trans-unit> <trans-unit id="Use_range_operator"> <source>Use range operator</source> <target state="translated">Utiliser l'opérateur de plage</target> <note /> </trans-unit> <trans-unit id="Use_simple_using_statement"> <source>Use simple 'using' statement</source> <target state="translated">Utiliser une instruction 'using' simple</target> <note /> </trans-unit> <trans-unit id="Use_switch_expression"> <source>Use 'switch' expression</source> <target state="translated">Utiliser l'expression 'switch'</target> <note /> </trans-unit> <trans-unit id="Using_directives_must_be_placed_inside_of_a_namespace_declaration"> <source>Using directives must be placed inside of a namespace declaration</source> <target state="translated">Les directives using doivent être placées dans une déclaration namespace</target> <note>{Locked="using"} "using" is a C# keyword and should not be localized. {Locked="namespace"} "namespace" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="Using_directives_must_be_placed_outside_of_a_namespace_declaration"> <source>Using directives must be placed outside of a namespace declaration</source> <target state="translated">Les directives using doivent être placées en dehors d'une déclaration namespace</target> <note>{Locked="using"} "using" is a C# keyword and should not be localized. {Locked="namespace"} "namespace" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="Variable_declaration_can_be_deconstructed"> <source>Variable declaration can be deconstructed</source> <target state="translated">La déclaration de variable peut être déconstruite</target> <note /> </trans-unit> <trans-unit id="Variable_declaration_can_be_inlined"> <source>Variable declaration can be inlined</source> <target state="translated">La déclaration de variable peut être inlined</target> <note /> </trans-unit> <trans-unit id="Warning_colon_Moving_using_directives_may_change_code_meaning"> <source>Warning: Moving using directives may change code meaning.</source> <target state="translated">Avertissement : Le déplacement des directives using peut changer la signification du code.</target> <note>{Locked="using"} "using" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="_0_can_be_simplified"> <source>{0} can be simplified</source> <target state="translated">{0} peut être simplifié</target> <note /> </trans-unit> <trans-unit id="default_expression_can_be_simplified"> <source>'default' expression can be simplified</source> <target state="translated">'l'expression 'default' peut être simplifiée</target> <note /> </trans-unit> <trans-unit id="if_statement_can_be_simplified"> <source>'if' statement can be simplified</source> <target state="translated">L'instruction 'if' peut être simplifiée</target> <note /> </trans-unit> <trans-unit id="new_expression_can_be_simplified"> <source>'new' expression can be simplified</source> <target state="translated">L'expression 'new' peut être simplifiée</target> <note /> </trans-unit> <trans-unit id="typeof_can_be_converted_ to_nameof"> <source>'typeof' can be converted to 'nameof'</source> <target state="translated">'typeof' peut être converti en 'nameof'</target> <note /> </trans-unit> <trans-unit id="use_var_instead_of_explicit_type"> <source>use 'var' instead of explicit type</source> <target state="translated">utiliser 'var' au lieu d'un type explicite</target> <note /> </trans-unit> <trans-unit id="Using_directive_is_unnecessary"> <source>Using directive is unnecessary.</source> <target state="translated">La directive using n'est pas nécessaire.</target> <note /> </trans-unit> <trans-unit id="using_statement_can_be_simplified"> <source>'using' statement can be simplified</source> <target state="translated">L'instruction 'using' peut être simplifiée</target> <note /> </trans-unit> </body> </file> </xliff>
1
dotnet/roslyn
55,427
Fixes #50462
Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
Blokyk
2021-08-05T01:17:37Z
2021-08-25T05:42:59Z
fefb8c2110625bc4908db4bbdaa367b12bfb1069
fb4ac545a1f1f365e7df570637699d9085ea4f87
Fixes #50462. Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
./src/Analyzers/CSharp/Analyzers/xlf/CSharpAnalyzersResources.it.xlf
<?xml version="1.0" encoding="utf-8"?> <xliff xmlns="urn:oasis:names:tc:xliff:document:1.2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="1.2" xsi:schemaLocation="urn:oasis:names:tc:xliff:document:1.2 xliff-core-1.2-transitional.xsd"> <file datatype="xml" source-language="en" target-language="it" original="../CSharpAnalyzersResources.resx"> <body> <trans-unit id="Add_braces"> <source>Add braces</source> <target state="translated">Aggiungi parentesi graffe</target> <note /> </trans-unit> <trans-unit id="Add_braces_to_0_statement"> <source>Add braces to '{0}' statement.</source> <target state="translated">Aggiunge le parentesi graffe all'istruzione '{0}'.</target> <note /> </trans-unit> <trans-unit id="Blank_line_not_allowed_after_constructor_initializer_colon"> <source>Blank line not allowed after constructor initializer colon</source> <target state="translated">Non sono consentite righe vuote dopo i due punti dell'inizializzatore del costruttore</target> <note /> </trans-unit> <trans-unit id="Consecutive_braces_must_not_have_a_blank_between_them"> <source>Consecutive braces must not have blank line between them</source> <target state="translated">Tra parentesi graffe consecutive non devono essere presenti righe vuote</target> <note /> </trans-unit> <trans-unit id="Convert_switch_statement_to_expression"> <source>Convert switch statement to expression</source> <target state="translated">Converti l'istruzione switch in espressione</target> <note /> </trans-unit> <trans-unit id="Convert_to_block_scoped_namespace"> <source>Convert to block scoped namespace</source> <target state="new">Convert to block scoped namespace</target> <note>{Locked="namespace"} "namespace" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="Convert_to_file_scoped_namespace"> <source>Convert to file-scoped namespace</source> <target state="new">Convert to file-scoped namespace</target> <note>{Locked="namespace"} "namespace" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="Deconstruct_variable_declaration"> <source>Deconstruct variable declaration</source> <target state="translated">Decostruisci la dichiarazione di variabile</target> <note /> </trans-unit> <trans-unit id="Delegate_invocation_can_be_simplified"> <source>Delegate invocation can be simplified.</source> <target state="translated">La chiamata del delegato può essere semplificata.</target> <note /> </trans-unit> <trans-unit id="Discard_can_be_removed"> <source>Discard can be removed</source> <target state="translated">È possibile rimuovere discard</target> <note /> </trans-unit> <trans-unit id="Embedded_statements_must_be_on_their_own_line"> <source>Embedded statements must be on their own line</source> <target state="translated">Le istruzioni incorporate devono essere posizionate nella rispettiva riga</target> <note /> </trans-unit> <trans-unit id="Indexing_can_be_simplified"> <source>Indexing can be simplified</source> <target state="translated">L'indicizzazione può essere semplificata</target> <note /> </trans-unit> <trans-unit id="Inline_variable_declaration"> <source>Inline variable declaration</source> <target state="translated">Dichiarazione di variabile inline</target> <note /> </trans-unit> <trans-unit id="Misplaced_using_directive"> <source>Misplaced using directive</source> <target state="translated">Direttiva using in posizione errata</target> <note>{Locked="using"} "using" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="Move_misplaced_using_directives"> <source>Move misplaced using directives</source> <target state="translated">Sposta le direttive using in posizione errata</target> <note>{Locked="using"} "using" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="Make_readonly_fields_writable"> <source>Make readonly fields writable</source> <target state="translated">Rendi scrivibili i campi readonly</target> <note>{Locked="readonly"} "readonly" is C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="Local_function_can_be_made_static"> <source>Local function can be made static</source> <target state="translated">La funzione locale può essere resa statica</target> <note /> </trans-unit> <trans-unit id="Make_local_function_static"> <source>Make local function 'static'</source> <target state="translated">Rendi la funzione locale 'static'</target> <note /> </trans-unit> <trans-unit id="Negate_expression_changes_semantics"> <source>Negate expression (changes semantics)</source> <target state="translated">Nega l'espressione (modifica la semantica)</target> <note /> </trans-unit> <trans-unit id="Null_check_can_be_clarified"> <source>Null check can be clarified</source> <target state="new">Null check can be clarified</target> <note /> </trans-unit> <trans-unit id="Prefer_null_check_over_type_check"> <source>Prefer 'null' check over type check</source> <target state="new">Prefer 'null' check over type check</target> <note /> </trans-unit> <trans-unit id="Remove_operator_preserves_semantics"> <source>Remove operator (preserves semantics)</source> <target state="translated">Rimuovi l'operatore (conserva la semantica)</target> <note /> </trans-unit> <trans-unit id="Remove_suppression_operators"> <source>Remove suppression operators</source> <target state="translated">Rimuovi gli operatori di eliminazione</target> <note /> </trans-unit> <trans-unit id="Remove_unnecessary_suppression_operator"> <source>Remove unnecessary suppression operator</source> <target state="translated">Rimuovi l'operatore di eliminazione non necessario</target> <note /> </trans-unit> <trans-unit id="Remove_unnessary_discard"> <source>Remove unnecessary discard</source> <target state="translated">Rimuovi discard non necessario</target> <note /> </trans-unit> <trans-unit id="Simplify_default_expression"> <source>Simplify 'default' expression</source> <target state="translated">Semplifica l'espressione 'default'</target> <note /> </trans-unit> <trans-unit id="Struct_contains_assignment_to_this_outside_of_constructor_Make_readonly_fields_writable"> <source>Struct contains assignment to 'this' outside of constructor. Make readonly fields writable.</source> <target state="translated">La parola chiave Struct contiene l'assegnazione a 'this' all'esterno del costruttore. Impostare i campi di sola lettura come scrivibili.</target> <note>{Locked="Struct"}{Locked="this"} these are C#/VB keywords and should not be localized.</note> </trans-unit> <trans-unit id="Suppression_operator_has_no_effect_and_can_be_misinterpreted"> <source>Suppression operator has no effect and can be misinterpreted</source> <target state="translated">L'operatore di eliminazione non ha alcun effetto e può essere frainteso</target> <note /> </trans-unit> <trans-unit id="Unreachable_code_detected"> <source>Unreachable code detected</source> <target state="translated">È stato rilevato codice non raggiungibile</target> <note /> </trans-unit> <trans-unit id="Use_block_body_for_accessors"> <source>Use block body for accessors</source> <target state="translated">Usa il corpo del blocco per le funzioni di accesso</target> <note /> </trans-unit> <trans-unit id="Use_block_body_for_constructors"> <source>Use block body for constructors</source> <target state="translated">Usa il corpo del blocco per i costruttori</target> <note /> </trans-unit> <trans-unit id="Use_block_body_for_indexers"> <source>Use block body for indexers</source> <target state="translated">Usa il corpo del blocco per gli indicizzatori</target> <note /> </trans-unit> <trans-unit id="Use_block_body_for_local_functions"> <source>Use block body for local functions</source> <target state="translated">Usa il corpo del blocco per le funzioni locali</target> <note /> </trans-unit> <trans-unit id="Use_block_body_for_methods"> <source>Use block body for methods</source> <target state="translated">Usa il corpo del blocco per i metodi</target> <note /> </trans-unit> <trans-unit id="Use_block_body_for_operators"> <source>Use block body for operators</source> <target state="translated">Usa il corpo del blocco per gli operatori</target> <note /> </trans-unit> <trans-unit id="Use_block_body_for_properties"> <source>Use block body for properties</source> <target state="translated">Usa il corpo del blocco per le proprietà</target> <note /> </trans-unit> <trans-unit id="Use_explicit_type"> <source>Use explicit type</source> <target state="translated">Usa il tipo esplicito</target> <note /> </trans-unit> <trans-unit id="Use_explicit_type_instead_of_var"> <source>Use explicit type instead of 'var'</source> <target state="translated">Usa il tipo esplicito invece di 'var'</target> <note /> </trans-unit> <trans-unit id="Use_expression_body_for_accessors"> <source>Use expression body for accessors</source> <target state="translated">Usa il corpo dell'espressione per le funzioni di accesso</target> <note /> </trans-unit> <trans-unit id="Use_expression_body_for_constructors"> <source>Use expression body for constructors</source> <target state="translated">Usa il corpo dell'espressione per i costruttori</target> <note /> </trans-unit> <trans-unit id="Use_expression_body_for_indexers"> <source>Use expression body for indexers</source> <target state="translated">Usa il corpo dell'espressione per gli indicizzatori</target> <note /> </trans-unit> <trans-unit id="Use_expression_body_for_local_functions"> <source>Use expression body for local functions</source> <target state="translated">Usa corpo dell'espressione per funzioni locali</target> <note /> </trans-unit> <trans-unit id="Use_expression_body_for_methods"> <source>Use expression body for methods</source> <target state="translated">Usa il corpo dell'espressione per i metodi</target> <note /> </trans-unit> <trans-unit id="Use_expression_body_for_operators"> <source>Use expression body for operators</source> <target state="translated">Usa il corpo dell'espressione per gli operatori</target> <note /> </trans-unit> <trans-unit id="Use_expression_body_for_properties"> <source>Use expression body for properties</source> <target state="translated">Usa il corpo dell'espressione per le proprietà</target> <note /> </trans-unit> <trans-unit id="Use_implicit_type"> <source>Use implicit type</source> <target state="translated">Usa il tipo implicito</target> <note /> </trans-unit> <trans-unit id="Use_index_operator"> <source>Use index operator</source> <target state="translated">Usa operatore di indice</target> <note /> </trans-unit> <trans-unit id="Use_is_null_check"> <source>Use 'is null' check</source> <target state="translated">Usa controllo 'is null'</target> <note /> </trans-unit> <trans-unit id="Use_local_function"> <source>Use local function</source> <target state="translated">Usa la funzione locale</target> <note /> </trans-unit> <trans-unit id="Use_new"> <source>Use 'new(...)'</source> <target state="translated">Usa 'new(...)'</target> <note>{Locked="new(...)"} This is a C# construct and should not be localized.</note> </trans-unit> <trans-unit id="Use_pattern_matching"> <source>Use pattern matching</source> <target state="translated">Usa i criteri di ricerca</target> <note /> </trans-unit> <trans-unit id="Use_range_operator"> <source>Use range operator</source> <target state="translated">Usa l'operatore di intervallo</target> <note /> </trans-unit> <trans-unit id="Use_simple_using_statement"> <source>Use simple 'using' statement</source> <target state="translated">Usa l'istruzione 'using' semplice</target> <note /> </trans-unit> <trans-unit id="Use_switch_expression"> <source>Use 'switch' expression</source> <target state="translated">Usa l'espressione 'switch'</target> <note /> </trans-unit> <trans-unit id="Using_directives_must_be_placed_inside_of_a_namespace_declaration"> <source>Using directives must be placed inside of a namespace declaration</source> <target state="translated">Le direttive using devono essere inserite all'interno di una dichiarazione di namespace</target> <note>{Locked="using"} "using" is a C# keyword and should not be localized. {Locked="namespace"} "namespace" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="Using_directives_must_be_placed_outside_of_a_namespace_declaration"> <source>Using directives must be placed outside of a namespace declaration</source> <target state="translated">Le direttive using devono essere inserite all'esterno di una dichiarazione di namespace</target> <note>{Locked="using"} "using" is a C# keyword and should not be localized. {Locked="namespace"} "namespace" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="Variable_declaration_can_be_deconstructed"> <source>Variable declaration can be deconstructed</source> <target state="translated">La dichiarazione di variabile può essere decostruita</target> <note /> </trans-unit> <trans-unit id="Variable_declaration_can_be_inlined"> <source>Variable declaration can be inlined</source> <target state="translated">La dichiarazione di variabile può essere impostata come inline</target> <note /> </trans-unit> <trans-unit id="Warning_colon_Moving_using_directives_may_change_code_meaning"> <source>Warning: Moving using directives may change code meaning.</source> <target state="translated">Avviso: in seguito allo spostamento di direttive using, il significato del codice può cambiare.</target> <note>{Locked="using"} "using" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="_0_can_be_simplified"> <source>{0} can be simplified</source> <target state="translated">{0} può essere semplificato</target> <note /> </trans-unit> <trans-unit id="default_expression_can_be_simplified"> <source>'default' expression can be simplified</source> <target state="translated">'L'espressione 'default' può essere semplificata</target> <note /> </trans-unit> <trans-unit id="if_statement_can_be_simplified"> <source>'if' statement can be simplified</source> <target state="translated">L'istruzione 'If' può essere semplificata</target> <note /> </trans-unit> <trans-unit id="new_expression_can_be_simplified"> <source>'new' expression can be simplified</source> <target state="translated">L'espressione 'new' può essere semplificata</target> <note /> </trans-unit> <trans-unit id="typeof_can_be_converted_ to_nameof"> <source>'typeof' can be converted to 'nameof'</source> <target state="translated">'typeof' può essere convertito in 'nameof'</target> <note /> </trans-unit> <trans-unit id="use_var_instead_of_explicit_type"> <source>use 'var' instead of explicit type</source> <target state="translated">usa 'var' invece del tipo esplicito</target> <note /> </trans-unit> <trans-unit id="Using_directive_is_unnecessary"> <source>Using directive is unnecessary.</source> <target state="translated">La direttiva using non è necessaria.</target> <note /> </trans-unit> <trans-unit id="using_statement_can_be_simplified"> <source>'using' statement can be simplified</source> <target state="translated">L'istruzione 'using' può essere semplificata</target> <note /> </trans-unit> </body> </file> </xliff>
<?xml version="1.0" encoding="utf-8"?> <xliff xmlns="urn:oasis:names:tc:xliff:document:1.2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="1.2" xsi:schemaLocation="urn:oasis:names:tc:xliff:document:1.2 xliff-core-1.2-transitional.xsd"> <file datatype="xml" source-language="en" target-language="it" original="../CSharpAnalyzersResources.resx"> <body> <trans-unit id="Add_braces"> <source>Add braces</source> <target state="translated">Aggiungi parentesi graffe</target> <note /> </trans-unit> <trans-unit id="Add_braces_to_0_statement"> <source>Add braces to '{0}' statement.</source> <target state="translated">Aggiunge le parentesi graffe all'istruzione '{0}'.</target> <note /> </trans-unit> <trans-unit id="Blank_line_not_allowed_after_constructor_initializer_colon"> <source>Blank line not allowed after constructor initializer colon</source> <target state="translated">Non sono consentite righe vuote dopo i due punti dell'inizializzatore del costruttore</target> <note /> </trans-unit> <trans-unit id="Consecutive_braces_must_not_have_a_blank_between_them"> <source>Consecutive braces must not have blank line between them</source> <target state="translated">Tra parentesi graffe consecutive non devono essere presenti righe vuote</target> <note /> </trans-unit> <trans-unit id="Convert_switch_statement_to_expression"> <source>Convert switch statement to expression</source> <target state="translated">Converti l'istruzione switch in espressione</target> <note /> </trans-unit> <trans-unit id="Convert_to_block_scoped_namespace"> <source>Convert to block scoped namespace</source> <target state="new">Convert to block scoped namespace</target> <note>{Locked="namespace"} "namespace" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="Convert_to_file_scoped_namespace"> <source>Convert to file-scoped namespace</source> <target state="new">Convert to file-scoped namespace</target> <note>{Locked="namespace"} "namespace" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="Deconstruct_variable_declaration"> <source>Deconstruct variable declaration</source> <target state="translated">Decostruisci la dichiarazione di variabile</target> <note /> </trans-unit> <trans-unit id="Delegate_invocation_can_be_simplified"> <source>Delegate invocation can be simplified.</source> <target state="translated">La chiamata del delegato può essere semplificata.</target> <note /> </trans-unit> <trans-unit id="Discard_can_be_removed"> <source>Discard can be removed</source> <target state="translated">È possibile rimuovere discard</target> <note /> </trans-unit> <trans-unit id="Embedded_statements_must_be_on_their_own_line"> <source>Embedded statements must be on their own line</source> <target state="translated">Le istruzioni incorporate devono essere posizionate nella rispettiva riga</target> <note /> </trans-unit> <trans-unit id="Indexing_can_be_simplified"> <source>Indexing can be simplified</source> <target state="translated">L'indicizzazione può essere semplificata</target> <note /> </trans-unit> <trans-unit id="Inline_variable_declaration"> <source>Inline variable declaration</source> <target state="translated">Dichiarazione di variabile inline</target> <note /> </trans-unit> <trans-unit id="Misplaced_using_directive"> <source>Misplaced using directive</source> <target state="translated">Direttiva using in posizione errata</target> <note>{Locked="using"} "using" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="Move_misplaced_using_directives"> <source>Move misplaced using directives</source> <target state="translated">Sposta le direttive using in posizione errata</target> <note>{Locked="using"} "using" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="Make_readonly_fields_writable"> <source>Make readonly fields writable</source> <target state="translated">Rendi scrivibili i campi readonly</target> <note>{Locked="readonly"} "readonly" is C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="Local_function_can_be_made_static"> <source>Local function can be made static</source> <target state="translated">La funzione locale può essere resa statica</target> <note /> </trans-unit> <trans-unit id="Make_local_function_static"> <source>Make local function 'static'</source> <target state="translated">Rendi la funzione locale 'static'</target> <note /> </trans-unit> <trans-unit id="Negate_expression_changes_semantics"> <source>Negate expression (changes semantics)</source> <target state="translated">Nega l'espressione (modifica la semantica)</target> <note /> </trans-unit> <trans-unit id="Null_check_can_be_clarified"> <source>Null check can be clarified</source> <target state="new">Null check can be clarified</target> <note /> </trans-unit> <trans-unit id="Prefer_null_check_over_type_check"> <source>Prefer 'null' check over type check</source> <target state="new">Prefer 'null' check over type check</target> <note /> </trans-unit> <trans-unit id="Remove_operator_preserves_semantics"> <source>Remove operator (preserves semantics)</source> <target state="translated">Rimuovi l'operatore (conserva la semantica)</target> <note /> </trans-unit> <trans-unit id="Remove_suppression_operators"> <source>Remove suppression operators</source> <target state="translated">Rimuovi gli operatori di eliminazione</target> <note /> </trans-unit> <trans-unit id="Remove_unnecessary_suppression_operator"> <source>Remove unnecessary suppression operator</source> <target state="translated">Rimuovi l'operatore di eliminazione non necessario</target> <note /> </trans-unit> <trans-unit id="Remove_unnessary_discard"> <source>Remove unnecessary discard</source> <target state="translated">Rimuovi discard non necessario</target> <note /> </trans-unit> <trans-unit id="Simplify_default_expression"> <source>Simplify 'default' expression</source> <target state="translated">Semplifica l'espressione 'default'</target> <note /> </trans-unit> <trans-unit id="Struct_contains_assignment_to_this_outside_of_constructor_Make_readonly_fields_writable"> <source>Struct contains assignment to 'this' outside of constructor. Make readonly fields writable.</source> <target state="translated">La parola chiave Struct contiene l'assegnazione a 'this' all'esterno del costruttore. Impostare i campi di sola lettura come scrivibili.</target> <note>{Locked="Struct"}{Locked="this"} these are C#/VB keywords and should not be localized.</note> </trans-unit> <trans-unit id="Suppression_operator_has_no_effect_and_can_be_misinterpreted"> <source>Suppression operator has no effect and can be misinterpreted</source> <target state="translated">L'operatore di eliminazione non ha alcun effetto e può essere frainteso</target> <note /> </trans-unit> <trans-unit id="Unreachable_code_detected"> <source>Unreachable code detected</source> <target state="translated">È stato rilevato codice non raggiungibile</target> <note /> </trans-unit> <trans-unit id="Use_block_body_for_accessors"> <source>Use block body for accessors</source> <target state="translated">Usa il corpo del blocco per le funzioni di accesso</target> <note /> </trans-unit> <trans-unit id="Use_block_body_for_constructors"> <source>Use block body for constructors</source> <target state="translated">Usa il corpo del blocco per i costruttori</target> <note /> </trans-unit> <trans-unit id="Use_block_body_for_indexers"> <source>Use block body for indexers</source> <target state="translated">Usa il corpo del blocco per gli indicizzatori</target> <note /> </trans-unit> <trans-unit id="Use_block_body_for_local_functions"> <source>Use block body for local functions</source> <target state="translated">Usa il corpo del blocco per le funzioni locali</target> <note /> </trans-unit> <trans-unit id="Use_block_body_for_methods"> <source>Use block body for methods</source> <target state="translated">Usa il corpo del blocco per i metodi</target> <note /> </trans-unit> <trans-unit id="Use_block_body_for_operators"> <source>Use block body for operators</source> <target state="translated">Usa il corpo del blocco per gli operatori</target> <note /> </trans-unit> <trans-unit id="Use_block_body_for_properties"> <source>Use block body for properties</source> <target state="translated">Usa il corpo del blocco per le proprietà</target> <note /> </trans-unit> <trans-unit id="Use_explicit_type"> <source>Use explicit type</source> <target state="translated">Usa il tipo esplicito</target> <note /> </trans-unit> <trans-unit id="Use_explicit_type_instead_of_var"> <source>Use explicit type instead of 'var'</source> <target state="translated">Usa il tipo esplicito invece di 'var'</target> <note /> </trans-unit> <trans-unit id="Use_expression_body_for_accessors"> <source>Use expression body for accessors</source> <target state="translated">Usa il corpo dell'espressione per le funzioni di accesso</target> <note /> </trans-unit> <trans-unit id="Use_expression_body_for_constructors"> <source>Use expression body for constructors</source> <target state="translated">Usa il corpo dell'espressione per i costruttori</target> <note /> </trans-unit> <trans-unit id="Use_expression_body_for_indexers"> <source>Use expression body for indexers</source> <target state="translated">Usa il corpo dell'espressione per gli indicizzatori</target> <note /> </trans-unit> <trans-unit id="Use_expression_body_for_local_functions"> <source>Use expression body for local functions</source> <target state="translated">Usa corpo dell'espressione per funzioni locali</target> <note /> </trans-unit> <trans-unit id="Use_expression_body_for_methods"> <source>Use expression body for methods</source> <target state="translated">Usa il corpo dell'espressione per i metodi</target> <note /> </trans-unit> <trans-unit id="Use_expression_body_for_operators"> <source>Use expression body for operators</source> <target state="translated">Usa il corpo dell'espressione per gli operatori</target> <note /> </trans-unit> <trans-unit id="Use_expression_body_for_properties"> <source>Use expression body for properties</source> <target state="translated">Usa il corpo dell'espressione per le proprietà</target> <note /> </trans-unit> <trans-unit id="Use_implicit_type"> <source>Use implicit type</source> <target state="translated">Usa il tipo implicito</target> <note /> </trans-unit> <trans-unit id="Use_index_operator"> <source>Use index operator</source> <target state="translated">Usa operatore di indice</target> <note /> </trans-unit> <trans-unit id="Use_is_null_check"> <source>Use 'is null' check</source> <target state="translated">Usa controllo 'is null'</target> <note /> </trans-unit> <trans-unit id="Use_local_function"> <source>Use local function</source> <target state="translated">Usa la funzione locale</target> <note /> </trans-unit> <trans-unit id="Use_new"> <source>Use 'new(...)'</source> <target state="translated">Usa 'new(...)'</target> <note>{Locked="new(...)"} This is a C# construct and should not be localized.</note> </trans-unit> <trans-unit id="Use_pattern_matching"> <source>Use pattern matching</source> <target state="translated">Usa i criteri di ricerca</target> <note /> </trans-unit> <trans-unit id="Use_pattern_matching_may_change_code_meaning"> <source>Use pattern matching (may change code meaning)</source> <target state="new">Use pattern matching (may change code meaning)</target> <note /> </trans-unit> <trans-unit id="Use_range_operator"> <source>Use range operator</source> <target state="translated">Usa l'operatore di intervallo</target> <note /> </trans-unit> <trans-unit id="Use_simple_using_statement"> <source>Use simple 'using' statement</source> <target state="translated">Usa l'istruzione 'using' semplice</target> <note /> </trans-unit> <trans-unit id="Use_switch_expression"> <source>Use 'switch' expression</source> <target state="translated">Usa l'espressione 'switch'</target> <note /> </trans-unit> <trans-unit id="Using_directives_must_be_placed_inside_of_a_namespace_declaration"> <source>Using directives must be placed inside of a namespace declaration</source> <target state="translated">Le direttive using devono essere inserite all'interno di una dichiarazione di namespace</target> <note>{Locked="using"} "using" is a C# keyword and should not be localized. {Locked="namespace"} "namespace" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="Using_directives_must_be_placed_outside_of_a_namespace_declaration"> <source>Using directives must be placed outside of a namespace declaration</source> <target state="translated">Le direttive using devono essere inserite all'esterno di una dichiarazione di namespace</target> <note>{Locked="using"} "using" is a C# keyword and should not be localized. {Locked="namespace"} "namespace" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="Variable_declaration_can_be_deconstructed"> <source>Variable declaration can be deconstructed</source> <target state="translated">La dichiarazione di variabile può essere decostruita</target> <note /> </trans-unit> <trans-unit id="Variable_declaration_can_be_inlined"> <source>Variable declaration can be inlined</source> <target state="translated">La dichiarazione di variabile può essere impostata come inline</target> <note /> </trans-unit> <trans-unit id="Warning_colon_Moving_using_directives_may_change_code_meaning"> <source>Warning: Moving using directives may change code meaning.</source> <target state="translated">Avviso: in seguito allo spostamento di direttive using, il significato del codice può cambiare.</target> <note>{Locked="using"} "using" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="_0_can_be_simplified"> <source>{0} can be simplified</source> <target state="translated">{0} può essere semplificato</target> <note /> </trans-unit> <trans-unit id="default_expression_can_be_simplified"> <source>'default' expression can be simplified</source> <target state="translated">'L'espressione 'default' può essere semplificata</target> <note /> </trans-unit> <trans-unit id="if_statement_can_be_simplified"> <source>'if' statement can be simplified</source> <target state="translated">L'istruzione 'If' può essere semplificata</target> <note /> </trans-unit> <trans-unit id="new_expression_can_be_simplified"> <source>'new' expression can be simplified</source> <target state="translated">L'espressione 'new' può essere semplificata</target> <note /> </trans-unit> <trans-unit id="typeof_can_be_converted_ to_nameof"> <source>'typeof' can be converted to 'nameof'</source> <target state="translated">'typeof' può essere convertito in 'nameof'</target> <note /> </trans-unit> <trans-unit id="use_var_instead_of_explicit_type"> <source>use 'var' instead of explicit type</source> <target state="translated">usa 'var' invece del tipo esplicito</target> <note /> </trans-unit> <trans-unit id="Using_directive_is_unnecessary"> <source>Using directive is unnecessary.</source> <target state="translated">La direttiva using non è necessaria.</target> <note /> </trans-unit> <trans-unit id="using_statement_can_be_simplified"> <source>'using' statement can be simplified</source> <target state="translated">L'istruzione 'using' può essere semplificata</target> <note /> </trans-unit> </body> </file> </xliff>
1
dotnet/roslyn
55,427
Fixes #50462
Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
Blokyk
2021-08-05T01:17:37Z
2021-08-25T05:42:59Z
fefb8c2110625bc4908db4bbdaa367b12bfb1069
fb4ac545a1f1f365e7df570637699d9085ea4f87
Fixes #50462. Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
./src/Analyzers/CSharp/Analyzers/xlf/CSharpAnalyzersResources.ja.xlf
<?xml version="1.0" encoding="utf-8"?> <xliff xmlns="urn:oasis:names:tc:xliff:document:1.2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="1.2" xsi:schemaLocation="urn:oasis:names:tc:xliff:document:1.2 xliff-core-1.2-transitional.xsd"> <file datatype="xml" source-language="en" target-language="ja" original="../CSharpAnalyzersResources.resx"> <body> <trans-unit id="Add_braces"> <source>Add braces</source> <target state="translated">波かっこを追加します</target> <note /> </trans-unit> <trans-unit id="Add_braces_to_0_statement"> <source>Add braces to '{0}' statement.</source> <target state="translated">'{0}' ステートメントに波かっこを追加します。</target> <note /> </trans-unit> <trans-unit id="Blank_line_not_allowed_after_constructor_initializer_colon"> <source>Blank line not allowed after constructor initializer colon</source> <target state="translated">コンストラクター初期化子のコロンの後に空白行を使用することはできません</target> <note /> </trans-unit> <trans-unit id="Consecutive_braces_must_not_have_a_blank_between_them"> <source>Consecutive braces must not have blank line between them</source> <target state="translated">連続する中かっこの間に空白行を含めることはできません</target> <note /> </trans-unit> <trans-unit id="Convert_switch_statement_to_expression"> <source>Convert switch statement to expression</source> <target state="translated">switch ステートメントを式に変換します</target> <note /> </trans-unit> <trans-unit id="Convert_to_block_scoped_namespace"> <source>Convert to block scoped namespace</source> <target state="new">Convert to block scoped namespace</target> <note>{Locked="namespace"} "namespace" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="Convert_to_file_scoped_namespace"> <source>Convert to file-scoped namespace</source> <target state="new">Convert to file-scoped namespace</target> <note>{Locked="namespace"} "namespace" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="Deconstruct_variable_declaration"> <source>Deconstruct variable declaration</source> <target state="translated">変数の宣言を分解</target> <note /> </trans-unit> <trans-unit id="Delegate_invocation_can_be_simplified"> <source>Delegate invocation can be simplified.</source> <target state="translated">デリゲート呼び出しを簡素化できます。</target> <note /> </trans-unit> <trans-unit id="Discard_can_be_removed"> <source>Discard can be removed</source> <target state="translated">ディスカードは削除できます</target> <note /> </trans-unit> <trans-unit id="Embedded_statements_must_be_on_their_own_line"> <source>Embedded statements must be on their own line</source> <target state="translated">埋め込みステートメントは独自の行に配置する必要があります</target> <note /> </trans-unit> <trans-unit id="Indexing_can_be_simplified"> <source>Indexing can be simplified</source> <target state="translated">インデックスの作成を簡素化することができます</target> <note /> </trans-unit> <trans-unit id="Inline_variable_declaration"> <source>Inline variable declaration</source> <target state="translated">インライン変数宣言</target> <note /> </trans-unit> <trans-unit id="Misplaced_using_directive"> <source>Misplaced using directive</source> <target state="translated">using ディレクティブが正しく配置されていません</target> <note>{Locked="using"} "using" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="Move_misplaced_using_directives"> <source>Move misplaced using directives</source> <target state="translated">誤って配置された using ディレクティブを移動します</target> <note>{Locked="using"} "using" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="Make_readonly_fields_writable"> <source>Make readonly fields writable</source> <target state="translated">readonly フィールドを書き込み可能にします</target> <note>{Locked="readonly"} "readonly" is C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="Local_function_can_be_made_static"> <source>Local function can be made static</source> <target state="translated">ローカル関数を静的にすることができます</target> <note /> </trans-unit> <trans-unit id="Make_local_function_static"> <source>Make local function 'static'</source> <target state="translated">ローカル関数を 'static' にします</target> <note /> </trans-unit> <trans-unit id="Negate_expression_changes_semantics"> <source>Negate expression (changes semantics)</source> <target state="translated">式の無効化 (セマンティクスを変更)</target> <note /> </trans-unit> <trans-unit id="Null_check_can_be_clarified"> <source>Null check can be clarified</source> <target state="new">Null check can be clarified</target> <note /> </trans-unit> <trans-unit id="Prefer_null_check_over_type_check"> <source>Prefer 'null' check over type check</source> <target state="new">Prefer 'null' check over type check</target> <note /> </trans-unit> <trans-unit id="Remove_operator_preserves_semantics"> <source>Remove operator (preserves semantics)</source> <target state="translated">演算子の削除 (セマンティクスを保持)</target> <note /> </trans-unit> <trans-unit id="Remove_suppression_operators"> <source>Remove suppression operators</source> <target state="translated">抑制演算子の削除</target> <note /> </trans-unit> <trans-unit id="Remove_unnecessary_suppression_operator"> <source>Remove unnecessary suppression operator</source> <target state="translated">不要な抑制演算子を削除します</target> <note /> </trans-unit> <trans-unit id="Remove_unnessary_discard"> <source>Remove unnecessary discard</source> <target state="translated">不要なディスカードを削除</target> <note /> </trans-unit> <trans-unit id="Simplify_default_expression"> <source>Simplify 'default' expression</source> <target state="translated">default' 式を単純化する</target> <note /> </trans-unit> <trans-unit id="Struct_contains_assignment_to_this_outside_of_constructor_Make_readonly_fields_writable"> <source>Struct contains assignment to 'this' outside of constructor. Make readonly fields writable.</source> <target state="translated">Struct に、コンストラクター外部の 'this' に対する代入が含まれています。読み取り専用フィールドを書き込み可能にしてください。</target> <note>{Locked="Struct"}{Locked="this"} these are C#/VB keywords and should not be localized.</note> </trans-unit> <trans-unit id="Suppression_operator_has_no_effect_and_can_be_misinterpreted"> <source>Suppression operator has no effect and can be misinterpreted</source> <target state="translated">抑制演算子は効果がなく、誤って解釈される可能性があります</target> <note /> </trans-unit> <trans-unit id="Unreachable_code_detected"> <source>Unreachable code detected</source> <target state="translated">到達できないコードが検出されました</target> <note /> </trans-unit> <trans-unit id="Use_block_body_for_accessors"> <source>Use block body for accessors</source> <target state="translated">アクセサーにブロック本体を使用する</target> <note /> </trans-unit> <trans-unit id="Use_block_body_for_constructors"> <source>Use block body for constructors</source> <target state="translated">コンストラクターにブロック本体を使用する</target> <note /> </trans-unit> <trans-unit id="Use_block_body_for_indexers"> <source>Use block body for indexers</source> <target state="translated">インデクサーにブロック本体を使用する</target> <note /> </trans-unit> <trans-unit id="Use_block_body_for_local_functions"> <source>Use block body for local functions</source> <target state="translated">ローカル関数にブロック本体を使用します</target> <note /> </trans-unit> <trans-unit id="Use_block_body_for_methods"> <source>Use block body for methods</source> <target state="translated">メソッドにブロック本体を使用する</target> <note /> </trans-unit> <trans-unit id="Use_block_body_for_operators"> <source>Use block body for operators</source> <target state="translated">オペレーターにブロック本体を使用する</target> <note /> </trans-unit> <trans-unit id="Use_block_body_for_properties"> <source>Use block body for properties</source> <target state="translated">プロパティにブロック本体を使用する</target> <note /> </trans-unit> <trans-unit id="Use_explicit_type"> <source>Use explicit type</source> <target state="translated">明示的な型の使用</target> <note /> </trans-unit> <trans-unit id="Use_explicit_type_instead_of_var"> <source>Use explicit type instead of 'var'</source> <target state="translated">var' ではなく明示的な型を使用します</target> <note /> </trans-unit> <trans-unit id="Use_expression_body_for_accessors"> <source>Use expression body for accessors</source> <target state="translated">アクセサーに式本体を使用する</target> <note /> </trans-unit> <trans-unit id="Use_expression_body_for_constructors"> <source>Use expression body for constructors</source> <target state="translated">コンストラクターに式本体を使用する</target> <note /> </trans-unit> <trans-unit id="Use_expression_body_for_indexers"> <source>Use expression body for indexers</source> <target state="translated">インデクサーに式本体を使用する</target> <note /> </trans-unit> <trans-unit id="Use_expression_body_for_local_functions"> <source>Use expression body for local functions</source> <target state="translated">ローカル関数に式本体を使用します</target> <note /> </trans-unit> <trans-unit id="Use_expression_body_for_methods"> <source>Use expression body for methods</source> <target state="translated">メソッドに式本体を使用する</target> <note /> </trans-unit> <trans-unit id="Use_expression_body_for_operators"> <source>Use expression body for operators</source> <target state="translated">オペレーターに式本体を使用する</target> <note /> </trans-unit> <trans-unit id="Use_expression_body_for_properties"> <source>Use expression body for properties</source> <target state="translated">プロパティに式本体を使用する</target> <note /> </trans-unit> <trans-unit id="Use_implicit_type"> <source>Use implicit type</source> <target state="translated">暗黙的な型の使用</target> <note /> </trans-unit> <trans-unit id="Use_index_operator"> <source>Use index operator</source> <target state="translated">インデックス演算子を使用</target> <note /> </trans-unit> <trans-unit id="Use_is_null_check"> <source>Use 'is null' check</source> <target state="translated">is null' チェックを使用します</target> <note /> </trans-unit> <trans-unit id="Use_local_function"> <source>Use local function</source> <target state="translated">ローカル関数を使用します</target> <note /> </trans-unit> <trans-unit id="Use_new"> <source>Use 'new(...)'</source> <target state="translated">'new(...)' を使用する</target> <note>{Locked="new(...)"} This is a C# construct and should not be localized.</note> </trans-unit> <trans-unit id="Use_pattern_matching"> <source>Use pattern matching</source> <target state="translated">パターン マッチングを使用します</target> <note /> </trans-unit> <trans-unit id="Use_range_operator"> <source>Use range operator</source> <target state="translated">範囲演算子を使用</target> <note /> </trans-unit> <trans-unit id="Use_simple_using_statement"> <source>Use simple 'using' statement</source> <target state="translated">単純な 'using' ステートメントを使用する</target> <note /> </trans-unit> <trans-unit id="Use_switch_expression"> <source>Use 'switch' expression</source> <target state="translated">'switch' 式を使用します</target> <note /> </trans-unit> <trans-unit id="Using_directives_must_be_placed_inside_of_a_namespace_declaration"> <source>Using directives must be placed inside of a namespace declaration</source> <target state="translated">using ディレクティブを namespace 宣言の中に配置する必要があります</target> <note>{Locked="using"} "using" is a C# keyword and should not be localized. {Locked="namespace"} "namespace" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="Using_directives_must_be_placed_outside_of_a_namespace_declaration"> <source>Using directives must be placed outside of a namespace declaration</source> <target state="translated">using ディレクティブを namespace 宣言の外に配置する必要があります</target> <note>{Locked="using"} "using" is a C# keyword and should not be localized. {Locked="namespace"} "namespace" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="Variable_declaration_can_be_deconstructed"> <source>Variable declaration can be deconstructed</source> <target state="translated">変数の宣言を分解できます</target> <note /> </trans-unit> <trans-unit id="Variable_declaration_can_be_inlined"> <source>Variable declaration can be inlined</source> <target state="translated">変数の宣言をインライン化できます</target> <note /> </trans-unit> <trans-unit id="Warning_colon_Moving_using_directives_may_change_code_meaning"> <source>Warning: Moving using directives may change code meaning.</source> <target state="translated">警告: using ディレクティブを移動すると、コードの意味が変わる可能性があります。</target> <note>{Locked="using"} "using" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="_0_can_be_simplified"> <source>{0} can be simplified</source> <target state="translated">{0} を簡素化できます</target> <note /> </trans-unit> <trans-unit id="default_expression_can_be_simplified"> <source>'default' expression can be simplified</source> <target state="translated">'default' 式を簡素化できます</target> <note /> </trans-unit> <trans-unit id="if_statement_can_be_simplified"> <source>'if' statement can be simplified</source> <target state="translated">'if' ステートメントは簡素化できます</target> <note /> </trans-unit> <trans-unit id="new_expression_can_be_simplified"> <source>'new' expression can be simplified</source> <target state="translated">'new' 式を簡素化できます</target> <note /> </trans-unit> <trans-unit id="typeof_can_be_converted_ to_nameof"> <source>'typeof' can be converted to 'nameof'</source> <target state="translated">'typeof' を 'nameof' に変換できます</target> <note /> </trans-unit> <trans-unit id="use_var_instead_of_explicit_type"> <source>use 'var' instead of explicit type</source> <target state="translated">明示的な型ではなく 'var' を使用します</target> <note /> </trans-unit> <trans-unit id="Using_directive_is_unnecessary"> <source>Using directive is unnecessary.</source> <target state="translated">Using ディレクティブは必要ありません。</target> <note /> </trans-unit> <trans-unit id="using_statement_can_be_simplified"> <source>'using' statement can be simplified</source> <target state="translated">'using' ステートメントは簡素化できます</target> <note /> </trans-unit> </body> </file> </xliff>
<?xml version="1.0" encoding="utf-8"?> <xliff xmlns="urn:oasis:names:tc:xliff:document:1.2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="1.2" xsi:schemaLocation="urn:oasis:names:tc:xliff:document:1.2 xliff-core-1.2-transitional.xsd"> <file datatype="xml" source-language="en" target-language="ja" original="../CSharpAnalyzersResources.resx"> <body> <trans-unit id="Add_braces"> <source>Add braces</source> <target state="translated">波かっこを追加します</target> <note /> </trans-unit> <trans-unit id="Add_braces_to_0_statement"> <source>Add braces to '{0}' statement.</source> <target state="translated">'{0}' ステートメントに波かっこを追加します。</target> <note /> </trans-unit> <trans-unit id="Blank_line_not_allowed_after_constructor_initializer_colon"> <source>Blank line not allowed after constructor initializer colon</source> <target state="translated">コンストラクター初期化子のコロンの後に空白行を使用することはできません</target> <note /> </trans-unit> <trans-unit id="Consecutive_braces_must_not_have_a_blank_between_them"> <source>Consecutive braces must not have blank line between them</source> <target state="translated">連続する中かっこの間に空白行を含めることはできません</target> <note /> </trans-unit> <trans-unit id="Convert_switch_statement_to_expression"> <source>Convert switch statement to expression</source> <target state="translated">switch ステートメントを式に変換します</target> <note /> </trans-unit> <trans-unit id="Convert_to_block_scoped_namespace"> <source>Convert to block scoped namespace</source> <target state="new">Convert to block scoped namespace</target> <note>{Locked="namespace"} "namespace" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="Convert_to_file_scoped_namespace"> <source>Convert to file-scoped namespace</source> <target state="new">Convert to file-scoped namespace</target> <note>{Locked="namespace"} "namespace" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="Deconstruct_variable_declaration"> <source>Deconstruct variable declaration</source> <target state="translated">変数の宣言を分解</target> <note /> </trans-unit> <trans-unit id="Delegate_invocation_can_be_simplified"> <source>Delegate invocation can be simplified.</source> <target state="translated">デリゲート呼び出しを簡素化できます。</target> <note /> </trans-unit> <trans-unit id="Discard_can_be_removed"> <source>Discard can be removed</source> <target state="translated">ディスカードは削除できます</target> <note /> </trans-unit> <trans-unit id="Embedded_statements_must_be_on_their_own_line"> <source>Embedded statements must be on their own line</source> <target state="translated">埋め込みステートメントは独自の行に配置する必要があります</target> <note /> </trans-unit> <trans-unit id="Indexing_can_be_simplified"> <source>Indexing can be simplified</source> <target state="translated">インデックスの作成を簡素化することができます</target> <note /> </trans-unit> <trans-unit id="Inline_variable_declaration"> <source>Inline variable declaration</source> <target state="translated">インライン変数宣言</target> <note /> </trans-unit> <trans-unit id="Misplaced_using_directive"> <source>Misplaced using directive</source> <target state="translated">using ディレクティブが正しく配置されていません</target> <note>{Locked="using"} "using" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="Move_misplaced_using_directives"> <source>Move misplaced using directives</source> <target state="translated">誤って配置された using ディレクティブを移動します</target> <note>{Locked="using"} "using" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="Make_readonly_fields_writable"> <source>Make readonly fields writable</source> <target state="translated">readonly フィールドを書き込み可能にします</target> <note>{Locked="readonly"} "readonly" is C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="Local_function_can_be_made_static"> <source>Local function can be made static</source> <target state="translated">ローカル関数を静的にすることができます</target> <note /> </trans-unit> <trans-unit id="Make_local_function_static"> <source>Make local function 'static'</source> <target state="translated">ローカル関数を 'static' にします</target> <note /> </trans-unit> <trans-unit id="Negate_expression_changes_semantics"> <source>Negate expression (changes semantics)</source> <target state="translated">式の無効化 (セマンティクスを変更)</target> <note /> </trans-unit> <trans-unit id="Null_check_can_be_clarified"> <source>Null check can be clarified</source> <target state="new">Null check can be clarified</target> <note /> </trans-unit> <trans-unit id="Prefer_null_check_over_type_check"> <source>Prefer 'null' check over type check</source> <target state="new">Prefer 'null' check over type check</target> <note /> </trans-unit> <trans-unit id="Remove_operator_preserves_semantics"> <source>Remove operator (preserves semantics)</source> <target state="translated">演算子の削除 (セマンティクスを保持)</target> <note /> </trans-unit> <trans-unit id="Remove_suppression_operators"> <source>Remove suppression operators</source> <target state="translated">抑制演算子の削除</target> <note /> </trans-unit> <trans-unit id="Remove_unnecessary_suppression_operator"> <source>Remove unnecessary suppression operator</source> <target state="translated">不要な抑制演算子を削除します</target> <note /> </trans-unit> <trans-unit id="Remove_unnessary_discard"> <source>Remove unnecessary discard</source> <target state="translated">不要なディスカードを削除</target> <note /> </trans-unit> <trans-unit id="Simplify_default_expression"> <source>Simplify 'default' expression</source> <target state="translated">default' 式を単純化する</target> <note /> </trans-unit> <trans-unit id="Struct_contains_assignment_to_this_outside_of_constructor_Make_readonly_fields_writable"> <source>Struct contains assignment to 'this' outside of constructor. Make readonly fields writable.</source> <target state="translated">Struct に、コンストラクター外部の 'this' に対する代入が含まれています。読み取り専用フィールドを書き込み可能にしてください。</target> <note>{Locked="Struct"}{Locked="this"} these are C#/VB keywords and should not be localized.</note> </trans-unit> <trans-unit id="Suppression_operator_has_no_effect_and_can_be_misinterpreted"> <source>Suppression operator has no effect and can be misinterpreted</source> <target state="translated">抑制演算子は効果がなく、誤って解釈される可能性があります</target> <note /> </trans-unit> <trans-unit id="Unreachable_code_detected"> <source>Unreachable code detected</source> <target state="translated">到達できないコードが検出されました</target> <note /> </trans-unit> <trans-unit id="Use_block_body_for_accessors"> <source>Use block body for accessors</source> <target state="translated">アクセサーにブロック本体を使用する</target> <note /> </trans-unit> <trans-unit id="Use_block_body_for_constructors"> <source>Use block body for constructors</source> <target state="translated">コンストラクターにブロック本体を使用する</target> <note /> </trans-unit> <trans-unit id="Use_block_body_for_indexers"> <source>Use block body for indexers</source> <target state="translated">インデクサーにブロック本体を使用する</target> <note /> </trans-unit> <trans-unit id="Use_block_body_for_local_functions"> <source>Use block body for local functions</source> <target state="translated">ローカル関数にブロック本体を使用します</target> <note /> </trans-unit> <trans-unit id="Use_block_body_for_methods"> <source>Use block body for methods</source> <target state="translated">メソッドにブロック本体を使用する</target> <note /> </trans-unit> <trans-unit id="Use_block_body_for_operators"> <source>Use block body for operators</source> <target state="translated">オペレーターにブロック本体を使用する</target> <note /> </trans-unit> <trans-unit id="Use_block_body_for_properties"> <source>Use block body for properties</source> <target state="translated">プロパティにブロック本体を使用する</target> <note /> </trans-unit> <trans-unit id="Use_explicit_type"> <source>Use explicit type</source> <target state="translated">明示的な型の使用</target> <note /> </trans-unit> <trans-unit id="Use_explicit_type_instead_of_var"> <source>Use explicit type instead of 'var'</source> <target state="translated">var' ではなく明示的な型を使用します</target> <note /> </trans-unit> <trans-unit id="Use_expression_body_for_accessors"> <source>Use expression body for accessors</source> <target state="translated">アクセサーに式本体を使用する</target> <note /> </trans-unit> <trans-unit id="Use_expression_body_for_constructors"> <source>Use expression body for constructors</source> <target state="translated">コンストラクターに式本体を使用する</target> <note /> </trans-unit> <trans-unit id="Use_expression_body_for_indexers"> <source>Use expression body for indexers</source> <target state="translated">インデクサーに式本体を使用する</target> <note /> </trans-unit> <trans-unit id="Use_expression_body_for_local_functions"> <source>Use expression body for local functions</source> <target state="translated">ローカル関数に式本体を使用します</target> <note /> </trans-unit> <trans-unit id="Use_expression_body_for_methods"> <source>Use expression body for methods</source> <target state="translated">メソッドに式本体を使用する</target> <note /> </trans-unit> <trans-unit id="Use_expression_body_for_operators"> <source>Use expression body for operators</source> <target state="translated">オペレーターに式本体を使用する</target> <note /> </trans-unit> <trans-unit id="Use_expression_body_for_properties"> <source>Use expression body for properties</source> <target state="translated">プロパティに式本体を使用する</target> <note /> </trans-unit> <trans-unit id="Use_implicit_type"> <source>Use implicit type</source> <target state="translated">暗黙的な型の使用</target> <note /> </trans-unit> <trans-unit id="Use_index_operator"> <source>Use index operator</source> <target state="translated">インデックス演算子を使用</target> <note /> </trans-unit> <trans-unit id="Use_is_null_check"> <source>Use 'is null' check</source> <target state="translated">is null' チェックを使用します</target> <note /> </trans-unit> <trans-unit id="Use_local_function"> <source>Use local function</source> <target state="translated">ローカル関数を使用します</target> <note /> </trans-unit> <trans-unit id="Use_new"> <source>Use 'new(...)'</source> <target state="translated">'new(...)' を使用する</target> <note>{Locked="new(...)"} This is a C# construct and should not be localized.</note> </trans-unit> <trans-unit id="Use_pattern_matching"> <source>Use pattern matching</source> <target state="translated">パターン マッチングを使用します</target> <note /> </trans-unit> <trans-unit id="Use_pattern_matching_may_change_code_meaning"> <source>Use pattern matching (may change code meaning)</source> <target state="new">Use pattern matching (may change code meaning)</target> <note /> </trans-unit> <trans-unit id="Use_range_operator"> <source>Use range operator</source> <target state="translated">範囲演算子を使用</target> <note /> </trans-unit> <trans-unit id="Use_simple_using_statement"> <source>Use simple 'using' statement</source> <target state="translated">単純な 'using' ステートメントを使用する</target> <note /> </trans-unit> <trans-unit id="Use_switch_expression"> <source>Use 'switch' expression</source> <target state="translated">'switch' 式を使用します</target> <note /> </trans-unit> <trans-unit id="Using_directives_must_be_placed_inside_of_a_namespace_declaration"> <source>Using directives must be placed inside of a namespace declaration</source> <target state="translated">using ディレクティブを namespace 宣言の中に配置する必要があります</target> <note>{Locked="using"} "using" is a C# keyword and should not be localized. {Locked="namespace"} "namespace" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="Using_directives_must_be_placed_outside_of_a_namespace_declaration"> <source>Using directives must be placed outside of a namespace declaration</source> <target state="translated">using ディレクティブを namespace 宣言の外に配置する必要があります</target> <note>{Locked="using"} "using" is a C# keyword and should not be localized. {Locked="namespace"} "namespace" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="Variable_declaration_can_be_deconstructed"> <source>Variable declaration can be deconstructed</source> <target state="translated">変数の宣言を分解できます</target> <note /> </trans-unit> <trans-unit id="Variable_declaration_can_be_inlined"> <source>Variable declaration can be inlined</source> <target state="translated">変数の宣言をインライン化できます</target> <note /> </trans-unit> <trans-unit id="Warning_colon_Moving_using_directives_may_change_code_meaning"> <source>Warning: Moving using directives may change code meaning.</source> <target state="translated">警告: using ディレクティブを移動すると、コードの意味が変わる可能性があります。</target> <note>{Locked="using"} "using" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="_0_can_be_simplified"> <source>{0} can be simplified</source> <target state="translated">{0} を簡素化できます</target> <note /> </trans-unit> <trans-unit id="default_expression_can_be_simplified"> <source>'default' expression can be simplified</source> <target state="translated">'default' 式を簡素化できます</target> <note /> </trans-unit> <trans-unit id="if_statement_can_be_simplified"> <source>'if' statement can be simplified</source> <target state="translated">'if' ステートメントは簡素化できます</target> <note /> </trans-unit> <trans-unit id="new_expression_can_be_simplified"> <source>'new' expression can be simplified</source> <target state="translated">'new' 式を簡素化できます</target> <note /> </trans-unit> <trans-unit id="typeof_can_be_converted_ to_nameof"> <source>'typeof' can be converted to 'nameof'</source> <target state="translated">'typeof' を 'nameof' に変換できます</target> <note /> </trans-unit> <trans-unit id="use_var_instead_of_explicit_type"> <source>use 'var' instead of explicit type</source> <target state="translated">明示的な型ではなく 'var' を使用します</target> <note /> </trans-unit> <trans-unit id="Using_directive_is_unnecessary"> <source>Using directive is unnecessary.</source> <target state="translated">Using ディレクティブは必要ありません。</target> <note /> </trans-unit> <trans-unit id="using_statement_can_be_simplified"> <source>'using' statement can be simplified</source> <target state="translated">'using' ステートメントは簡素化できます</target> <note /> </trans-unit> </body> </file> </xliff>
1
dotnet/roslyn
55,427
Fixes #50462
Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
Blokyk
2021-08-05T01:17:37Z
2021-08-25T05:42:59Z
fefb8c2110625bc4908db4bbdaa367b12bfb1069
fb4ac545a1f1f365e7df570637699d9085ea4f87
Fixes #50462. Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
./src/Analyzers/CSharp/Analyzers/xlf/CSharpAnalyzersResources.ko.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="ko" original="../CSharpAnalyzersResources.resx"> <body> <trans-unit id="Add_braces"> <source>Add braces</source> <target state="translated">중괄호 추가</target> <note /> </trans-unit> <trans-unit id="Add_braces_to_0_statement"> <source>Add braces to '{0}' statement.</source> <target state="translated">'{0}' 문에 중괄호를 추가합니다.</target> <note /> </trans-unit> <trans-unit id="Blank_line_not_allowed_after_constructor_initializer_colon"> <source>Blank line not allowed after constructor initializer colon</source> <target state="translated">생성자 이니셜라이저 콜론 뒤에 빈 줄을 사용할 수 없음</target> <note /> </trans-unit> <trans-unit id="Consecutive_braces_must_not_have_a_blank_between_them"> <source>Consecutive braces must not have blank line between them</source> <target state="translated">연속 중괄호 사이에 빈 줄이 없어야 함</target> <note /> </trans-unit> <trans-unit id="Convert_switch_statement_to_expression"> <source>Convert switch statement to expression</source> <target state="translated">switch 문을 식으로 변환</target> <note /> </trans-unit> <trans-unit id="Convert_to_block_scoped_namespace"> <source>Convert to block scoped namespace</source> <target state="new">Convert to block scoped namespace</target> <note>{Locked="namespace"} "namespace" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="Convert_to_file_scoped_namespace"> <source>Convert to file-scoped namespace</source> <target state="new">Convert to file-scoped namespace</target> <note>{Locked="namespace"} "namespace" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="Deconstruct_variable_declaration"> <source>Deconstruct variable declaration</source> <target state="translated">변수 선언 분해</target> <note /> </trans-unit> <trans-unit id="Delegate_invocation_can_be_simplified"> <source>Delegate invocation can be simplified.</source> <target state="translated">대리자 호출을 단순화할 수 있습니다.</target> <note /> </trans-unit> <trans-unit id="Discard_can_be_removed"> <source>Discard can be removed</source> <target state="translated">무시 항목은 제거할 수 있습니다.</target> <note /> </trans-unit> <trans-unit id="Embedded_statements_must_be_on_their_own_line"> <source>Embedded statements must be on their own line</source> <target state="translated">포함 문은 고유한 줄에 있어야 합니다.</target> <note /> </trans-unit> <trans-unit id="Indexing_can_be_simplified"> <source>Indexing can be simplified</source> <target state="translated">인덱싱을 단순화할 수 있습니다.</target> <note /> </trans-unit> <trans-unit id="Inline_variable_declaration"> <source>Inline variable declaration</source> <target state="translated">인라인 변수 선언</target> <note /> </trans-unit> <trans-unit id="Misplaced_using_directive"> <source>Misplaced using directive</source> <target state="translated">위치가 잘못된 using 지시문</target> <note>{Locked="using"} "using" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="Move_misplaced_using_directives"> <source>Move misplaced using directives</source> <target state="translated">위치가 잘못된 using 지시문 이동</target> <note>{Locked="using"} "using" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="Make_readonly_fields_writable"> <source>Make readonly fields writable</source> <target state="translated">readonly 필드를 쓰기 가능으로 지정</target> <note>{Locked="readonly"} "readonly" is C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="Local_function_can_be_made_static"> <source>Local function can be made static</source> <target state="translated">로컬 함수를 정적으로 지정할 수 있습니다.</target> <note /> </trans-unit> <trans-unit id="Make_local_function_static"> <source>Make local function 'static'</source> <target state="translated">로컬 함수를 '정적'으로 지정</target> <note /> </trans-unit> <trans-unit id="Negate_expression_changes_semantics"> <source>Negate expression (changes semantics)</source> <target state="translated">식 부정(의미 체계를 변경함)</target> <note /> </trans-unit> <trans-unit id="Null_check_can_be_clarified"> <source>Null check can be clarified</source> <target state="new">Null check can be clarified</target> <note /> </trans-unit> <trans-unit id="Prefer_null_check_over_type_check"> <source>Prefer 'null' check over type check</source> <target state="new">Prefer 'null' check over type check</target> <note /> </trans-unit> <trans-unit id="Remove_operator_preserves_semantics"> <source>Remove operator (preserves semantics)</source> <target state="translated">연산자 제거(의미 체계를 유지함)</target> <note /> </trans-unit> <trans-unit id="Remove_suppression_operators"> <source>Remove suppression operators</source> <target state="translated">비표시 오류(Suppression) 연산자 제거</target> <note /> </trans-unit> <trans-unit id="Remove_unnecessary_suppression_operator"> <source>Remove unnecessary suppression operator</source> <target state="translated">불필요한 비표시 오류(Suppression) 연산자 제거</target> <note /> </trans-unit> <trans-unit id="Remove_unnessary_discard"> <source>Remove unnecessary discard</source> <target state="translated">불필요한 무시 항목 제거</target> <note /> </trans-unit> <trans-unit id="Simplify_default_expression"> <source>Simplify 'default' expression</source> <target state="translated">default' 식 단순화</target> <note /> </trans-unit> <trans-unit id="Struct_contains_assignment_to_this_outside_of_constructor_Make_readonly_fields_writable"> <source>Struct contains assignment to 'this' outside of constructor. Make readonly fields writable.</source> <target state="translated">Struct에서 'this'에 대한 할당이 생성자 외부에 있습니다. 읽기 전용 필드를 쓰기 가능으로 설정하세요.</target> <note>{Locked="Struct"}{Locked="this"} these are C#/VB keywords and should not be localized.</note> </trans-unit> <trans-unit id="Suppression_operator_has_no_effect_and_can_be_misinterpreted"> <source>Suppression operator has no effect and can be misinterpreted</source> <target state="translated">비표시 오류(Suppression) 연산자는 아무런 영향을 주지 않으며 잘못 해석될 수 있습니다.</target> <note /> </trans-unit> <trans-unit id="Unreachable_code_detected"> <source>Unreachable code detected</source> <target state="translated">접근할 수 없는 코드가 있습니다.</target> <note /> </trans-unit> <trans-unit id="Use_block_body_for_accessors"> <source>Use block body for accessors</source> <target state="translated">접근자에 블록 본문 사용</target> <note /> </trans-unit> <trans-unit id="Use_block_body_for_constructors"> <source>Use block body for constructors</source> <target state="translated">생성자에 블록 본문 사용</target> <note /> </trans-unit> <trans-unit id="Use_block_body_for_indexers"> <source>Use block body for indexers</source> <target state="translated">인덱서에 블록 본문 사용</target> <note /> </trans-unit> <trans-unit id="Use_block_body_for_local_functions"> <source>Use block body for local functions</source> <target state="translated">로컬 함수에 블록 본문 사용</target> <note /> </trans-unit> <trans-unit id="Use_block_body_for_methods"> <source>Use block body for methods</source> <target state="translated">메서드에 블록 본문 사용</target> <note /> </trans-unit> <trans-unit id="Use_block_body_for_operators"> <source>Use block body for operators</source> <target state="translated">연산자에 블록 본문 사용</target> <note /> </trans-unit> <trans-unit id="Use_block_body_for_properties"> <source>Use block body for properties</source> <target state="translated">속성에 블록 본문 사용</target> <note /> </trans-unit> <trans-unit id="Use_explicit_type"> <source>Use explicit type</source> <target state="translated">명시적 형식 사용</target> <note /> </trans-unit> <trans-unit id="Use_explicit_type_instead_of_var"> <source>Use explicit type instead of 'var'</source> <target state="translated">var' 대신에 명시적 형식을 사용합니다.</target> <note /> </trans-unit> <trans-unit id="Use_expression_body_for_accessors"> <source>Use expression body for accessors</source> <target state="translated">접근자에 식 본문 사용</target> <note /> </trans-unit> <trans-unit id="Use_expression_body_for_constructors"> <source>Use expression body for constructors</source> <target state="translated">생성자에 식 본문 사용</target> <note /> </trans-unit> <trans-unit id="Use_expression_body_for_indexers"> <source>Use expression body for indexers</source> <target state="translated">인덱서에 식 본문 사용</target> <note /> </trans-unit> <trans-unit id="Use_expression_body_for_local_functions"> <source>Use expression body for local functions</source> <target state="translated">로컬 함수의 식 본문 사용</target> <note /> </trans-unit> <trans-unit id="Use_expression_body_for_methods"> <source>Use expression body for methods</source> <target state="translated">메서드에 식 본문 사용</target> <note /> </trans-unit> <trans-unit id="Use_expression_body_for_operators"> <source>Use expression body for operators</source> <target state="translated">연산자에 식 본문 사용</target> <note /> </trans-unit> <trans-unit id="Use_expression_body_for_properties"> <source>Use expression body for properties</source> <target state="translated">속성에 식 본문 사용</target> <note /> </trans-unit> <trans-unit id="Use_implicit_type"> <source>Use implicit type</source> <target state="translated">암시적 형식 사용</target> <note /> </trans-unit> <trans-unit id="Use_index_operator"> <source>Use index operator</source> <target state="translated">인덱스 연산자 사용</target> <note /> </trans-unit> <trans-unit id="Use_is_null_check"> <source>Use 'is null' check</source> <target state="translated">is null' 검사 사용</target> <note /> </trans-unit> <trans-unit id="Use_local_function"> <source>Use local function</source> <target state="translated">로컬 함수 사용</target> <note /> </trans-unit> <trans-unit id="Use_new"> <source>Use 'new(...)'</source> <target state="translated">'new(...)' 사용</target> <note>{Locked="new(...)"} This is a C# construct and should not be localized.</note> </trans-unit> <trans-unit id="Use_pattern_matching"> <source>Use pattern matching</source> <target state="translated">패턴 일치 사용</target> <note /> </trans-unit> <trans-unit id="Use_range_operator"> <source>Use range operator</source> <target state="translated">범위 연산자 사용</target> <note /> </trans-unit> <trans-unit id="Use_simple_using_statement"> <source>Use simple 'using' statement</source> <target state="translated">간단한 'using' 문 사용</target> <note /> </trans-unit> <trans-unit id="Use_switch_expression"> <source>Use 'switch' expression</source> <target state="translated">'switch' 식 사용</target> <note /> </trans-unit> <trans-unit id="Using_directives_must_be_placed_inside_of_a_namespace_declaration"> <source>Using directives must be placed inside of a namespace declaration</source> <target state="translated">Using 지시문은 namespace 선언 내부에 배치되어야 합니다.</target> <note>{Locked="using"} "using" is a C# keyword and should not be localized. {Locked="namespace"} "namespace" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="Using_directives_must_be_placed_outside_of_a_namespace_declaration"> <source>Using directives must be placed outside of a namespace declaration</source> <target state="translated">Using 지시문은 namespace 선언 외부에 배치되어야 합니다.</target> <note>{Locked="using"} "using" is a C# keyword and should not be localized. {Locked="namespace"} "namespace" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="Variable_declaration_can_be_deconstructed"> <source>Variable declaration can be deconstructed</source> <target state="translated">변수 선언을 분해할 수 있습니다.</target> <note /> </trans-unit> <trans-unit id="Variable_declaration_can_be_inlined"> <source>Variable declaration can be inlined</source> <target state="translated">변수 선언은 인라인될 수 있습니다.</target> <note /> </trans-unit> <trans-unit id="Warning_colon_Moving_using_directives_may_change_code_meaning"> <source>Warning: Moving using directives may change code meaning.</source> <target state="translated">경고: using 지시문을 이동하면 코드 의미가 변경될 수 있습니다.</target> <note>{Locked="using"} "using" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="_0_can_be_simplified"> <source>{0} can be simplified</source> <target state="translated">{0}을(를) 단순화할 수 있습니다.</target> <note /> </trans-unit> <trans-unit id="default_expression_can_be_simplified"> <source>'default' expression can be simplified</source> <target state="translated">'default' 식을 단순화할 수 있습니다.</target> <note /> </trans-unit> <trans-unit id="if_statement_can_be_simplified"> <source>'if' statement can be simplified</source> <target state="translated">'if' 문을 단순화할 수 있습니다.</target> <note /> </trans-unit> <trans-unit id="new_expression_can_be_simplified"> <source>'new' expression can be simplified</source> <target state="translated">'new' 식을 단순화할 수 있습니다.</target> <note /> </trans-unit> <trans-unit id="typeof_can_be_converted_ to_nameof"> <source>'typeof' can be converted to 'nameof'</source> <target state="translated">'typeof'를 'nameof'로 변환할 수 있습니다.</target> <note /> </trans-unit> <trans-unit id="use_var_instead_of_explicit_type"> <source>use 'var' instead of explicit type</source> <target state="translated">대신 명시적 형식의 'var'을 사용합니다.</target> <note /> </trans-unit> <trans-unit id="Using_directive_is_unnecessary"> <source>Using directive is unnecessary.</source> <target state="translated">Using 지시문은 필요하지 않습니다.</target> <note /> </trans-unit> <trans-unit id="using_statement_can_be_simplified"> <source>'using' statement can be simplified</source> <target state="translated">'using' 문을 단순화할 수 있습니다.</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="ko" original="../CSharpAnalyzersResources.resx"> <body> <trans-unit id="Add_braces"> <source>Add braces</source> <target state="translated">중괄호 추가</target> <note /> </trans-unit> <trans-unit id="Add_braces_to_0_statement"> <source>Add braces to '{0}' statement.</source> <target state="translated">'{0}' 문에 중괄호를 추가합니다.</target> <note /> </trans-unit> <trans-unit id="Blank_line_not_allowed_after_constructor_initializer_colon"> <source>Blank line not allowed after constructor initializer colon</source> <target state="translated">생성자 이니셜라이저 콜론 뒤에 빈 줄을 사용할 수 없음</target> <note /> </trans-unit> <trans-unit id="Consecutive_braces_must_not_have_a_blank_between_them"> <source>Consecutive braces must not have blank line between them</source> <target state="translated">연속 중괄호 사이에 빈 줄이 없어야 함</target> <note /> </trans-unit> <trans-unit id="Convert_switch_statement_to_expression"> <source>Convert switch statement to expression</source> <target state="translated">switch 문을 식으로 변환</target> <note /> </trans-unit> <trans-unit id="Convert_to_block_scoped_namespace"> <source>Convert to block scoped namespace</source> <target state="new">Convert to block scoped namespace</target> <note>{Locked="namespace"} "namespace" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="Convert_to_file_scoped_namespace"> <source>Convert to file-scoped namespace</source> <target state="new">Convert to file-scoped namespace</target> <note>{Locked="namespace"} "namespace" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="Deconstruct_variable_declaration"> <source>Deconstruct variable declaration</source> <target state="translated">변수 선언 분해</target> <note /> </trans-unit> <trans-unit id="Delegate_invocation_can_be_simplified"> <source>Delegate invocation can be simplified.</source> <target state="translated">대리자 호출을 단순화할 수 있습니다.</target> <note /> </trans-unit> <trans-unit id="Discard_can_be_removed"> <source>Discard can be removed</source> <target state="translated">무시 항목은 제거할 수 있습니다.</target> <note /> </trans-unit> <trans-unit id="Embedded_statements_must_be_on_their_own_line"> <source>Embedded statements must be on their own line</source> <target state="translated">포함 문은 고유한 줄에 있어야 합니다.</target> <note /> </trans-unit> <trans-unit id="Indexing_can_be_simplified"> <source>Indexing can be simplified</source> <target state="translated">인덱싱을 단순화할 수 있습니다.</target> <note /> </trans-unit> <trans-unit id="Inline_variable_declaration"> <source>Inline variable declaration</source> <target state="translated">인라인 변수 선언</target> <note /> </trans-unit> <trans-unit id="Misplaced_using_directive"> <source>Misplaced using directive</source> <target state="translated">위치가 잘못된 using 지시문</target> <note>{Locked="using"} "using" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="Move_misplaced_using_directives"> <source>Move misplaced using directives</source> <target state="translated">위치가 잘못된 using 지시문 이동</target> <note>{Locked="using"} "using" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="Make_readonly_fields_writable"> <source>Make readonly fields writable</source> <target state="translated">readonly 필드를 쓰기 가능으로 지정</target> <note>{Locked="readonly"} "readonly" is C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="Local_function_can_be_made_static"> <source>Local function can be made static</source> <target state="translated">로컬 함수를 정적으로 지정할 수 있습니다.</target> <note /> </trans-unit> <trans-unit id="Make_local_function_static"> <source>Make local function 'static'</source> <target state="translated">로컬 함수를 '정적'으로 지정</target> <note /> </trans-unit> <trans-unit id="Negate_expression_changes_semantics"> <source>Negate expression (changes semantics)</source> <target state="translated">식 부정(의미 체계를 변경함)</target> <note /> </trans-unit> <trans-unit id="Null_check_can_be_clarified"> <source>Null check can be clarified</source> <target state="new">Null check can be clarified</target> <note /> </trans-unit> <trans-unit id="Prefer_null_check_over_type_check"> <source>Prefer 'null' check over type check</source> <target state="new">Prefer 'null' check over type check</target> <note /> </trans-unit> <trans-unit id="Remove_operator_preserves_semantics"> <source>Remove operator (preserves semantics)</source> <target state="translated">연산자 제거(의미 체계를 유지함)</target> <note /> </trans-unit> <trans-unit id="Remove_suppression_operators"> <source>Remove suppression operators</source> <target state="translated">비표시 오류(Suppression) 연산자 제거</target> <note /> </trans-unit> <trans-unit id="Remove_unnecessary_suppression_operator"> <source>Remove unnecessary suppression operator</source> <target state="translated">불필요한 비표시 오류(Suppression) 연산자 제거</target> <note /> </trans-unit> <trans-unit id="Remove_unnessary_discard"> <source>Remove unnecessary discard</source> <target state="translated">불필요한 무시 항목 제거</target> <note /> </trans-unit> <trans-unit id="Simplify_default_expression"> <source>Simplify 'default' expression</source> <target state="translated">default' 식 단순화</target> <note /> </trans-unit> <trans-unit id="Struct_contains_assignment_to_this_outside_of_constructor_Make_readonly_fields_writable"> <source>Struct contains assignment to 'this' outside of constructor. Make readonly fields writable.</source> <target state="translated">Struct에서 'this'에 대한 할당이 생성자 외부에 있습니다. 읽기 전용 필드를 쓰기 가능으로 설정하세요.</target> <note>{Locked="Struct"}{Locked="this"} these are C#/VB keywords and should not be localized.</note> </trans-unit> <trans-unit id="Suppression_operator_has_no_effect_and_can_be_misinterpreted"> <source>Suppression operator has no effect and can be misinterpreted</source> <target state="translated">비표시 오류(Suppression) 연산자는 아무런 영향을 주지 않으며 잘못 해석될 수 있습니다.</target> <note /> </trans-unit> <trans-unit id="Unreachable_code_detected"> <source>Unreachable code detected</source> <target state="translated">접근할 수 없는 코드가 있습니다.</target> <note /> </trans-unit> <trans-unit id="Use_block_body_for_accessors"> <source>Use block body for accessors</source> <target state="translated">접근자에 블록 본문 사용</target> <note /> </trans-unit> <trans-unit id="Use_block_body_for_constructors"> <source>Use block body for constructors</source> <target state="translated">생성자에 블록 본문 사용</target> <note /> </trans-unit> <trans-unit id="Use_block_body_for_indexers"> <source>Use block body for indexers</source> <target state="translated">인덱서에 블록 본문 사용</target> <note /> </trans-unit> <trans-unit id="Use_block_body_for_local_functions"> <source>Use block body for local functions</source> <target state="translated">로컬 함수에 블록 본문 사용</target> <note /> </trans-unit> <trans-unit id="Use_block_body_for_methods"> <source>Use block body for methods</source> <target state="translated">메서드에 블록 본문 사용</target> <note /> </trans-unit> <trans-unit id="Use_block_body_for_operators"> <source>Use block body for operators</source> <target state="translated">연산자에 블록 본문 사용</target> <note /> </trans-unit> <trans-unit id="Use_block_body_for_properties"> <source>Use block body for properties</source> <target state="translated">속성에 블록 본문 사용</target> <note /> </trans-unit> <trans-unit id="Use_explicit_type"> <source>Use explicit type</source> <target state="translated">명시적 형식 사용</target> <note /> </trans-unit> <trans-unit id="Use_explicit_type_instead_of_var"> <source>Use explicit type instead of 'var'</source> <target state="translated">var' 대신에 명시적 형식을 사용합니다.</target> <note /> </trans-unit> <trans-unit id="Use_expression_body_for_accessors"> <source>Use expression body for accessors</source> <target state="translated">접근자에 식 본문 사용</target> <note /> </trans-unit> <trans-unit id="Use_expression_body_for_constructors"> <source>Use expression body for constructors</source> <target state="translated">생성자에 식 본문 사용</target> <note /> </trans-unit> <trans-unit id="Use_expression_body_for_indexers"> <source>Use expression body for indexers</source> <target state="translated">인덱서에 식 본문 사용</target> <note /> </trans-unit> <trans-unit id="Use_expression_body_for_local_functions"> <source>Use expression body for local functions</source> <target state="translated">로컬 함수의 식 본문 사용</target> <note /> </trans-unit> <trans-unit id="Use_expression_body_for_methods"> <source>Use expression body for methods</source> <target state="translated">메서드에 식 본문 사용</target> <note /> </trans-unit> <trans-unit id="Use_expression_body_for_operators"> <source>Use expression body for operators</source> <target state="translated">연산자에 식 본문 사용</target> <note /> </trans-unit> <trans-unit id="Use_expression_body_for_properties"> <source>Use expression body for properties</source> <target state="translated">속성에 식 본문 사용</target> <note /> </trans-unit> <trans-unit id="Use_implicit_type"> <source>Use implicit type</source> <target state="translated">암시적 형식 사용</target> <note /> </trans-unit> <trans-unit id="Use_index_operator"> <source>Use index operator</source> <target state="translated">인덱스 연산자 사용</target> <note /> </trans-unit> <trans-unit id="Use_is_null_check"> <source>Use 'is null' check</source> <target state="translated">is null' 검사 사용</target> <note /> </trans-unit> <trans-unit id="Use_local_function"> <source>Use local function</source> <target state="translated">로컬 함수 사용</target> <note /> </trans-unit> <trans-unit id="Use_new"> <source>Use 'new(...)'</source> <target state="translated">'new(...)' 사용</target> <note>{Locked="new(...)"} This is a C# construct and should not be localized.</note> </trans-unit> <trans-unit id="Use_pattern_matching"> <source>Use pattern matching</source> <target state="translated">패턴 일치 사용</target> <note /> </trans-unit> <trans-unit id="Use_pattern_matching_may_change_code_meaning"> <source>Use pattern matching (may change code meaning)</source> <target state="new">Use pattern matching (may change code meaning)</target> <note /> </trans-unit> <trans-unit id="Use_range_operator"> <source>Use range operator</source> <target state="translated">범위 연산자 사용</target> <note /> </trans-unit> <trans-unit id="Use_simple_using_statement"> <source>Use simple 'using' statement</source> <target state="translated">간단한 'using' 문 사용</target> <note /> </trans-unit> <trans-unit id="Use_switch_expression"> <source>Use 'switch' expression</source> <target state="translated">'switch' 식 사용</target> <note /> </trans-unit> <trans-unit id="Using_directives_must_be_placed_inside_of_a_namespace_declaration"> <source>Using directives must be placed inside of a namespace declaration</source> <target state="translated">Using 지시문은 namespace 선언 내부에 배치되어야 합니다.</target> <note>{Locked="using"} "using" is a C# keyword and should not be localized. {Locked="namespace"} "namespace" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="Using_directives_must_be_placed_outside_of_a_namespace_declaration"> <source>Using directives must be placed outside of a namespace declaration</source> <target state="translated">Using 지시문은 namespace 선언 외부에 배치되어야 합니다.</target> <note>{Locked="using"} "using" is a C# keyword and should not be localized. {Locked="namespace"} "namespace" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="Variable_declaration_can_be_deconstructed"> <source>Variable declaration can be deconstructed</source> <target state="translated">변수 선언을 분해할 수 있습니다.</target> <note /> </trans-unit> <trans-unit id="Variable_declaration_can_be_inlined"> <source>Variable declaration can be inlined</source> <target state="translated">변수 선언은 인라인될 수 있습니다.</target> <note /> </trans-unit> <trans-unit id="Warning_colon_Moving_using_directives_may_change_code_meaning"> <source>Warning: Moving using directives may change code meaning.</source> <target state="translated">경고: using 지시문을 이동하면 코드 의미가 변경될 수 있습니다.</target> <note>{Locked="using"} "using" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="_0_can_be_simplified"> <source>{0} can be simplified</source> <target state="translated">{0}을(를) 단순화할 수 있습니다.</target> <note /> </trans-unit> <trans-unit id="default_expression_can_be_simplified"> <source>'default' expression can be simplified</source> <target state="translated">'default' 식을 단순화할 수 있습니다.</target> <note /> </trans-unit> <trans-unit id="if_statement_can_be_simplified"> <source>'if' statement can be simplified</source> <target state="translated">'if' 문을 단순화할 수 있습니다.</target> <note /> </trans-unit> <trans-unit id="new_expression_can_be_simplified"> <source>'new' expression can be simplified</source> <target state="translated">'new' 식을 단순화할 수 있습니다.</target> <note /> </trans-unit> <trans-unit id="typeof_can_be_converted_ to_nameof"> <source>'typeof' can be converted to 'nameof'</source> <target state="translated">'typeof'를 'nameof'로 변환할 수 있습니다.</target> <note /> </trans-unit> <trans-unit id="use_var_instead_of_explicit_type"> <source>use 'var' instead of explicit type</source> <target state="translated">대신 명시적 형식의 'var'을 사용합니다.</target> <note /> </trans-unit> <trans-unit id="Using_directive_is_unnecessary"> <source>Using directive is unnecessary.</source> <target state="translated">Using 지시문은 필요하지 않습니다.</target> <note /> </trans-unit> <trans-unit id="using_statement_can_be_simplified"> <source>'using' statement can be simplified</source> <target state="translated">'using' 문을 단순화할 수 있습니다.</target> <note /> </trans-unit> </body> </file> </xliff>
1
dotnet/roslyn
55,427
Fixes #50462
Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
Blokyk
2021-08-05T01:17:37Z
2021-08-25T05:42:59Z
fefb8c2110625bc4908db4bbdaa367b12bfb1069
fb4ac545a1f1f365e7df570637699d9085ea4f87
Fixes #50462. Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
./src/Analyzers/CSharp/Analyzers/xlf/CSharpAnalyzersResources.pl.xlf
<?xml version="1.0" encoding="utf-8"?> <xliff xmlns="urn:oasis:names:tc:xliff:document:1.2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="1.2" xsi:schemaLocation="urn:oasis:names:tc:xliff:document:1.2 xliff-core-1.2-transitional.xsd"> <file datatype="xml" source-language="en" target-language="pl" original="../CSharpAnalyzersResources.resx"> <body> <trans-unit id="Add_braces"> <source>Add braces</source> <target state="translated">Dodaj nawiasy klamrowe</target> <note /> </trans-unit> <trans-unit id="Add_braces_to_0_statement"> <source>Add braces to '{0}' statement.</source> <target state="translated">Dodaj nawiasy klamrowe do instrukcji „{0}”.</target> <note /> </trans-unit> <trans-unit id="Blank_line_not_allowed_after_constructor_initializer_colon"> <source>Blank line not allowed after constructor initializer colon</source> <target state="translated">Pusty wiersz jest niedozwolony po dwukropku inicjatora konstruktora</target> <note /> </trans-unit> <trans-unit id="Consecutive_braces_must_not_have_a_blank_between_them"> <source>Consecutive braces must not have blank line between them</source> <target state="translated">Między kolejnymi nawiasami klamrowymi nie może znajdować się pusty wiersz.</target> <note /> </trans-unit> <trans-unit id="Convert_switch_statement_to_expression"> <source>Convert switch statement to expression</source> <target state="translated">Konwertuj instrukcję switch na wyrażenie</target> <note /> </trans-unit> <trans-unit id="Convert_to_block_scoped_namespace"> <source>Convert to block scoped namespace</source> <target state="new">Convert to block scoped namespace</target> <note>{Locked="namespace"} "namespace" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="Convert_to_file_scoped_namespace"> <source>Convert to file-scoped namespace</source> <target state="new">Convert to file-scoped namespace</target> <note>{Locked="namespace"} "namespace" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="Deconstruct_variable_declaration"> <source>Deconstruct variable declaration</source> <target state="translated">Zdekonstruuj deklarację zmiennej</target> <note /> </trans-unit> <trans-unit id="Delegate_invocation_can_be_simplified"> <source>Delegate invocation can be simplified.</source> <target state="translated">Wywołanie delegata można uprościć.</target> <note /> </trans-unit> <trans-unit id="Discard_can_be_removed"> <source>Discard can be removed</source> <target state="translated">Odrzucenie można usunąć</target> <note /> </trans-unit> <trans-unit id="Embedded_statements_must_be_on_their_own_line"> <source>Embedded statements must be on their own line</source> <target state="translated">Osadzone instrukcje muszą znajdować się w osobnym wierszu</target> <note /> </trans-unit> <trans-unit id="Indexing_can_be_simplified"> <source>Indexing can be simplified</source> <target state="translated">Indeksowanie można uprościć</target> <note /> </trans-unit> <trans-unit id="Inline_variable_declaration"> <source>Inline variable declaration</source> <target state="translated">Deklaracja zmiennej wbudowanej</target> <note /> </trans-unit> <trans-unit id="Misplaced_using_directive"> <source>Misplaced using directive</source> <target state="translated">Nieprawidłowo umieszczona dyrektywa using</target> <note>{Locked="using"} "using" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="Move_misplaced_using_directives"> <source>Move misplaced using directives</source> <target state="translated">Przenieś nieprawidłowo umieszczone dyrektywy using</target> <note>{Locked="using"} "using" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="Make_readonly_fields_writable"> <source>Make readonly fields writable</source> <target state="translated">Ustaw możliwość zapisu dla pól z deklaracją readonly</target> <note>{Locked="readonly"} "readonly" is C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="Local_function_can_be_made_static"> <source>Local function can be made static</source> <target state="translated">Funkcję lokalną można ustawić jako statyczną</target> <note /> </trans-unit> <trans-unit id="Make_local_function_static"> <source>Make local function 'static'</source> <target state="translated">Ustaw funkcję lokalną jako „static”</target> <note /> </trans-unit> <trans-unit id="Negate_expression_changes_semantics"> <source>Negate expression (changes semantics)</source> <target state="translated">Neguj wyrażenie (zmienia semantykę)</target> <note /> </trans-unit> <trans-unit id="Null_check_can_be_clarified"> <source>Null check can be clarified</source> <target state="new">Null check can be clarified</target> <note /> </trans-unit> <trans-unit id="Prefer_null_check_over_type_check"> <source>Prefer 'null' check over type check</source> <target state="new">Prefer 'null' check over type check</target> <note /> </trans-unit> <trans-unit id="Remove_operator_preserves_semantics"> <source>Remove operator (preserves semantics)</source> <target state="translated">Usuń operator (zachowuje semantykę)</target> <note /> </trans-unit> <trans-unit id="Remove_suppression_operators"> <source>Remove suppression operators</source> <target state="translated">Usuń operatory pomijania</target> <note /> </trans-unit> <trans-unit id="Remove_unnecessary_suppression_operator"> <source>Remove unnecessary suppression operator</source> <target state="translated">Usuń niepotrzebny operator pomijania</target> <note /> </trans-unit> <trans-unit id="Remove_unnessary_discard"> <source>Remove unnecessary discard</source> <target state="translated">Usuń niepotrzebne odrzucenie</target> <note /> </trans-unit> <trans-unit id="Simplify_default_expression"> <source>Simplify 'default' expression</source> <target state="translated">Uprość wyrażenie „default”</target> <note /> </trans-unit> <trans-unit id="Struct_contains_assignment_to_this_outside_of_constructor_Make_readonly_fields_writable"> <source>Struct contains assignment to 'this' outside of constructor. Make readonly fields writable.</source> <target state="translated">Element Struct zawiera przypisanie do elementu „this” poza konstruktorem. Ustaw pola tylko do odczytu jako zapisywalne.</target> <note>{Locked="Struct"}{Locked="this"} these are C#/VB keywords and should not be localized.</note> </trans-unit> <trans-unit id="Suppression_operator_has_no_effect_and_can_be_misinterpreted"> <source>Suppression operator has no effect and can be misinterpreted</source> <target state="translated">Operator pomijania nie ma żadnego efektu i może zostać błędnie zinterpretowany</target> <note /> </trans-unit> <trans-unit id="Unreachable_code_detected"> <source>Unreachable code detected</source> <target state="translated">Wykryto nieosiągalny kod</target> <note /> </trans-unit> <trans-unit id="Use_block_body_for_accessors"> <source>Use block body for accessors</source> <target state="translated">Użyj treści bloku dla metod dostępu</target> <note /> </trans-unit> <trans-unit id="Use_block_body_for_constructors"> <source>Use block body for constructors</source> <target state="translated">Użyj treści bloku dla konstruktorów</target> <note /> </trans-unit> <trans-unit id="Use_block_body_for_indexers"> <source>Use block body for indexers</source> <target state="translated">Użyj treści bloku dla indeksatorów</target> <note /> </trans-unit> <trans-unit id="Use_block_body_for_local_functions"> <source>Use block body for local functions</source> <target state="translated">Użyj treści bloku dla funkcji lokalnych</target> <note /> </trans-unit> <trans-unit id="Use_block_body_for_methods"> <source>Use block body for methods</source> <target state="translated">Użyj treści bloku dla metod</target> <note /> </trans-unit> <trans-unit id="Use_block_body_for_operators"> <source>Use block body for operators</source> <target state="translated">Użyj treści bloku dla operatorów</target> <note /> </trans-unit> <trans-unit id="Use_block_body_for_properties"> <source>Use block body for properties</source> <target state="translated">Użyj treści bloku dla właściwości</target> <note /> </trans-unit> <trans-unit id="Use_explicit_type"> <source>Use explicit type</source> <target state="translated">Użyj jawnego typu</target> <note /> </trans-unit> <trans-unit id="Use_explicit_type_instead_of_var"> <source>Use explicit type instead of 'var'</source> <target state="translated">Użyj jawnego typu zamiast deklaracji „var”</target> <note /> </trans-unit> <trans-unit id="Use_expression_body_for_accessors"> <source>Use expression body for accessors</source> <target state="translated">Użyj treści wyrażenia dla metod dostępu</target> <note /> </trans-unit> <trans-unit id="Use_expression_body_for_constructors"> <source>Use expression body for constructors</source> <target state="translated">Użyj treści wyrażenia dla konstruktorów</target> <note /> </trans-unit> <trans-unit id="Use_expression_body_for_indexers"> <source>Use expression body for indexers</source> <target state="translated">Użyj treści wyrażenia dla indeksatorów</target> <note /> </trans-unit> <trans-unit id="Use_expression_body_for_local_functions"> <source>Use expression body for local functions</source> <target state="translated">Użyj treści wyrażenia dla funkcji lokalnych</target> <note /> </trans-unit> <trans-unit id="Use_expression_body_for_methods"> <source>Use expression body for methods</source> <target state="translated">Użyj treści wyrażenia dla metod</target> <note /> </trans-unit> <trans-unit id="Use_expression_body_for_operators"> <source>Use expression body for operators</source> <target state="translated">Użyj treści wyrażenia dla operatorów</target> <note /> </trans-unit> <trans-unit id="Use_expression_body_for_properties"> <source>Use expression body for properties</source> <target state="translated">Użyj treści wyrażenia dla właściwości</target> <note /> </trans-unit> <trans-unit id="Use_implicit_type"> <source>Use implicit type</source> <target state="translated">Użyj niejawnego typu</target> <note /> </trans-unit> <trans-unit id="Use_index_operator"> <source>Use index operator</source> <target state="translated">Użyj operatora indeksu</target> <note /> </trans-unit> <trans-unit id="Use_is_null_check"> <source>Use 'is null' check</source> <target state="translated">Użyj sprawdzania „is null”</target> <note /> </trans-unit> <trans-unit id="Use_local_function"> <source>Use local function</source> <target state="translated">Użyj funkcji lokalnej</target> <note /> </trans-unit> <trans-unit id="Use_new"> <source>Use 'new(...)'</source> <target state="translated">Użyj operatora „new(...)”</target> <note>{Locked="new(...)"} This is a C# construct and should not be localized.</note> </trans-unit> <trans-unit id="Use_pattern_matching"> <source>Use pattern matching</source> <target state="translated">Użyj dopasowywania wzorców</target> <note /> </trans-unit> <trans-unit id="Use_range_operator"> <source>Use range operator</source> <target state="translated">Użyj operatora zakresu</target> <note /> </trans-unit> <trans-unit id="Use_simple_using_statement"> <source>Use simple 'using' statement</source> <target state="translated">Użyj prostej instrukcji „using”</target> <note /> </trans-unit> <trans-unit id="Use_switch_expression"> <source>Use 'switch' expression</source> <target state="translated">Użyj wyrażenia „switch”</target> <note /> </trans-unit> <trans-unit id="Using_directives_must_be_placed_inside_of_a_namespace_declaration"> <source>Using directives must be placed inside of a namespace declaration</source> <target state="translated">Dyrektywy using muszą znajdować się wewnątrz deklaracji namespace</target> <note>{Locked="using"} "using" is a C# keyword and should not be localized. {Locked="namespace"} "namespace" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="Using_directives_must_be_placed_outside_of_a_namespace_declaration"> <source>Using directives must be placed outside of a namespace declaration</source> <target state="translated">Dyrektywy using muszą znajdować się poza deklaracją namespace</target> <note>{Locked="using"} "using" is a C# keyword and should not be localized. {Locked="namespace"} "namespace" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="Variable_declaration_can_be_deconstructed"> <source>Variable declaration can be deconstructed</source> <target state="translated">Deklaracja zmiennej może zostać zdekonstruowana</target> <note /> </trans-unit> <trans-unit id="Variable_declaration_can_be_inlined"> <source>Variable declaration can be inlined</source> <target state="translated">Deklaracja zmiennej może być śródwierszowa</target> <note /> </trans-unit> <trans-unit id="Warning_colon_Moving_using_directives_may_change_code_meaning"> <source>Warning: Moving using directives may change code meaning.</source> <target state="translated">Uwaga: przeniesienie dyrektyw using może zmienić znaczenie kodu.</target> <note>{Locked="using"} "using" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="_0_can_be_simplified"> <source>{0} can be simplified</source> <target state="translated">Element {0} można uprościć</target> <note /> </trans-unit> <trans-unit id="default_expression_can_be_simplified"> <source>'default' expression can be simplified</source> <target state="translated">Wyrażenie „default” można uprościć</target> <note /> </trans-unit> <trans-unit id="if_statement_can_be_simplified"> <source>'if' statement can be simplified</source> <target state="translated">Instrukcja „if” może zostać uproszczona</target> <note /> </trans-unit> <trans-unit id="new_expression_can_be_simplified"> <source>'new' expression can be simplified</source> <target state="translated">Wyrażenie „new” można uprościć</target> <note /> </trans-unit> <trans-unit id="typeof_can_be_converted_ to_nameof"> <source>'typeof' can be converted to 'nameof'</source> <target state="translated">Element „typeof” można przekonwertować na element „nameof”</target> <note /> </trans-unit> <trans-unit id="use_var_instead_of_explicit_type"> <source>use 'var' instead of explicit type</source> <target state="translated">użyj deklaracji „var” zamiast jawnego typu</target> <note /> </trans-unit> <trans-unit id="Using_directive_is_unnecessary"> <source>Using directive is unnecessary.</source> <target state="translated">Dyrektywa using jest niepotrzebna.</target> <note /> </trans-unit> <trans-unit id="using_statement_can_be_simplified"> <source>'using' statement can be simplified</source> <target state="translated">Instrukcję „using” można uprościć</target> <note /> </trans-unit> </body> </file> </xliff>
<?xml version="1.0" encoding="utf-8"?> <xliff xmlns="urn:oasis:names:tc:xliff:document:1.2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="1.2" xsi:schemaLocation="urn:oasis:names:tc:xliff:document:1.2 xliff-core-1.2-transitional.xsd"> <file datatype="xml" source-language="en" target-language="pl" original="../CSharpAnalyzersResources.resx"> <body> <trans-unit id="Add_braces"> <source>Add braces</source> <target state="translated">Dodaj nawiasy klamrowe</target> <note /> </trans-unit> <trans-unit id="Add_braces_to_0_statement"> <source>Add braces to '{0}' statement.</source> <target state="translated">Dodaj nawiasy klamrowe do instrukcji „{0}”.</target> <note /> </trans-unit> <trans-unit id="Blank_line_not_allowed_after_constructor_initializer_colon"> <source>Blank line not allowed after constructor initializer colon</source> <target state="translated">Pusty wiersz jest niedozwolony po dwukropku inicjatora konstruktora</target> <note /> </trans-unit> <trans-unit id="Consecutive_braces_must_not_have_a_blank_between_them"> <source>Consecutive braces must not have blank line between them</source> <target state="translated">Między kolejnymi nawiasami klamrowymi nie może znajdować się pusty wiersz.</target> <note /> </trans-unit> <trans-unit id="Convert_switch_statement_to_expression"> <source>Convert switch statement to expression</source> <target state="translated">Konwertuj instrukcję switch na wyrażenie</target> <note /> </trans-unit> <trans-unit id="Convert_to_block_scoped_namespace"> <source>Convert to block scoped namespace</source> <target state="new">Convert to block scoped namespace</target> <note>{Locked="namespace"} "namespace" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="Convert_to_file_scoped_namespace"> <source>Convert to file-scoped namespace</source> <target state="new">Convert to file-scoped namespace</target> <note>{Locked="namespace"} "namespace" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="Deconstruct_variable_declaration"> <source>Deconstruct variable declaration</source> <target state="translated">Zdekonstruuj deklarację zmiennej</target> <note /> </trans-unit> <trans-unit id="Delegate_invocation_can_be_simplified"> <source>Delegate invocation can be simplified.</source> <target state="translated">Wywołanie delegata można uprościć.</target> <note /> </trans-unit> <trans-unit id="Discard_can_be_removed"> <source>Discard can be removed</source> <target state="translated">Odrzucenie można usunąć</target> <note /> </trans-unit> <trans-unit id="Embedded_statements_must_be_on_their_own_line"> <source>Embedded statements must be on their own line</source> <target state="translated">Osadzone instrukcje muszą znajdować się w osobnym wierszu</target> <note /> </trans-unit> <trans-unit id="Indexing_can_be_simplified"> <source>Indexing can be simplified</source> <target state="translated">Indeksowanie można uprościć</target> <note /> </trans-unit> <trans-unit id="Inline_variable_declaration"> <source>Inline variable declaration</source> <target state="translated">Deklaracja zmiennej wbudowanej</target> <note /> </trans-unit> <trans-unit id="Misplaced_using_directive"> <source>Misplaced using directive</source> <target state="translated">Nieprawidłowo umieszczona dyrektywa using</target> <note>{Locked="using"} "using" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="Move_misplaced_using_directives"> <source>Move misplaced using directives</source> <target state="translated">Przenieś nieprawidłowo umieszczone dyrektywy using</target> <note>{Locked="using"} "using" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="Make_readonly_fields_writable"> <source>Make readonly fields writable</source> <target state="translated">Ustaw możliwość zapisu dla pól z deklaracją readonly</target> <note>{Locked="readonly"} "readonly" is C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="Local_function_can_be_made_static"> <source>Local function can be made static</source> <target state="translated">Funkcję lokalną można ustawić jako statyczną</target> <note /> </trans-unit> <trans-unit id="Make_local_function_static"> <source>Make local function 'static'</source> <target state="translated">Ustaw funkcję lokalną jako „static”</target> <note /> </trans-unit> <trans-unit id="Negate_expression_changes_semantics"> <source>Negate expression (changes semantics)</source> <target state="translated">Neguj wyrażenie (zmienia semantykę)</target> <note /> </trans-unit> <trans-unit id="Null_check_can_be_clarified"> <source>Null check can be clarified</source> <target state="new">Null check can be clarified</target> <note /> </trans-unit> <trans-unit id="Prefer_null_check_over_type_check"> <source>Prefer 'null' check over type check</source> <target state="new">Prefer 'null' check over type check</target> <note /> </trans-unit> <trans-unit id="Remove_operator_preserves_semantics"> <source>Remove operator (preserves semantics)</source> <target state="translated">Usuń operator (zachowuje semantykę)</target> <note /> </trans-unit> <trans-unit id="Remove_suppression_operators"> <source>Remove suppression operators</source> <target state="translated">Usuń operatory pomijania</target> <note /> </trans-unit> <trans-unit id="Remove_unnecessary_suppression_operator"> <source>Remove unnecessary suppression operator</source> <target state="translated">Usuń niepotrzebny operator pomijania</target> <note /> </trans-unit> <trans-unit id="Remove_unnessary_discard"> <source>Remove unnecessary discard</source> <target state="translated">Usuń niepotrzebne odrzucenie</target> <note /> </trans-unit> <trans-unit id="Simplify_default_expression"> <source>Simplify 'default' expression</source> <target state="translated">Uprość wyrażenie „default”</target> <note /> </trans-unit> <trans-unit id="Struct_contains_assignment_to_this_outside_of_constructor_Make_readonly_fields_writable"> <source>Struct contains assignment to 'this' outside of constructor. Make readonly fields writable.</source> <target state="translated">Element Struct zawiera przypisanie do elementu „this” poza konstruktorem. Ustaw pola tylko do odczytu jako zapisywalne.</target> <note>{Locked="Struct"}{Locked="this"} these are C#/VB keywords and should not be localized.</note> </trans-unit> <trans-unit id="Suppression_operator_has_no_effect_and_can_be_misinterpreted"> <source>Suppression operator has no effect and can be misinterpreted</source> <target state="translated">Operator pomijania nie ma żadnego efektu i może zostać błędnie zinterpretowany</target> <note /> </trans-unit> <trans-unit id="Unreachable_code_detected"> <source>Unreachable code detected</source> <target state="translated">Wykryto nieosiągalny kod</target> <note /> </trans-unit> <trans-unit id="Use_block_body_for_accessors"> <source>Use block body for accessors</source> <target state="translated">Użyj treści bloku dla metod dostępu</target> <note /> </trans-unit> <trans-unit id="Use_block_body_for_constructors"> <source>Use block body for constructors</source> <target state="translated">Użyj treści bloku dla konstruktorów</target> <note /> </trans-unit> <trans-unit id="Use_block_body_for_indexers"> <source>Use block body for indexers</source> <target state="translated">Użyj treści bloku dla indeksatorów</target> <note /> </trans-unit> <trans-unit id="Use_block_body_for_local_functions"> <source>Use block body for local functions</source> <target state="translated">Użyj treści bloku dla funkcji lokalnych</target> <note /> </trans-unit> <trans-unit id="Use_block_body_for_methods"> <source>Use block body for methods</source> <target state="translated">Użyj treści bloku dla metod</target> <note /> </trans-unit> <trans-unit id="Use_block_body_for_operators"> <source>Use block body for operators</source> <target state="translated">Użyj treści bloku dla operatorów</target> <note /> </trans-unit> <trans-unit id="Use_block_body_for_properties"> <source>Use block body for properties</source> <target state="translated">Użyj treści bloku dla właściwości</target> <note /> </trans-unit> <trans-unit id="Use_explicit_type"> <source>Use explicit type</source> <target state="translated">Użyj jawnego typu</target> <note /> </trans-unit> <trans-unit id="Use_explicit_type_instead_of_var"> <source>Use explicit type instead of 'var'</source> <target state="translated">Użyj jawnego typu zamiast deklaracji „var”</target> <note /> </trans-unit> <trans-unit id="Use_expression_body_for_accessors"> <source>Use expression body for accessors</source> <target state="translated">Użyj treści wyrażenia dla metod dostępu</target> <note /> </trans-unit> <trans-unit id="Use_expression_body_for_constructors"> <source>Use expression body for constructors</source> <target state="translated">Użyj treści wyrażenia dla konstruktorów</target> <note /> </trans-unit> <trans-unit id="Use_expression_body_for_indexers"> <source>Use expression body for indexers</source> <target state="translated">Użyj treści wyrażenia dla indeksatorów</target> <note /> </trans-unit> <trans-unit id="Use_expression_body_for_local_functions"> <source>Use expression body for local functions</source> <target state="translated">Użyj treści wyrażenia dla funkcji lokalnych</target> <note /> </trans-unit> <trans-unit id="Use_expression_body_for_methods"> <source>Use expression body for methods</source> <target state="translated">Użyj treści wyrażenia dla metod</target> <note /> </trans-unit> <trans-unit id="Use_expression_body_for_operators"> <source>Use expression body for operators</source> <target state="translated">Użyj treści wyrażenia dla operatorów</target> <note /> </trans-unit> <trans-unit id="Use_expression_body_for_properties"> <source>Use expression body for properties</source> <target state="translated">Użyj treści wyrażenia dla właściwości</target> <note /> </trans-unit> <trans-unit id="Use_implicit_type"> <source>Use implicit type</source> <target state="translated">Użyj niejawnego typu</target> <note /> </trans-unit> <trans-unit id="Use_index_operator"> <source>Use index operator</source> <target state="translated">Użyj operatora indeksu</target> <note /> </trans-unit> <trans-unit id="Use_is_null_check"> <source>Use 'is null' check</source> <target state="translated">Użyj sprawdzania „is null”</target> <note /> </trans-unit> <trans-unit id="Use_local_function"> <source>Use local function</source> <target state="translated">Użyj funkcji lokalnej</target> <note /> </trans-unit> <trans-unit id="Use_new"> <source>Use 'new(...)'</source> <target state="translated">Użyj operatora „new(...)”</target> <note>{Locked="new(...)"} This is a C# construct and should not be localized.</note> </trans-unit> <trans-unit id="Use_pattern_matching"> <source>Use pattern matching</source> <target state="translated">Użyj dopasowywania wzorców</target> <note /> </trans-unit> <trans-unit id="Use_pattern_matching_may_change_code_meaning"> <source>Use pattern matching (may change code meaning)</source> <target state="new">Use pattern matching (may change code meaning)</target> <note /> </trans-unit> <trans-unit id="Use_range_operator"> <source>Use range operator</source> <target state="translated">Użyj operatora zakresu</target> <note /> </trans-unit> <trans-unit id="Use_simple_using_statement"> <source>Use simple 'using' statement</source> <target state="translated">Użyj prostej instrukcji „using”</target> <note /> </trans-unit> <trans-unit id="Use_switch_expression"> <source>Use 'switch' expression</source> <target state="translated">Użyj wyrażenia „switch”</target> <note /> </trans-unit> <trans-unit id="Using_directives_must_be_placed_inside_of_a_namespace_declaration"> <source>Using directives must be placed inside of a namespace declaration</source> <target state="translated">Dyrektywy using muszą znajdować się wewnątrz deklaracji namespace</target> <note>{Locked="using"} "using" is a C# keyword and should not be localized. {Locked="namespace"} "namespace" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="Using_directives_must_be_placed_outside_of_a_namespace_declaration"> <source>Using directives must be placed outside of a namespace declaration</source> <target state="translated">Dyrektywy using muszą znajdować się poza deklaracją namespace</target> <note>{Locked="using"} "using" is a C# keyword and should not be localized. {Locked="namespace"} "namespace" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="Variable_declaration_can_be_deconstructed"> <source>Variable declaration can be deconstructed</source> <target state="translated">Deklaracja zmiennej może zostać zdekonstruowana</target> <note /> </trans-unit> <trans-unit id="Variable_declaration_can_be_inlined"> <source>Variable declaration can be inlined</source> <target state="translated">Deklaracja zmiennej może być śródwierszowa</target> <note /> </trans-unit> <trans-unit id="Warning_colon_Moving_using_directives_may_change_code_meaning"> <source>Warning: Moving using directives may change code meaning.</source> <target state="translated">Uwaga: przeniesienie dyrektyw using może zmienić znaczenie kodu.</target> <note>{Locked="using"} "using" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="_0_can_be_simplified"> <source>{0} can be simplified</source> <target state="translated">Element {0} można uprościć</target> <note /> </trans-unit> <trans-unit id="default_expression_can_be_simplified"> <source>'default' expression can be simplified</source> <target state="translated">Wyrażenie „default” można uprościć</target> <note /> </trans-unit> <trans-unit id="if_statement_can_be_simplified"> <source>'if' statement can be simplified</source> <target state="translated">Instrukcja „if” może zostać uproszczona</target> <note /> </trans-unit> <trans-unit id="new_expression_can_be_simplified"> <source>'new' expression can be simplified</source> <target state="translated">Wyrażenie „new” można uprościć</target> <note /> </trans-unit> <trans-unit id="typeof_can_be_converted_ to_nameof"> <source>'typeof' can be converted to 'nameof'</source> <target state="translated">Element „typeof” można przekonwertować na element „nameof”</target> <note /> </trans-unit> <trans-unit id="use_var_instead_of_explicit_type"> <source>use 'var' instead of explicit type</source> <target state="translated">użyj deklaracji „var” zamiast jawnego typu</target> <note /> </trans-unit> <trans-unit id="Using_directive_is_unnecessary"> <source>Using directive is unnecessary.</source> <target state="translated">Dyrektywa using jest niepotrzebna.</target> <note /> </trans-unit> <trans-unit id="using_statement_can_be_simplified"> <source>'using' statement can be simplified</source> <target state="translated">Instrukcję „using” można uprościć</target> <note /> </trans-unit> </body> </file> </xliff>
1
dotnet/roslyn
55,427
Fixes #50462
Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
Blokyk
2021-08-05T01:17:37Z
2021-08-25T05:42:59Z
fefb8c2110625bc4908db4bbdaa367b12bfb1069
fb4ac545a1f1f365e7df570637699d9085ea4f87
Fixes #50462. Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
./src/Analyzers/CSharp/Analyzers/xlf/CSharpAnalyzersResources.pt-BR.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="pt-BR" original="../CSharpAnalyzersResources.resx"> <body> <trans-unit id="Add_braces"> <source>Add braces</source> <target state="translated">Adicionar chaves</target> <note /> </trans-unit> <trans-unit id="Add_braces_to_0_statement"> <source>Add braces to '{0}' statement.</source> <target state="translated">Adicionar chaves à instrução '{0}'.</target> <note /> </trans-unit> <trans-unit id="Blank_line_not_allowed_after_constructor_initializer_colon"> <source>Blank line not allowed after constructor initializer colon</source> <target state="translated">Linha em branco não permitida após os dois-pontos do inicializador de construtor</target> <note /> </trans-unit> <trans-unit id="Consecutive_braces_must_not_have_a_blank_between_them"> <source>Consecutive braces must not have blank line between them</source> <target state="translated">As chaves consecutivas não podem ter uma linha em branco entre elas</target> <note /> </trans-unit> <trans-unit id="Convert_switch_statement_to_expression"> <source>Convert switch statement to expression</source> <target state="translated">Converter a instrução switch em expressão</target> <note /> </trans-unit> <trans-unit id="Convert_to_block_scoped_namespace"> <source>Convert to block scoped namespace</source> <target state="new">Convert to block scoped namespace</target> <note>{Locked="namespace"} "namespace" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="Convert_to_file_scoped_namespace"> <source>Convert to file-scoped namespace</source> <target state="new">Convert to file-scoped namespace</target> <note>{Locked="namespace"} "namespace" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="Deconstruct_variable_declaration"> <source>Deconstruct variable declaration</source> <target state="translated">Desconstruir declaração de variável</target> <note /> </trans-unit> <trans-unit id="Delegate_invocation_can_be_simplified"> <source>Delegate invocation can be simplified.</source> <target state="translated">A invocação de delegado pode ser simplificada.</target> <note /> </trans-unit> <trans-unit id="Discard_can_be_removed"> <source>Discard can be removed</source> <target state="translated">O discard pode ser removido</target> <note /> </trans-unit> <trans-unit id="Embedded_statements_must_be_on_their_own_line"> <source>Embedded statements must be on their own line</source> <target state="translated">As instruções inseridas precisam estar nas próprias linhas</target> <note /> </trans-unit> <trans-unit id="Indexing_can_be_simplified"> <source>Indexing can be simplified</source> <target state="translated">A indexação pode ser simplificada</target> <note /> </trans-unit> <trans-unit id="Inline_variable_declaration"> <source>Inline variable declaration</source> <target state="translated">Declaração de variável embutida</target> <note /> </trans-unit> <trans-unit id="Misplaced_using_directive"> <source>Misplaced using directive</source> <target state="translated">Diretiva using em local incorreto</target> <note>{Locked="using"} "using" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="Move_misplaced_using_directives"> <source>Move misplaced using directives</source> <target state="translated">Mover diretivas using no local incorreto</target> <note>{Locked="using"} "using" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="Make_readonly_fields_writable"> <source>Make readonly fields writable</source> <target state="translated">Alterar os campos readonly para graváveis</target> <note>{Locked="readonly"} "readonly" is C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="Local_function_can_be_made_static"> <source>Local function can be made static</source> <target state="translated">A função local pode ser alterada para estática</target> <note /> </trans-unit> <trans-unit id="Make_local_function_static"> <source>Make local function 'static'</source> <target state="translated">Alterar a função local para 'static'</target> <note /> </trans-unit> <trans-unit id="Negate_expression_changes_semantics"> <source>Negate expression (changes semantics)</source> <target state="translated">Negar expressão (altera a semântica)</target> <note /> </trans-unit> <trans-unit id="Null_check_can_be_clarified"> <source>Null check can be clarified</source> <target state="new">Null check can be clarified</target> <note /> </trans-unit> <trans-unit id="Prefer_null_check_over_type_check"> <source>Prefer 'null' check over type check</source> <target state="new">Prefer 'null' check over type check</target> <note /> </trans-unit> <trans-unit id="Remove_operator_preserves_semantics"> <source>Remove operator (preserves semantics)</source> <target state="translated">Remover operador (preserva a semântica)</target> <note /> </trans-unit> <trans-unit id="Remove_suppression_operators"> <source>Remove suppression operators</source> <target state="translated">Remover operadores de supressão</target> <note /> </trans-unit> <trans-unit id="Remove_unnecessary_suppression_operator"> <source>Remove unnecessary suppression operator</source> <target state="translated">Remover operador de supressão desnecessário</target> <note /> </trans-unit> <trans-unit id="Remove_unnessary_discard"> <source>Remove unnecessary discard</source> <target state="translated">Remover o discard desnecessário</target> <note /> </trans-unit> <trans-unit id="Simplify_default_expression"> <source>Simplify 'default' expression</source> <target state="translated">Simplificar expressão 'default'</target> <note /> </trans-unit> <trans-unit id="Struct_contains_assignment_to_this_outside_of_constructor_Make_readonly_fields_writable"> <source>Struct contains assignment to 'this' outside of constructor. Make readonly fields writable.</source> <target state="translated">O Struct contém a atribuição para 'this' fora do construtor. Converta os campos somente leitura em graváveis.</target> <note>{Locked="Struct"}{Locked="this"} these are C#/VB keywords and should not be localized.</note> </trans-unit> <trans-unit id="Suppression_operator_has_no_effect_and_can_be_misinterpreted"> <source>Suppression operator has no effect and can be misinterpreted</source> <target state="translated">O operador de supressão não tem efeito e pode ser mal interpretado</target> <note /> </trans-unit> <trans-unit id="Unreachable_code_detected"> <source>Unreachable code detected</source> <target state="translated">Código inacessível detectado</target> <note /> </trans-unit> <trans-unit id="Use_block_body_for_accessors"> <source>Use block body for accessors</source> <target state="translated">Usar o corpo do bloco para acessadores</target> <note /> </trans-unit> <trans-unit id="Use_block_body_for_constructors"> <source>Use block body for constructors</source> <target state="translated">Usar o corpo do bloco para construtores</target> <note /> </trans-unit> <trans-unit id="Use_block_body_for_indexers"> <source>Use block body for indexers</source> <target state="translated">Usar o corpo do bloco para indexadores</target> <note /> </trans-unit> <trans-unit id="Use_block_body_for_local_functions"> <source>Use block body for local functions</source> <target state="translated">Usar o corpo do bloco para funções locais</target> <note /> </trans-unit> <trans-unit id="Use_block_body_for_methods"> <source>Use block body for methods</source> <target state="translated">Usar o corpo do bloco para métodos</target> <note /> </trans-unit> <trans-unit id="Use_block_body_for_operators"> <source>Use block body for operators</source> <target state="translated">Usar o corpo do bloco para operadores</target> <note /> </trans-unit> <trans-unit id="Use_block_body_for_properties"> <source>Use block body for properties</source> <target state="translated">Usar o corpo do bloco para propriedades</target> <note /> </trans-unit> <trans-unit id="Use_explicit_type"> <source>Use explicit type</source> <target state="translated">Usar o tipo explícito</target> <note /> </trans-unit> <trans-unit id="Use_explicit_type_instead_of_var"> <source>Use explicit type instead of 'var'</source> <target state="translated">Usar o tipo explícito em vez de 'var'</target> <note /> </trans-unit> <trans-unit id="Use_expression_body_for_accessors"> <source>Use expression body for accessors</source> <target state="translated">Usar o corpo da expressão para acessadores</target> <note /> </trans-unit> <trans-unit id="Use_expression_body_for_constructors"> <source>Use expression body for constructors</source> <target state="translated">Usar o corpo da expressão para construtores</target> <note /> </trans-unit> <trans-unit id="Use_expression_body_for_indexers"> <source>Use expression body for indexers</source> <target state="translated">Usar o corpo da expressão para indexadores</target> <note /> </trans-unit> <trans-unit id="Use_expression_body_for_local_functions"> <source>Use expression body for local functions</source> <target state="translated">Usar o corpo da expressão para funções locais</target> <note /> </trans-unit> <trans-unit id="Use_expression_body_for_methods"> <source>Use expression body for methods</source> <target state="translated">Usar o corpo da expressão para métodos</target> <note /> </trans-unit> <trans-unit id="Use_expression_body_for_operators"> <source>Use expression body for operators</source> <target state="translated">Usar o corpo da expressão para operadores</target> <note /> </trans-unit> <trans-unit id="Use_expression_body_for_properties"> <source>Use expression body for properties</source> <target state="translated">Usar o corpo da expressão para propriedades</target> <note /> </trans-unit> <trans-unit id="Use_implicit_type"> <source>Use implicit type</source> <target state="translated">Usar o tipo implícito</target> <note /> </trans-unit> <trans-unit id="Use_index_operator"> <source>Use index operator</source> <target state="translated">Usar operador de índice</target> <note /> </trans-unit> <trans-unit id="Use_is_null_check"> <source>Use 'is null' check</source> <target state="translated">Usar verificação 'is null'</target> <note /> </trans-unit> <trans-unit id="Use_local_function"> <source>Use local function</source> <target state="translated">Usar função local</target> <note /> </trans-unit> <trans-unit id="Use_new"> <source>Use 'new(...)'</source> <target state="translated">Usar 'new(...)'</target> <note>{Locked="new(...)"} This is a C# construct and should not be localized.</note> </trans-unit> <trans-unit id="Use_pattern_matching"> <source>Use pattern matching</source> <target state="translated">Usar a correspondência de padrão</target> <note /> </trans-unit> <trans-unit id="Use_range_operator"> <source>Use range operator</source> <target state="translated">Usar operador de intervalo</target> <note /> </trans-unit> <trans-unit id="Use_simple_using_statement"> <source>Use simple 'using' statement</source> <target state="translated">Usar a instrução 'using' simples</target> <note /> </trans-unit> <trans-unit id="Use_switch_expression"> <source>Use 'switch' expression</source> <target state="translated">Usar a expressão 'switch'</target> <note /> </trans-unit> <trans-unit id="Using_directives_must_be_placed_inside_of_a_namespace_declaration"> <source>Using directives must be placed inside of a namespace declaration</source> <target state="translated">As diretivas using precisam ser colocadas dentro de uma declaração de namespace</target> <note>{Locked="using"} "using" is a C# keyword and should not be localized. {Locked="namespace"} "namespace" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="Using_directives_must_be_placed_outside_of_a_namespace_declaration"> <source>Using directives must be placed outside of a namespace declaration</source> <target state="translated">As diretivas using precisam ser colocadas fora de uma declaração de namespace</target> <note>{Locked="using"} "using" is a C# keyword and should not be localized. {Locked="namespace"} "namespace" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="Variable_declaration_can_be_deconstructed"> <source>Variable declaration can be deconstructed</source> <target state="translated">A declaração de variável pode ser desconstruída</target> <note /> </trans-unit> <trans-unit id="Variable_declaration_can_be_inlined"> <source>Variable declaration can be inlined</source> <target state="translated">A declaração de variável pode ser embutida</target> <note /> </trans-unit> <trans-unit id="Warning_colon_Moving_using_directives_may_change_code_meaning"> <source>Warning: Moving using directives may change code meaning.</source> <target state="translated">Aviso: a movimentação das diretivas using pode alterar o significado do código.</target> <note>{Locked="using"} "using" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="_0_can_be_simplified"> <source>{0} can be simplified</source> <target state="translated">{0} pode ser simplificado</target> <note /> </trans-unit> <trans-unit id="default_expression_can_be_simplified"> <source>'default' expression can be simplified</source> <target state="translated">'a expressão 'default' pode ser simplificada</target> <note /> </trans-unit> <trans-unit id="if_statement_can_be_simplified"> <source>'if' statement can be simplified</source> <target state="translated">A instrução 'if' pode ser simplificada</target> <note /> </trans-unit> <trans-unit id="new_expression_can_be_simplified"> <source>'new' expression can be simplified</source> <target state="translated">A expressão 'new' pode ser simplificada</target> <note /> </trans-unit> <trans-unit id="typeof_can_be_converted_ to_nameof"> <source>'typeof' can be converted to 'nameof'</source> <target state="translated">'typeof' pode ser convertido em 'nameof'</target> <note /> </trans-unit> <trans-unit id="use_var_instead_of_explicit_type"> <source>use 'var' instead of explicit type</source> <target state="translated">usar 'var' em vez do tipo explícito</target> <note /> </trans-unit> <trans-unit id="Using_directive_is_unnecessary"> <source>Using directive is unnecessary.</source> <target state="translated">O uso da diretiva é desnecessário.</target> <note /> </trans-unit> <trans-unit id="using_statement_can_be_simplified"> <source>'using' statement can be simplified</source> <target state="translated">A instrução 'using' pode ser simplificada</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="pt-BR" original="../CSharpAnalyzersResources.resx"> <body> <trans-unit id="Add_braces"> <source>Add braces</source> <target state="translated">Adicionar chaves</target> <note /> </trans-unit> <trans-unit id="Add_braces_to_0_statement"> <source>Add braces to '{0}' statement.</source> <target state="translated">Adicionar chaves à instrução '{0}'.</target> <note /> </trans-unit> <trans-unit id="Blank_line_not_allowed_after_constructor_initializer_colon"> <source>Blank line not allowed after constructor initializer colon</source> <target state="translated">Linha em branco não permitida após os dois-pontos do inicializador de construtor</target> <note /> </trans-unit> <trans-unit id="Consecutive_braces_must_not_have_a_blank_between_them"> <source>Consecutive braces must not have blank line between them</source> <target state="translated">As chaves consecutivas não podem ter uma linha em branco entre elas</target> <note /> </trans-unit> <trans-unit id="Convert_switch_statement_to_expression"> <source>Convert switch statement to expression</source> <target state="translated">Converter a instrução switch em expressão</target> <note /> </trans-unit> <trans-unit id="Convert_to_block_scoped_namespace"> <source>Convert to block scoped namespace</source> <target state="new">Convert to block scoped namespace</target> <note>{Locked="namespace"} "namespace" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="Convert_to_file_scoped_namespace"> <source>Convert to file-scoped namespace</source> <target state="new">Convert to file-scoped namespace</target> <note>{Locked="namespace"} "namespace" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="Deconstruct_variable_declaration"> <source>Deconstruct variable declaration</source> <target state="translated">Desconstruir declaração de variável</target> <note /> </trans-unit> <trans-unit id="Delegate_invocation_can_be_simplified"> <source>Delegate invocation can be simplified.</source> <target state="translated">A invocação de delegado pode ser simplificada.</target> <note /> </trans-unit> <trans-unit id="Discard_can_be_removed"> <source>Discard can be removed</source> <target state="translated">O discard pode ser removido</target> <note /> </trans-unit> <trans-unit id="Embedded_statements_must_be_on_their_own_line"> <source>Embedded statements must be on their own line</source> <target state="translated">As instruções inseridas precisam estar nas próprias linhas</target> <note /> </trans-unit> <trans-unit id="Indexing_can_be_simplified"> <source>Indexing can be simplified</source> <target state="translated">A indexação pode ser simplificada</target> <note /> </trans-unit> <trans-unit id="Inline_variable_declaration"> <source>Inline variable declaration</source> <target state="translated">Declaração de variável embutida</target> <note /> </trans-unit> <trans-unit id="Misplaced_using_directive"> <source>Misplaced using directive</source> <target state="translated">Diretiva using em local incorreto</target> <note>{Locked="using"} "using" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="Move_misplaced_using_directives"> <source>Move misplaced using directives</source> <target state="translated">Mover diretivas using no local incorreto</target> <note>{Locked="using"} "using" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="Make_readonly_fields_writable"> <source>Make readonly fields writable</source> <target state="translated">Alterar os campos readonly para graváveis</target> <note>{Locked="readonly"} "readonly" is C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="Local_function_can_be_made_static"> <source>Local function can be made static</source> <target state="translated">A função local pode ser alterada para estática</target> <note /> </trans-unit> <trans-unit id="Make_local_function_static"> <source>Make local function 'static'</source> <target state="translated">Alterar a função local para 'static'</target> <note /> </trans-unit> <trans-unit id="Negate_expression_changes_semantics"> <source>Negate expression (changes semantics)</source> <target state="translated">Negar expressão (altera a semântica)</target> <note /> </trans-unit> <trans-unit id="Null_check_can_be_clarified"> <source>Null check can be clarified</source> <target state="new">Null check can be clarified</target> <note /> </trans-unit> <trans-unit id="Prefer_null_check_over_type_check"> <source>Prefer 'null' check over type check</source> <target state="new">Prefer 'null' check over type check</target> <note /> </trans-unit> <trans-unit id="Remove_operator_preserves_semantics"> <source>Remove operator (preserves semantics)</source> <target state="translated">Remover operador (preserva a semântica)</target> <note /> </trans-unit> <trans-unit id="Remove_suppression_operators"> <source>Remove suppression operators</source> <target state="translated">Remover operadores de supressão</target> <note /> </trans-unit> <trans-unit id="Remove_unnecessary_suppression_operator"> <source>Remove unnecessary suppression operator</source> <target state="translated">Remover operador de supressão desnecessário</target> <note /> </trans-unit> <trans-unit id="Remove_unnessary_discard"> <source>Remove unnecessary discard</source> <target state="translated">Remover o discard desnecessário</target> <note /> </trans-unit> <trans-unit id="Simplify_default_expression"> <source>Simplify 'default' expression</source> <target state="translated">Simplificar expressão 'default'</target> <note /> </trans-unit> <trans-unit id="Struct_contains_assignment_to_this_outside_of_constructor_Make_readonly_fields_writable"> <source>Struct contains assignment to 'this' outside of constructor. Make readonly fields writable.</source> <target state="translated">O Struct contém a atribuição para 'this' fora do construtor. Converta os campos somente leitura em graváveis.</target> <note>{Locked="Struct"}{Locked="this"} these are C#/VB keywords and should not be localized.</note> </trans-unit> <trans-unit id="Suppression_operator_has_no_effect_and_can_be_misinterpreted"> <source>Suppression operator has no effect and can be misinterpreted</source> <target state="translated">O operador de supressão não tem efeito e pode ser mal interpretado</target> <note /> </trans-unit> <trans-unit id="Unreachable_code_detected"> <source>Unreachable code detected</source> <target state="translated">Código inacessível detectado</target> <note /> </trans-unit> <trans-unit id="Use_block_body_for_accessors"> <source>Use block body for accessors</source> <target state="translated">Usar o corpo do bloco para acessadores</target> <note /> </trans-unit> <trans-unit id="Use_block_body_for_constructors"> <source>Use block body for constructors</source> <target state="translated">Usar o corpo do bloco para construtores</target> <note /> </trans-unit> <trans-unit id="Use_block_body_for_indexers"> <source>Use block body for indexers</source> <target state="translated">Usar o corpo do bloco para indexadores</target> <note /> </trans-unit> <trans-unit id="Use_block_body_for_local_functions"> <source>Use block body for local functions</source> <target state="translated">Usar o corpo do bloco para funções locais</target> <note /> </trans-unit> <trans-unit id="Use_block_body_for_methods"> <source>Use block body for methods</source> <target state="translated">Usar o corpo do bloco para métodos</target> <note /> </trans-unit> <trans-unit id="Use_block_body_for_operators"> <source>Use block body for operators</source> <target state="translated">Usar o corpo do bloco para operadores</target> <note /> </trans-unit> <trans-unit id="Use_block_body_for_properties"> <source>Use block body for properties</source> <target state="translated">Usar o corpo do bloco para propriedades</target> <note /> </trans-unit> <trans-unit id="Use_explicit_type"> <source>Use explicit type</source> <target state="translated">Usar o tipo explícito</target> <note /> </trans-unit> <trans-unit id="Use_explicit_type_instead_of_var"> <source>Use explicit type instead of 'var'</source> <target state="translated">Usar o tipo explícito em vez de 'var'</target> <note /> </trans-unit> <trans-unit id="Use_expression_body_for_accessors"> <source>Use expression body for accessors</source> <target state="translated">Usar o corpo da expressão para acessadores</target> <note /> </trans-unit> <trans-unit id="Use_expression_body_for_constructors"> <source>Use expression body for constructors</source> <target state="translated">Usar o corpo da expressão para construtores</target> <note /> </trans-unit> <trans-unit id="Use_expression_body_for_indexers"> <source>Use expression body for indexers</source> <target state="translated">Usar o corpo da expressão para indexadores</target> <note /> </trans-unit> <trans-unit id="Use_expression_body_for_local_functions"> <source>Use expression body for local functions</source> <target state="translated">Usar o corpo da expressão para funções locais</target> <note /> </trans-unit> <trans-unit id="Use_expression_body_for_methods"> <source>Use expression body for methods</source> <target state="translated">Usar o corpo da expressão para métodos</target> <note /> </trans-unit> <trans-unit id="Use_expression_body_for_operators"> <source>Use expression body for operators</source> <target state="translated">Usar o corpo da expressão para operadores</target> <note /> </trans-unit> <trans-unit id="Use_expression_body_for_properties"> <source>Use expression body for properties</source> <target state="translated">Usar o corpo da expressão para propriedades</target> <note /> </trans-unit> <trans-unit id="Use_implicit_type"> <source>Use implicit type</source> <target state="translated">Usar o tipo implícito</target> <note /> </trans-unit> <trans-unit id="Use_index_operator"> <source>Use index operator</source> <target state="translated">Usar operador de índice</target> <note /> </trans-unit> <trans-unit id="Use_is_null_check"> <source>Use 'is null' check</source> <target state="translated">Usar verificação 'is null'</target> <note /> </trans-unit> <trans-unit id="Use_local_function"> <source>Use local function</source> <target state="translated">Usar função local</target> <note /> </trans-unit> <trans-unit id="Use_new"> <source>Use 'new(...)'</source> <target state="translated">Usar 'new(...)'</target> <note>{Locked="new(...)"} This is a C# construct and should not be localized.</note> </trans-unit> <trans-unit id="Use_pattern_matching"> <source>Use pattern matching</source> <target state="translated">Usar a correspondência de padrão</target> <note /> </trans-unit> <trans-unit id="Use_pattern_matching_may_change_code_meaning"> <source>Use pattern matching (may change code meaning)</source> <target state="new">Use pattern matching (may change code meaning)</target> <note /> </trans-unit> <trans-unit id="Use_range_operator"> <source>Use range operator</source> <target state="translated">Usar operador de intervalo</target> <note /> </trans-unit> <trans-unit id="Use_simple_using_statement"> <source>Use simple 'using' statement</source> <target state="translated">Usar a instrução 'using' simples</target> <note /> </trans-unit> <trans-unit id="Use_switch_expression"> <source>Use 'switch' expression</source> <target state="translated">Usar a expressão 'switch'</target> <note /> </trans-unit> <trans-unit id="Using_directives_must_be_placed_inside_of_a_namespace_declaration"> <source>Using directives must be placed inside of a namespace declaration</source> <target state="translated">As diretivas using precisam ser colocadas dentro de uma declaração de namespace</target> <note>{Locked="using"} "using" is a C# keyword and should not be localized. {Locked="namespace"} "namespace" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="Using_directives_must_be_placed_outside_of_a_namespace_declaration"> <source>Using directives must be placed outside of a namespace declaration</source> <target state="translated">As diretivas using precisam ser colocadas fora de uma declaração de namespace</target> <note>{Locked="using"} "using" is a C# keyword and should not be localized. {Locked="namespace"} "namespace" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="Variable_declaration_can_be_deconstructed"> <source>Variable declaration can be deconstructed</source> <target state="translated">A declaração de variável pode ser desconstruída</target> <note /> </trans-unit> <trans-unit id="Variable_declaration_can_be_inlined"> <source>Variable declaration can be inlined</source> <target state="translated">A declaração de variável pode ser embutida</target> <note /> </trans-unit> <trans-unit id="Warning_colon_Moving_using_directives_may_change_code_meaning"> <source>Warning: Moving using directives may change code meaning.</source> <target state="translated">Aviso: a movimentação das diretivas using pode alterar o significado do código.</target> <note>{Locked="using"} "using" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="_0_can_be_simplified"> <source>{0} can be simplified</source> <target state="translated">{0} pode ser simplificado</target> <note /> </trans-unit> <trans-unit id="default_expression_can_be_simplified"> <source>'default' expression can be simplified</source> <target state="translated">'a expressão 'default' pode ser simplificada</target> <note /> </trans-unit> <trans-unit id="if_statement_can_be_simplified"> <source>'if' statement can be simplified</source> <target state="translated">A instrução 'if' pode ser simplificada</target> <note /> </trans-unit> <trans-unit id="new_expression_can_be_simplified"> <source>'new' expression can be simplified</source> <target state="translated">A expressão 'new' pode ser simplificada</target> <note /> </trans-unit> <trans-unit id="typeof_can_be_converted_ to_nameof"> <source>'typeof' can be converted to 'nameof'</source> <target state="translated">'typeof' pode ser convertido em 'nameof'</target> <note /> </trans-unit> <trans-unit id="use_var_instead_of_explicit_type"> <source>use 'var' instead of explicit type</source> <target state="translated">usar 'var' em vez do tipo explícito</target> <note /> </trans-unit> <trans-unit id="Using_directive_is_unnecessary"> <source>Using directive is unnecessary.</source> <target state="translated">O uso da diretiva é desnecessário.</target> <note /> </trans-unit> <trans-unit id="using_statement_can_be_simplified"> <source>'using' statement can be simplified</source> <target state="translated">A instrução 'using' pode ser simplificada</target> <note /> </trans-unit> </body> </file> </xliff>
1
dotnet/roslyn
55,427
Fixes #50462
Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
Blokyk
2021-08-05T01:17:37Z
2021-08-25T05:42:59Z
fefb8c2110625bc4908db4bbdaa367b12bfb1069
fb4ac545a1f1f365e7df570637699d9085ea4f87
Fixes #50462. Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
./src/Analyzers/CSharp/Analyzers/xlf/CSharpAnalyzersResources.ru.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="ru" original="../CSharpAnalyzersResources.resx"> <body> <trans-unit id="Add_braces"> <source>Add braces</source> <target state="translated">Добавить фигурные скобки</target> <note /> </trans-unit> <trans-unit id="Add_braces_to_0_statement"> <source>Add braces to '{0}' statement.</source> <target state="translated">Добавить фигурные скобки в оператор "{0}".</target> <note /> </trans-unit> <trans-unit id="Blank_line_not_allowed_after_constructor_initializer_colon"> <source>Blank line not allowed after constructor initializer colon</source> <target state="translated">После инициализатора конструктора с двоеточием не допускается пустая строка.</target> <note /> </trans-unit> <trans-unit id="Consecutive_braces_must_not_have_a_blank_between_them"> <source>Consecutive braces must not have blank line between them</source> <target state="translated">Между последовательными фигурными скобками не должно быть пустых строк.</target> <note /> </trans-unit> <trans-unit id="Convert_switch_statement_to_expression"> <source>Convert switch statement to expression</source> <target state="translated">Преобразовать оператор switch в выражение</target> <note /> </trans-unit> <trans-unit id="Convert_to_block_scoped_namespace"> <source>Convert to block scoped namespace</source> <target state="new">Convert to block scoped namespace</target> <note>{Locked="namespace"} "namespace" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="Convert_to_file_scoped_namespace"> <source>Convert to file-scoped namespace</source> <target state="new">Convert to file-scoped namespace</target> <note>{Locked="namespace"} "namespace" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="Deconstruct_variable_declaration"> <source>Deconstruct variable declaration</source> <target state="translated">Деконструировать объявление переменной</target> <note /> </trans-unit> <trans-unit id="Delegate_invocation_can_be_simplified"> <source>Delegate invocation can be simplified.</source> <target state="translated">Вызов делегата можно упростить.</target> <note /> </trans-unit> <trans-unit id="Discard_can_be_removed"> <source>Discard can be removed</source> <target state="translated">Пустую переменную можно удалить</target> <note /> </trans-unit> <trans-unit id="Embedded_statements_must_be_on_their_own_line"> <source>Embedded statements must be on their own line</source> <target state="translated">Встроенные операторы должны располагаться на отдельной строке.</target> <note /> </trans-unit> <trans-unit id="Indexing_can_be_simplified"> <source>Indexing can be simplified</source> <target state="translated">Вы можете упростить индексирование</target> <note /> </trans-unit> <trans-unit id="Inline_variable_declaration"> <source>Inline variable declaration</source> <target state="translated">Объявление встроенной переменной</target> <note /> </trans-unit> <trans-unit id="Misplaced_using_directive"> <source>Misplaced using directive</source> <target state="translated">Неправильно расположенная директива using</target> <note>{Locked="using"} "using" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="Move_misplaced_using_directives"> <source>Move misplaced using directives</source> <target state="translated">Переместить неправильно расположенные директивы using</target> <note>{Locked="using"} "using" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="Make_readonly_fields_writable"> <source>Make readonly fields writable</source> <target state="translated">Сделать поля readonly доступными для записи</target> <note>{Locked="readonly"} "readonly" is C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="Local_function_can_be_made_static"> <source>Local function can be made static</source> <target state="translated">Локальную функцию можно сделать статической</target> <note /> </trans-unit> <trans-unit id="Make_local_function_static"> <source>Make local function 'static'</source> <target state="translated">Сделать локальную функцию статической</target> <note /> </trans-unit> <trans-unit id="Negate_expression_changes_semantics"> <source>Negate expression (changes semantics)</source> <target state="translated">Применить отрицание к выражению (семантика изменяется)</target> <note /> </trans-unit> <trans-unit id="Null_check_can_be_clarified"> <source>Null check can be clarified</source> <target state="new">Null check can be clarified</target> <note /> </trans-unit> <trans-unit id="Prefer_null_check_over_type_check"> <source>Prefer 'null' check over type check</source> <target state="new">Prefer 'null' check over type check</target> <note /> </trans-unit> <trans-unit id="Remove_operator_preserves_semantics"> <source>Remove operator (preserves semantics)</source> <target state="translated">Удалить оператор (семантика сохраняется)</target> <note /> </trans-unit> <trans-unit id="Remove_suppression_operators"> <source>Remove suppression operators</source> <target state="translated">Удалить операторы подавления</target> <note /> </trans-unit> <trans-unit id="Remove_unnecessary_suppression_operator"> <source>Remove unnecessary suppression operator</source> <target state="translated">Удалить ненужный оператор подавления</target> <note /> </trans-unit> <trans-unit id="Remove_unnessary_discard"> <source>Remove unnecessary discard</source> <target state="translated">Удалите ненужную пустую переменную.</target> <note /> </trans-unit> <trans-unit id="Simplify_default_expression"> <source>Simplify 'default' expression</source> <target state="translated">Упростить выражение default</target> <note /> </trans-unit> <trans-unit id="Struct_contains_assignment_to_this_outside_of_constructor_Make_readonly_fields_writable"> <source>Struct contains assignment to 'this' outside of constructor. Make readonly fields writable.</source> <target state="translated">Структура (Struct) содержит присваивание "this" вне конструктора. Сделайте поля, доступные только для чтения, доступными для записи.</target> <note>{Locked="Struct"}{Locked="this"} these are C#/VB keywords and should not be localized.</note> </trans-unit> <trans-unit id="Suppression_operator_has_no_effect_and_can_be_misinterpreted"> <source>Suppression operator has no effect and can be misinterpreted</source> <target state="translated">Оператор подавления не имеет эффекта и может быть интерпретирован неправильно.</target> <note /> </trans-unit> <trans-unit id="Unreachable_code_detected"> <source>Unreachable code detected</source> <target state="translated">Обнаружен недостижимый код</target> <note /> </trans-unit> <trans-unit id="Use_block_body_for_accessors"> <source>Use block body for accessors</source> <target state="translated">Использовать тело блока для методов доступа</target> <note /> </trans-unit> <trans-unit id="Use_block_body_for_constructors"> <source>Use block body for constructors</source> <target state="translated">Использовать тело блока для конструкторов</target> <note /> </trans-unit> <trans-unit id="Use_block_body_for_indexers"> <source>Use block body for indexers</source> <target state="translated">Использовать тело блока для индексаторов</target> <note /> </trans-unit> <trans-unit id="Use_block_body_for_local_functions"> <source>Use block body for local functions</source> <target state="translated">Использовать тело блока для локальных функций</target> <note /> </trans-unit> <trans-unit id="Use_block_body_for_methods"> <source>Use block body for methods</source> <target state="translated">Использовать тело блока для методов</target> <note /> </trans-unit> <trans-unit id="Use_block_body_for_operators"> <source>Use block body for operators</source> <target state="translated">Использовать тело блока для операторов</target> <note /> </trans-unit> <trans-unit id="Use_block_body_for_properties"> <source>Use block body for properties</source> <target state="translated">Использовать тело блока для свойств</target> <note /> </trans-unit> <trans-unit id="Use_explicit_type"> <source>Use explicit type</source> <target state="translated">Использование явного типа</target> <note /> </trans-unit> <trans-unit id="Use_explicit_type_instead_of_var"> <source>Use explicit type instead of 'var'</source> <target state="translated">Использовать явный тип вместо var</target> <note /> </trans-unit> <trans-unit id="Use_expression_body_for_accessors"> <source>Use expression body for accessors</source> <target state="translated">Использовать тело выражения для методов доступа</target> <note /> </trans-unit> <trans-unit id="Use_expression_body_for_constructors"> <source>Use expression body for constructors</source> <target state="translated">Использовать тело выражения для конструкторов</target> <note /> </trans-unit> <trans-unit id="Use_expression_body_for_indexers"> <source>Use expression body for indexers</source> <target state="translated">Использовать тело выражения для индексаторов</target> <note /> </trans-unit> <trans-unit id="Use_expression_body_for_local_functions"> <source>Use expression body for local functions</source> <target state="translated">Использовать тело выражения для локальных функций</target> <note /> </trans-unit> <trans-unit id="Use_expression_body_for_methods"> <source>Use expression body for methods</source> <target state="translated">Использовать тело выражения для методов</target> <note /> </trans-unit> <trans-unit id="Use_expression_body_for_operators"> <source>Use expression body for operators</source> <target state="translated">Использовать тело выражения для операторов</target> <note /> </trans-unit> <trans-unit id="Use_expression_body_for_properties"> <source>Use expression body for properties</source> <target state="translated">Использовать тело выражения для свойств</target> <note /> </trans-unit> <trans-unit id="Use_implicit_type"> <source>Use implicit type</source> <target state="translated">Использование неявного типа</target> <note /> </trans-unit> <trans-unit id="Use_index_operator"> <source>Use index operator</source> <target state="translated">Использовать оператор индекса</target> <note /> </trans-unit> <trans-unit id="Use_is_null_check"> <source>Use 'is null' check</source> <target state="translated">Использовать флажок "is NULL"</target> <note /> </trans-unit> <trans-unit id="Use_local_function"> <source>Use local function</source> <target state="translated">Использовать локальную функцию</target> <note /> </trans-unit> <trans-unit id="Use_new"> <source>Use 'new(...)'</source> <target state="translated">Используйте "new(...)".</target> <note>{Locked="new(...)"} This is a C# construct and should not be localized.</note> </trans-unit> <trans-unit id="Use_pattern_matching"> <source>Use pattern matching</source> <target state="translated">Используйте сопоставление шаблонов</target> <note /> </trans-unit> <trans-unit id="Use_range_operator"> <source>Use range operator</source> <target state="translated">Использовать оператор диапазона</target> <note /> </trans-unit> <trans-unit id="Use_simple_using_statement"> <source>Use simple 'using' statement</source> <target state="translated">Использовать простой оператор using</target> <note /> </trans-unit> <trans-unit id="Use_switch_expression"> <source>Use 'switch' expression</source> <target state="translated">Использовать выражение switch</target> <note /> </trans-unit> <trans-unit id="Using_directives_must_be_placed_inside_of_a_namespace_declaration"> <source>Using directives must be placed inside of a namespace declaration</source> <target state="translated">Директивы using должны находиться внутри объявления namespace</target> <note>{Locked="using"} "using" is a C# keyword and should not be localized. {Locked="namespace"} "namespace" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="Using_directives_must_be_placed_outside_of_a_namespace_declaration"> <source>Using directives must be placed outside of a namespace declaration</source> <target state="translated">Директивы using должны находиться вне объявления namespace</target> <note>{Locked="using"} "using" is a C# keyword and should not be localized. {Locked="namespace"} "namespace" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="Variable_declaration_can_be_deconstructed"> <source>Variable declaration can be deconstructed</source> <target state="translated">Объявление переменной можно деконструировать</target> <note /> </trans-unit> <trans-unit id="Variable_declaration_can_be_inlined"> <source>Variable declaration can be inlined</source> <target state="translated">Объявление переменной может быть встроенным.</target> <note /> </trans-unit> <trans-unit id="Warning_colon_Moving_using_directives_may_change_code_meaning"> <source>Warning: Moving using directives may change code meaning.</source> <target state="translated">Предупреждение! Перемещение директив using может изменить значение кода.</target> <note>{Locked="using"} "using" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="_0_can_be_simplified"> <source>{0} can be simplified</source> <target state="translated">{0} можно упростить</target> <note /> </trans-unit> <trans-unit id="default_expression_can_be_simplified"> <source>'default' expression can be simplified</source> <target state="translated">выражение default можно упростить</target> <note /> </trans-unit> <trans-unit id="if_statement_can_be_simplified"> <source>'if' statement can be simplified</source> <target state="translated">Оператор if можно упростить</target> <note /> </trans-unit> <trans-unit id="new_expression_can_be_simplified"> <source>'new' expression can be simplified</source> <target state="translated">выражение new можно упростить</target> <note /> </trans-unit> <trans-unit id="typeof_can_be_converted_ to_nameof"> <source>'typeof' can be converted to 'nameof'</source> <target state="translated">"typeof" можно преобразовать в "nameof".</target> <note /> </trans-unit> <trans-unit id="use_var_instead_of_explicit_type"> <source>use 'var' instead of explicit type</source> <target state="translated">Использовать var вместо явного типа</target> <note /> </trans-unit> <trans-unit id="Using_directive_is_unnecessary"> <source>Using directive is unnecessary.</source> <target state="translated">Директива using не нужна.</target> <note /> </trans-unit> <trans-unit id="using_statement_can_be_simplified"> <source>'using' statement can be simplified</source> <target state="translated">Оператор using можно упростить</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="ru" original="../CSharpAnalyzersResources.resx"> <body> <trans-unit id="Add_braces"> <source>Add braces</source> <target state="translated">Добавить фигурные скобки</target> <note /> </trans-unit> <trans-unit id="Add_braces_to_0_statement"> <source>Add braces to '{0}' statement.</source> <target state="translated">Добавить фигурные скобки в оператор "{0}".</target> <note /> </trans-unit> <trans-unit id="Blank_line_not_allowed_after_constructor_initializer_colon"> <source>Blank line not allowed after constructor initializer colon</source> <target state="translated">После инициализатора конструктора с двоеточием не допускается пустая строка.</target> <note /> </trans-unit> <trans-unit id="Consecutive_braces_must_not_have_a_blank_between_them"> <source>Consecutive braces must not have blank line between them</source> <target state="translated">Между последовательными фигурными скобками не должно быть пустых строк.</target> <note /> </trans-unit> <trans-unit id="Convert_switch_statement_to_expression"> <source>Convert switch statement to expression</source> <target state="translated">Преобразовать оператор switch в выражение</target> <note /> </trans-unit> <trans-unit id="Convert_to_block_scoped_namespace"> <source>Convert to block scoped namespace</source> <target state="new">Convert to block scoped namespace</target> <note>{Locked="namespace"} "namespace" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="Convert_to_file_scoped_namespace"> <source>Convert to file-scoped namespace</source> <target state="new">Convert to file-scoped namespace</target> <note>{Locked="namespace"} "namespace" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="Deconstruct_variable_declaration"> <source>Deconstruct variable declaration</source> <target state="translated">Деконструировать объявление переменной</target> <note /> </trans-unit> <trans-unit id="Delegate_invocation_can_be_simplified"> <source>Delegate invocation can be simplified.</source> <target state="translated">Вызов делегата можно упростить.</target> <note /> </trans-unit> <trans-unit id="Discard_can_be_removed"> <source>Discard can be removed</source> <target state="translated">Пустую переменную можно удалить</target> <note /> </trans-unit> <trans-unit id="Embedded_statements_must_be_on_their_own_line"> <source>Embedded statements must be on their own line</source> <target state="translated">Встроенные операторы должны располагаться на отдельной строке.</target> <note /> </trans-unit> <trans-unit id="Indexing_can_be_simplified"> <source>Indexing can be simplified</source> <target state="translated">Вы можете упростить индексирование</target> <note /> </trans-unit> <trans-unit id="Inline_variable_declaration"> <source>Inline variable declaration</source> <target state="translated">Объявление встроенной переменной</target> <note /> </trans-unit> <trans-unit id="Misplaced_using_directive"> <source>Misplaced using directive</source> <target state="translated">Неправильно расположенная директива using</target> <note>{Locked="using"} "using" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="Move_misplaced_using_directives"> <source>Move misplaced using directives</source> <target state="translated">Переместить неправильно расположенные директивы using</target> <note>{Locked="using"} "using" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="Make_readonly_fields_writable"> <source>Make readonly fields writable</source> <target state="translated">Сделать поля readonly доступными для записи</target> <note>{Locked="readonly"} "readonly" is C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="Local_function_can_be_made_static"> <source>Local function can be made static</source> <target state="translated">Локальную функцию можно сделать статической</target> <note /> </trans-unit> <trans-unit id="Make_local_function_static"> <source>Make local function 'static'</source> <target state="translated">Сделать локальную функцию статической</target> <note /> </trans-unit> <trans-unit id="Negate_expression_changes_semantics"> <source>Negate expression (changes semantics)</source> <target state="translated">Применить отрицание к выражению (семантика изменяется)</target> <note /> </trans-unit> <trans-unit id="Null_check_can_be_clarified"> <source>Null check can be clarified</source> <target state="new">Null check can be clarified</target> <note /> </trans-unit> <trans-unit id="Prefer_null_check_over_type_check"> <source>Prefer 'null' check over type check</source> <target state="new">Prefer 'null' check over type check</target> <note /> </trans-unit> <trans-unit id="Remove_operator_preserves_semantics"> <source>Remove operator (preserves semantics)</source> <target state="translated">Удалить оператор (семантика сохраняется)</target> <note /> </trans-unit> <trans-unit id="Remove_suppression_operators"> <source>Remove suppression operators</source> <target state="translated">Удалить операторы подавления</target> <note /> </trans-unit> <trans-unit id="Remove_unnecessary_suppression_operator"> <source>Remove unnecessary suppression operator</source> <target state="translated">Удалить ненужный оператор подавления</target> <note /> </trans-unit> <trans-unit id="Remove_unnessary_discard"> <source>Remove unnecessary discard</source> <target state="translated">Удалите ненужную пустую переменную.</target> <note /> </trans-unit> <trans-unit id="Simplify_default_expression"> <source>Simplify 'default' expression</source> <target state="translated">Упростить выражение default</target> <note /> </trans-unit> <trans-unit id="Struct_contains_assignment_to_this_outside_of_constructor_Make_readonly_fields_writable"> <source>Struct contains assignment to 'this' outside of constructor. Make readonly fields writable.</source> <target state="translated">Структура (Struct) содержит присваивание "this" вне конструктора. Сделайте поля, доступные только для чтения, доступными для записи.</target> <note>{Locked="Struct"}{Locked="this"} these are C#/VB keywords and should not be localized.</note> </trans-unit> <trans-unit id="Suppression_operator_has_no_effect_and_can_be_misinterpreted"> <source>Suppression operator has no effect and can be misinterpreted</source> <target state="translated">Оператор подавления не имеет эффекта и может быть интерпретирован неправильно.</target> <note /> </trans-unit> <trans-unit id="Unreachable_code_detected"> <source>Unreachable code detected</source> <target state="translated">Обнаружен недостижимый код</target> <note /> </trans-unit> <trans-unit id="Use_block_body_for_accessors"> <source>Use block body for accessors</source> <target state="translated">Использовать тело блока для методов доступа</target> <note /> </trans-unit> <trans-unit id="Use_block_body_for_constructors"> <source>Use block body for constructors</source> <target state="translated">Использовать тело блока для конструкторов</target> <note /> </trans-unit> <trans-unit id="Use_block_body_for_indexers"> <source>Use block body for indexers</source> <target state="translated">Использовать тело блока для индексаторов</target> <note /> </trans-unit> <trans-unit id="Use_block_body_for_local_functions"> <source>Use block body for local functions</source> <target state="translated">Использовать тело блока для локальных функций</target> <note /> </trans-unit> <trans-unit id="Use_block_body_for_methods"> <source>Use block body for methods</source> <target state="translated">Использовать тело блока для методов</target> <note /> </trans-unit> <trans-unit id="Use_block_body_for_operators"> <source>Use block body for operators</source> <target state="translated">Использовать тело блока для операторов</target> <note /> </trans-unit> <trans-unit id="Use_block_body_for_properties"> <source>Use block body for properties</source> <target state="translated">Использовать тело блока для свойств</target> <note /> </trans-unit> <trans-unit id="Use_explicit_type"> <source>Use explicit type</source> <target state="translated">Использование явного типа</target> <note /> </trans-unit> <trans-unit id="Use_explicit_type_instead_of_var"> <source>Use explicit type instead of 'var'</source> <target state="translated">Использовать явный тип вместо var</target> <note /> </trans-unit> <trans-unit id="Use_expression_body_for_accessors"> <source>Use expression body for accessors</source> <target state="translated">Использовать тело выражения для методов доступа</target> <note /> </trans-unit> <trans-unit id="Use_expression_body_for_constructors"> <source>Use expression body for constructors</source> <target state="translated">Использовать тело выражения для конструкторов</target> <note /> </trans-unit> <trans-unit id="Use_expression_body_for_indexers"> <source>Use expression body for indexers</source> <target state="translated">Использовать тело выражения для индексаторов</target> <note /> </trans-unit> <trans-unit id="Use_expression_body_for_local_functions"> <source>Use expression body for local functions</source> <target state="translated">Использовать тело выражения для локальных функций</target> <note /> </trans-unit> <trans-unit id="Use_expression_body_for_methods"> <source>Use expression body for methods</source> <target state="translated">Использовать тело выражения для методов</target> <note /> </trans-unit> <trans-unit id="Use_expression_body_for_operators"> <source>Use expression body for operators</source> <target state="translated">Использовать тело выражения для операторов</target> <note /> </trans-unit> <trans-unit id="Use_expression_body_for_properties"> <source>Use expression body for properties</source> <target state="translated">Использовать тело выражения для свойств</target> <note /> </trans-unit> <trans-unit id="Use_implicit_type"> <source>Use implicit type</source> <target state="translated">Использование неявного типа</target> <note /> </trans-unit> <trans-unit id="Use_index_operator"> <source>Use index operator</source> <target state="translated">Использовать оператор индекса</target> <note /> </trans-unit> <trans-unit id="Use_is_null_check"> <source>Use 'is null' check</source> <target state="translated">Использовать флажок "is NULL"</target> <note /> </trans-unit> <trans-unit id="Use_local_function"> <source>Use local function</source> <target state="translated">Использовать локальную функцию</target> <note /> </trans-unit> <trans-unit id="Use_new"> <source>Use 'new(...)'</source> <target state="translated">Используйте "new(...)".</target> <note>{Locked="new(...)"} This is a C# construct and should not be localized.</note> </trans-unit> <trans-unit id="Use_pattern_matching"> <source>Use pattern matching</source> <target state="translated">Используйте сопоставление шаблонов</target> <note /> </trans-unit> <trans-unit id="Use_pattern_matching_may_change_code_meaning"> <source>Use pattern matching (may change code meaning)</source> <target state="new">Use pattern matching (may change code meaning)</target> <note /> </trans-unit> <trans-unit id="Use_range_operator"> <source>Use range operator</source> <target state="translated">Использовать оператор диапазона</target> <note /> </trans-unit> <trans-unit id="Use_simple_using_statement"> <source>Use simple 'using' statement</source> <target state="translated">Использовать простой оператор using</target> <note /> </trans-unit> <trans-unit id="Use_switch_expression"> <source>Use 'switch' expression</source> <target state="translated">Использовать выражение switch</target> <note /> </trans-unit> <trans-unit id="Using_directives_must_be_placed_inside_of_a_namespace_declaration"> <source>Using directives must be placed inside of a namespace declaration</source> <target state="translated">Директивы using должны находиться внутри объявления namespace</target> <note>{Locked="using"} "using" is a C# keyword and should not be localized. {Locked="namespace"} "namespace" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="Using_directives_must_be_placed_outside_of_a_namespace_declaration"> <source>Using directives must be placed outside of a namespace declaration</source> <target state="translated">Директивы using должны находиться вне объявления namespace</target> <note>{Locked="using"} "using" is a C# keyword and should not be localized. {Locked="namespace"} "namespace" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="Variable_declaration_can_be_deconstructed"> <source>Variable declaration can be deconstructed</source> <target state="translated">Объявление переменной можно деконструировать</target> <note /> </trans-unit> <trans-unit id="Variable_declaration_can_be_inlined"> <source>Variable declaration can be inlined</source> <target state="translated">Объявление переменной может быть встроенным.</target> <note /> </trans-unit> <trans-unit id="Warning_colon_Moving_using_directives_may_change_code_meaning"> <source>Warning: Moving using directives may change code meaning.</source> <target state="translated">Предупреждение! Перемещение директив using может изменить значение кода.</target> <note>{Locked="using"} "using" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="_0_can_be_simplified"> <source>{0} can be simplified</source> <target state="translated">{0} можно упростить</target> <note /> </trans-unit> <trans-unit id="default_expression_can_be_simplified"> <source>'default' expression can be simplified</source> <target state="translated">выражение default можно упростить</target> <note /> </trans-unit> <trans-unit id="if_statement_can_be_simplified"> <source>'if' statement can be simplified</source> <target state="translated">Оператор if можно упростить</target> <note /> </trans-unit> <trans-unit id="new_expression_can_be_simplified"> <source>'new' expression can be simplified</source> <target state="translated">выражение new можно упростить</target> <note /> </trans-unit> <trans-unit id="typeof_can_be_converted_ to_nameof"> <source>'typeof' can be converted to 'nameof'</source> <target state="translated">"typeof" можно преобразовать в "nameof".</target> <note /> </trans-unit> <trans-unit id="use_var_instead_of_explicit_type"> <source>use 'var' instead of explicit type</source> <target state="translated">Использовать var вместо явного типа</target> <note /> </trans-unit> <trans-unit id="Using_directive_is_unnecessary"> <source>Using directive is unnecessary.</source> <target state="translated">Директива using не нужна.</target> <note /> </trans-unit> <trans-unit id="using_statement_can_be_simplified"> <source>'using' statement can be simplified</source> <target state="translated">Оператор using можно упростить</target> <note /> </trans-unit> </body> </file> </xliff>
1
dotnet/roslyn
55,427
Fixes #50462
Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
Blokyk
2021-08-05T01:17:37Z
2021-08-25T05:42:59Z
fefb8c2110625bc4908db4bbdaa367b12bfb1069
fb4ac545a1f1f365e7df570637699d9085ea4f87
Fixes #50462. Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
./src/Analyzers/CSharp/Analyzers/xlf/CSharpAnalyzersResources.tr.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="tr" original="../CSharpAnalyzersResources.resx"> <body> <trans-unit id="Add_braces"> <source>Add braces</source> <target state="translated">Küme ayracı ekle</target> <note /> </trans-unit> <trans-unit id="Add_braces_to_0_statement"> <source>Add braces to '{0}' statement.</source> <target state="translated">'{0}' deyimine küme ayracı ekleyin.</target> <note /> </trans-unit> <trans-unit id="Blank_line_not_allowed_after_constructor_initializer_colon"> <source>Blank line not allowed after constructor initializer colon</source> <target state="translated">Oluşturucu başlatıcı iki noktadan sonra boş satıra izin verilmiyor</target> <note /> </trans-unit> <trans-unit id="Consecutive_braces_must_not_have_a_blank_between_them"> <source>Consecutive braces must not have blank line between them</source> <target state="translated">Ardışık ayraçlar arasında boş çizgi olmamalıdır</target> <note /> </trans-unit> <trans-unit id="Convert_switch_statement_to_expression"> <source>Convert switch statement to expression</source> <target state="translated">Switch deyimini ifadeye dönüştür</target> <note /> </trans-unit> <trans-unit id="Convert_to_block_scoped_namespace"> <source>Convert to block scoped namespace</source> <target state="new">Convert to block scoped namespace</target> <note>{Locked="namespace"} "namespace" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="Convert_to_file_scoped_namespace"> <source>Convert to file-scoped namespace</source> <target state="new">Convert to file-scoped namespace</target> <note>{Locked="namespace"} "namespace" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="Deconstruct_variable_declaration"> <source>Deconstruct variable declaration</source> <target state="translated">Değişken bildirimini ayrıştır</target> <note /> </trans-unit> <trans-unit id="Delegate_invocation_can_be_simplified"> <source>Delegate invocation can be simplified.</source> <target state="translated">Temsilci çağrısı basitleştirilebilir.</target> <note /> </trans-unit> <trans-unit id="Discard_can_be_removed"> <source>Discard can be removed</source> <target state="translated">Atma işlemi kaldırılabilir</target> <note /> </trans-unit> <trans-unit id="Embedded_statements_must_be_on_their_own_line"> <source>Embedded statements must be on their own line</source> <target state="translated">Katıştırılmış deyimler kendi satırına yerleştirilmelidir</target> <note /> </trans-unit> <trans-unit id="Indexing_can_be_simplified"> <source>Indexing can be simplified</source> <target state="translated">Dizin oluşturma basitleştirilebilir</target> <note /> </trans-unit> <trans-unit id="Inline_variable_declaration"> <source>Inline variable declaration</source> <target state="translated">Satır içi değişken bildirimi</target> <note /> </trans-unit> <trans-unit id="Misplaced_using_directive"> <source>Misplaced using directive</source> <target state="translated">Yanlış yerleştirilmiş using yönergesi</target> <note>{Locked="using"} "using" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="Move_misplaced_using_directives"> <source>Move misplaced using directives</source> <target state="translated">Yanlış yerleştirilmiş using yönergelerini taşı</target> <note>{Locked="using"} "using" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="Make_readonly_fields_writable"> <source>Make readonly fields writable</source> <target state="translated">readonly alanları yazılabilir yap</target> <note>{Locked="readonly"} "readonly" is C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="Local_function_can_be_made_static"> <source>Local function can be made static</source> <target state="translated">Yerel işlev statik yapılabilir</target> <note /> </trans-unit> <trans-unit id="Make_local_function_static"> <source>Make local function 'static'</source> <target state="translated">Yerel işlevi 'static' yap</target> <note /> </trans-unit> <trans-unit id="Negate_expression_changes_semantics"> <source>Negate expression (changes semantics)</source> <target state="translated">İfadeyi tersine çevir (semantiği değiştirir)</target> <note /> </trans-unit> <trans-unit id="Null_check_can_be_clarified"> <source>Null check can be clarified</source> <target state="new">Null check can be clarified</target> <note /> </trans-unit> <trans-unit id="Prefer_null_check_over_type_check"> <source>Prefer 'null' check over type check</source> <target state="new">Prefer 'null' check over type check</target> <note /> </trans-unit> <trans-unit id="Remove_operator_preserves_semantics"> <source>Remove operator (preserves semantics)</source> <target state="translated">İşleci kaldır (semantiği korur)</target> <note /> </trans-unit> <trans-unit id="Remove_suppression_operators"> <source>Remove suppression operators</source> <target state="translated">Gizleme işleçlerini kaldır</target> <note /> </trans-unit> <trans-unit id="Remove_unnecessary_suppression_operator"> <source>Remove unnecessary suppression operator</source> <target state="translated">Gereksiz gizleme işlecini kaldır</target> <note /> </trans-unit> <trans-unit id="Remove_unnessary_discard"> <source>Remove unnecessary discard</source> <target state="translated">Gereksiz atmayı kaldır</target> <note /> </trans-unit> <trans-unit id="Simplify_default_expression"> <source>Simplify 'default' expression</source> <target state="translated">Default' ifadesini basitleştir</target> <note /> </trans-unit> <trans-unit id="Struct_contains_assignment_to_this_outside_of_constructor_Make_readonly_fields_writable"> <source>Struct contains assignment to 'this' outside of constructor. Make readonly fields writable.</source> <target state="translated">Struct, oluşturucu dışında 'this' öğesine yönelik atama içeriyor. Salt okunur alanları yazılabilir yapın.</target> <note>{Locked="Struct"}{Locked="this"} these are C#/VB keywords and should not be localized.</note> </trans-unit> <trans-unit id="Suppression_operator_has_no_effect_and_can_be_misinterpreted"> <source>Suppression operator has no effect and can be misinterpreted</source> <target state="translated">Gizleme işleci hiçbir etkiye sahip değil ve yanlış yorumlanabilir</target> <note /> </trans-unit> <trans-unit id="Unreachable_code_detected"> <source>Unreachable code detected</source> <target state="translated">Ulaşılamayan kod algılandı</target> <note /> </trans-unit> <trans-unit id="Use_block_body_for_accessors"> <source>Use block body for accessors</source> <target state="translated">Erişimciler için blok gövdesi kullan</target> <note /> </trans-unit> <trans-unit id="Use_block_body_for_constructors"> <source>Use block body for constructors</source> <target state="translated">Oluşturucular için blok gövdesi kullan</target> <note /> </trans-unit> <trans-unit id="Use_block_body_for_indexers"> <source>Use block body for indexers</source> <target state="translated">Dizin oluşturucular için blok gövdesi kullan</target> <note /> </trans-unit> <trans-unit id="Use_block_body_for_local_functions"> <source>Use block body for local functions</source> <target state="translated">Yerel işlevler için blok gövdesi kullan</target> <note /> </trans-unit> <trans-unit id="Use_block_body_for_methods"> <source>Use block body for methods</source> <target state="translated">Metotlar için blok gövdesi kullan</target> <note /> </trans-unit> <trans-unit id="Use_block_body_for_operators"> <source>Use block body for operators</source> <target state="translated">İşleçler için blok gövdesi kullan</target> <note /> </trans-unit> <trans-unit id="Use_block_body_for_properties"> <source>Use block body for properties</source> <target state="translated">Özellikler için blok gövdesi kullan</target> <note /> </trans-unit> <trans-unit id="Use_explicit_type"> <source>Use explicit type</source> <target state="translated">Açık tür kullanma</target> <note /> </trans-unit> <trans-unit id="Use_explicit_type_instead_of_var"> <source>Use explicit type instead of 'var'</source> <target state="translated">Var' yerine açık tür kullan</target> <note /> </trans-unit> <trans-unit id="Use_expression_body_for_accessors"> <source>Use expression body for accessors</source> <target state="translated">Erişimciler için ifade gövdesi kullan</target> <note /> </trans-unit> <trans-unit id="Use_expression_body_for_constructors"> <source>Use expression body for constructors</source> <target state="translated">Oluşturucular için ifade gövdesi kullan</target> <note /> </trans-unit> <trans-unit id="Use_expression_body_for_indexers"> <source>Use expression body for indexers</source> <target state="translated">Dizin oluşturucular için ifade gövdesi kullan</target> <note /> </trans-unit> <trans-unit id="Use_expression_body_for_local_functions"> <source>Use expression body for local functions</source> <target state="translated">Yerel işlevler için ifade gövdesi kullan</target> <note /> </trans-unit> <trans-unit id="Use_expression_body_for_methods"> <source>Use expression body for methods</source> <target state="translated">Metotlar için ifade gövdesi kullan</target> <note /> </trans-unit> <trans-unit id="Use_expression_body_for_operators"> <source>Use expression body for operators</source> <target state="translated">İşleçler için ifade gövdesi kullan</target> <note /> </trans-unit> <trans-unit id="Use_expression_body_for_properties"> <source>Use expression body for properties</source> <target state="translated">Özellikler için ifade gövdesi kullan</target> <note /> </trans-unit> <trans-unit id="Use_implicit_type"> <source>Use implicit type</source> <target state="translated">Örtük tür kullanma</target> <note /> </trans-unit> <trans-unit id="Use_index_operator"> <source>Use index operator</source> <target state="translated">Dizin işleci kullan</target> <note /> </trans-unit> <trans-unit id="Use_is_null_check"> <source>Use 'is null' check</source> <target state="translated">is null' denetimini kullan</target> <note /> </trans-unit> <trans-unit id="Use_local_function"> <source>Use local function</source> <target state="translated">Yerel işlev kullan</target> <note /> </trans-unit> <trans-unit id="Use_new"> <source>Use 'new(...)'</source> <target state="translated">'new(...)' kullanın</target> <note>{Locked="new(...)"} This is a C# construct and should not be localized.</note> </trans-unit> <trans-unit id="Use_pattern_matching"> <source>Use pattern matching</source> <target state="translated">Desen eşleştirme kullan</target> <note /> </trans-unit> <trans-unit id="Use_range_operator"> <source>Use range operator</source> <target state="translated">Aralık işleci kullan</target> <note /> </trans-unit> <trans-unit id="Use_simple_using_statement"> <source>Use simple 'using' statement</source> <target state="translated">Basit 'using' deyimini kullan</target> <note /> </trans-unit> <trans-unit id="Use_switch_expression"> <source>Use 'switch' expression</source> <target state="translated">'Switch' ifadesini kullan</target> <note /> </trans-unit> <trans-unit id="Using_directives_must_be_placed_inside_of_a_namespace_declaration"> <source>Using directives must be placed inside of a namespace declaration</source> <target state="translated">Using yönergelerinin bir namespace bildiriminin içine yerleştirilmesi gerekir</target> <note>{Locked="using"} "using" is a C# keyword and should not be localized. {Locked="namespace"} "namespace" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="Using_directives_must_be_placed_outside_of_a_namespace_declaration"> <source>Using directives must be placed outside of a namespace declaration</source> <target state="translated">Using yönergelerinin bir namespace bildiriminin dışına yerleştirilmesi gerekir</target> <note>{Locked="using"} "using" is a C# keyword and should not be localized. {Locked="namespace"} "namespace" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="Variable_declaration_can_be_deconstructed"> <source>Variable declaration can be deconstructed</source> <target state="translated">Değişken bildirimi ayrıştırılabilir</target> <note /> </trans-unit> <trans-unit id="Variable_declaration_can_be_inlined"> <source>Variable declaration can be inlined</source> <target state="translated">Değişken bildirimi satır içine alınabilir</target> <note /> </trans-unit> <trans-unit id="Warning_colon_Moving_using_directives_may_change_code_meaning"> <source>Warning: Moving using directives may change code meaning.</source> <target state="translated">Uyarı: using yönergelerini taşımak, kodun anlamını değiştirebilir.</target> <note>{Locked="using"} "using" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="_0_can_be_simplified"> <source>{0} can be simplified</source> <target state="translated">{0} basitleştirilebilir</target> <note /> </trans-unit> <trans-unit id="default_expression_can_be_simplified"> <source>'default' expression can be simplified</source> <target state="translated">'default' ifadesi basitleştirilebilir</target> <note /> </trans-unit> <trans-unit id="if_statement_can_be_simplified"> <source>'if' statement can be simplified</source> <target state="translated">'If' deyimi basitleştirilebilir</target> <note /> </trans-unit> <trans-unit id="new_expression_can_be_simplified"> <source>'new' expression can be simplified</source> <target state="translated">'new' ifadesi basitleştirilebilir</target> <note /> </trans-unit> <trans-unit id="typeof_can_be_converted_ to_nameof"> <source>'typeof' can be converted to 'nameof'</source> <target state="translated">'typeof' metodu 'nameof' metoduna dönüştürülebilir</target> <note /> </trans-unit> <trans-unit id="use_var_instead_of_explicit_type"> <source>use 'var' instead of explicit type</source> <target state="translated">açık tür yerine 'var' kullan</target> <note /> </trans-unit> <trans-unit id="Using_directive_is_unnecessary"> <source>Using directive is unnecessary.</source> <target state="translated">Using yönergesi gerekli değildir.</target> <note /> </trans-unit> <trans-unit id="using_statement_can_be_simplified"> <source>'using' statement can be simplified</source> <target state="translated">'using' deyimi basitleştirilebilir</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="tr" original="../CSharpAnalyzersResources.resx"> <body> <trans-unit id="Add_braces"> <source>Add braces</source> <target state="translated">Küme ayracı ekle</target> <note /> </trans-unit> <trans-unit id="Add_braces_to_0_statement"> <source>Add braces to '{0}' statement.</source> <target state="translated">'{0}' deyimine küme ayracı ekleyin.</target> <note /> </trans-unit> <trans-unit id="Blank_line_not_allowed_after_constructor_initializer_colon"> <source>Blank line not allowed after constructor initializer colon</source> <target state="translated">Oluşturucu başlatıcı iki noktadan sonra boş satıra izin verilmiyor</target> <note /> </trans-unit> <trans-unit id="Consecutive_braces_must_not_have_a_blank_between_them"> <source>Consecutive braces must not have blank line between them</source> <target state="translated">Ardışık ayraçlar arasında boş çizgi olmamalıdır</target> <note /> </trans-unit> <trans-unit id="Convert_switch_statement_to_expression"> <source>Convert switch statement to expression</source> <target state="translated">Switch deyimini ifadeye dönüştür</target> <note /> </trans-unit> <trans-unit id="Convert_to_block_scoped_namespace"> <source>Convert to block scoped namespace</source> <target state="new">Convert to block scoped namespace</target> <note>{Locked="namespace"} "namespace" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="Convert_to_file_scoped_namespace"> <source>Convert to file-scoped namespace</source> <target state="new">Convert to file-scoped namespace</target> <note>{Locked="namespace"} "namespace" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="Deconstruct_variable_declaration"> <source>Deconstruct variable declaration</source> <target state="translated">Değişken bildirimini ayrıştır</target> <note /> </trans-unit> <trans-unit id="Delegate_invocation_can_be_simplified"> <source>Delegate invocation can be simplified.</source> <target state="translated">Temsilci çağrısı basitleştirilebilir.</target> <note /> </trans-unit> <trans-unit id="Discard_can_be_removed"> <source>Discard can be removed</source> <target state="translated">Atma işlemi kaldırılabilir</target> <note /> </trans-unit> <trans-unit id="Embedded_statements_must_be_on_their_own_line"> <source>Embedded statements must be on their own line</source> <target state="translated">Katıştırılmış deyimler kendi satırına yerleştirilmelidir</target> <note /> </trans-unit> <trans-unit id="Indexing_can_be_simplified"> <source>Indexing can be simplified</source> <target state="translated">Dizin oluşturma basitleştirilebilir</target> <note /> </trans-unit> <trans-unit id="Inline_variable_declaration"> <source>Inline variable declaration</source> <target state="translated">Satır içi değişken bildirimi</target> <note /> </trans-unit> <trans-unit id="Misplaced_using_directive"> <source>Misplaced using directive</source> <target state="translated">Yanlış yerleştirilmiş using yönergesi</target> <note>{Locked="using"} "using" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="Move_misplaced_using_directives"> <source>Move misplaced using directives</source> <target state="translated">Yanlış yerleştirilmiş using yönergelerini taşı</target> <note>{Locked="using"} "using" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="Make_readonly_fields_writable"> <source>Make readonly fields writable</source> <target state="translated">readonly alanları yazılabilir yap</target> <note>{Locked="readonly"} "readonly" is C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="Local_function_can_be_made_static"> <source>Local function can be made static</source> <target state="translated">Yerel işlev statik yapılabilir</target> <note /> </trans-unit> <trans-unit id="Make_local_function_static"> <source>Make local function 'static'</source> <target state="translated">Yerel işlevi 'static' yap</target> <note /> </trans-unit> <trans-unit id="Negate_expression_changes_semantics"> <source>Negate expression (changes semantics)</source> <target state="translated">İfadeyi tersine çevir (semantiği değiştirir)</target> <note /> </trans-unit> <trans-unit id="Null_check_can_be_clarified"> <source>Null check can be clarified</source> <target state="new">Null check can be clarified</target> <note /> </trans-unit> <trans-unit id="Prefer_null_check_over_type_check"> <source>Prefer 'null' check over type check</source> <target state="new">Prefer 'null' check over type check</target> <note /> </trans-unit> <trans-unit id="Remove_operator_preserves_semantics"> <source>Remove operator (preserves semantics)</source> <target state="translated">İşleci kaldır (semantiği korur)</target> <note /> </trans-unit> <trans-unit id="Remove_suppression_operators"> <source>Remove suppression operators</source> <target state="translated">Gizleme işleçlerini kaldır</target> <note /> </trans-unit> <trans-unit id="Remove_unnecessary_suppression_operator"> <source>Remove unnecessary suppression operator</source> <target state="translated">Gereksiz gizleme işlecini kaldır</target> <note /> </trans-unit> <trans-unit id="Remove_unnessary_discard"> <source>Remove unnecessary discard</source> <target state="translated">Gereksiz atmayı kaldır</target> <note /> </trans-unit> <trans-unit id="Simplify_default_expression"> <source>Simplify 'default' expression</source> <target state="translated">Default' ifadesini basitleştir</target> <note /> </trans-unit> <trans-unit id="Struct_contains_assignment_to_this_outside_of_constructor_Make_readonly_fields_writable"> <source>Struct contains assignment to 'this' outside of constructor. Make readonly fields writable.</source> <target state="translated">Struct, oluşturucu dışında 'this' öğesine yönelik atama içeriyor. Salt okunur alanları yazılabilir yapın.</target> <note>{Locked="Struct"}{Locked="this"} these are C#/VB keywords and should not be localized.</note> </trans-unit> <trans-unit id="Suppression_operator_has_no_effect_and_can_be_misinterpreted"> <source>Suppression operator has no effect and can be misinterpreted</source> <target state="translated">Gizleme işleci hiçbir etkiye sahip değil ve yanlış yorumlanabilir</target> <note /> </trans-unit> <trans-unit id="Unreachable_code_detected"> <source>Unreachable code detected</source> <target state="translated">Ulaşılamayan kod algılandı</target> <note /> </trans-unit> <trans-unit id="Use_block_body_for_accessors"> <source>Use block body for accessors</source> <target state="translated">Erişimciler için blok gövdesi kullan</target> <note /> </trans-unit> <trans-unit id="Use_block_body_for_constructors"> <source>Use block body for constructors</source> <target state="translated">Oluşturucular için blok gövdesi kullan</target> <note /> </trans-unit> <trans-unit id="Use_block_body_for_indexers"> <source>Use block body for indexers</source> <target state="translated">Dizin oluşturucular için blok gövdesi kullan</target> <note /> </trans-unit> <trans-unit id="Use_block_body_for_local_functions"> <source>Use block body for local functions</source> <target state="translated">Yerel işlevler için blok gövdesi kullan</target> <note /> </trans-unit> <trans-unit id="Use_block_body_for_methods"> <source>Use block body for methods</source> <target state="translated">Metotlar için blok gövdesi kullan</target> <note /> </trans-unit> <trans-unit id="Use_block_body_for_operators"> <source>Use block body for operators</source> <target state="translated">İşleçler için blok gövdesi kullan</target> <note /> </trans-unit> <trans-unit id="Use_block_body_for_properties"> <source>Use block body for properties</source> <target state="translated">Özellikler için blok gövdesi kullan</target> <note /> </trans-unit> <trans-unit id="Use_explicit_type"> <source>Use explicit type</source> <target state="translated">Açık tür kullanma</target> <note /> </trans-unit> <trans-unit id="Use_explicit_type_instead_of_var"> <source>Use explicit type instead of 'var'</source> <target state="translated">Var' yerine açık tür kullan</target> <note /> </trans-unit> <trans-unit id="Use_expression_body_for_accessors"> <source>Use expression body for accessors</source> <target state="translated">Erişimciler için ifade gövdesi kullan</target> <note /> </trans-unit> <trans-unit id="Use_expression_body_for_constructors"> <source>Use expression body for constructors</source> <target state="translated">Oluşturucular için ifade gövdesi kullan</target> <note /> </trans-unit> <trans-unit id="Use_expression_body_for_indexers"> <source>Use expression body for indexers</source> <target state="translated">Dizin oluşturucular için ifade gövdesi kullan</target> <note /> </trans-unit> <trans-unit id="Use_expression_body_for_local_functions"> <source>Use expression body for local functions</source> <target state="translated">Yerel işlevler için ifade gövdesi kullan</target> <note /> </trans-unit> <trans-unit id="Use_expression_body_for_methods"> <source>Use expression body for methods</source> <target state="translated">Metotlar için ifade gövdesi kullan</target> <note /> </trans-unit> <trans-unit id="Use_expression_body_for_operators"> <source>Use expression body for operators</source> <target state="translated">İşleçler için ifade gövdesi kullan</target> <note /> </trans-unit> <trans-unit id="Use_expression_body_for_properties"> <source>Use expression body for properties</source> <target state="translated">Özellikler için ifade gövdesi kullan</target> <note /> </trans-unit> <trans-unit id="Use_implicit_type"> <source>Use implicit type</source> <target state="translated">Örtük tür kullanma</target> <note /> </trans-unit> <trans-unit id="Use_index_operator"> <source>Use index operator</source> <target state="translated">Dizin işleci kullan</target> <note /> </trans-unit> <trans-unit id="Use_is_null_check"> <source>Use 'is null' check</source> <target state="translated">is null' denetimini kullan</target> <note /> </trans-unit> <trans-unit id="Use_local_function"> <source>Use local function</source> <target state="translated">Yerel işlev kullan</target> <note /> </trans-unit> <trans-unit id="Use_new"> <source>Use 'new(...)'</source> <target state="translated">'new(...)' kullanın</target> <note>{Locked="new(...)"} This is a C# construct and should not be localized.</note> </trans-unit> <trans-unit id="Use_pattern_matching"> <source>Use pattern matching</source> <target state="translated">Desen eşleştirme kullan</target> <note /> </trans-unit> <trans-unit id="Use_pattern_matching_may_change_code_meaning"> <source>Use pattern matching (may change code meaning)</source> <target state="new">Use pattern matching (may change code meaning)</target> <note /> </trans-unit> <trans-unit id="Use_range_operator"> <source>Use range operator</source> <target state="translated">Aralık işleci kullan</target> <note /> </trans-unit> <trans-unit id="Use_simple_using_statement"> <source>Use simple 'using' statement</source> <target state="translated">Basit 'using' deyimini kullan</target> <note /> </trans-unit> <trans-unit id="Use_switch_expression"> <source>Use 'switch' expression</source> <target state="translated">'Switch' ifadesini kullan</target> <note /> </trans-unit> <trans-unit id="Using_directives_must_be_placed_inside_of_a_namespace_declaration"> <source>Using directives must be placed inside of a namespace declaration</source> <target state="translated">Using yönergelerinin bir namespace bildiriminin içine yerleştirilmesi gerekir</target> <note>{Locked="using"} "using" is a C# keyword and should not be localized. {Locked="namespace"} "namespace" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="Using_directives_must_be_placed_outside_of_a_namespace_declaration"> <source>Using directives must be placed outside of a namespace declaration</source> <target state="translated">Using yönergelerinin bir namespace bildiriminin dışına yerleştirilmesi gerekir</target> <note>{Locked="using"} "using" is a C# keyword and should not be localized. {Locked="namespace"} "namespace" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="Variable_declaration_can_be_deconstructed"> <source>Variable declaration can be deconstructed</source> <target state="translated">Değişken bildirimi ayrıştırılabilir</target> <note /> </trans-unit> <trans-unit id="Variable_declaration_can_be_inlined"> <source>Variable declaration can be inlined</source> <target state="translated">Değişken bildirimi satır içine alınabilir</target> <note /> </trans-unit> <trans-unit id="Warning_colon_Moving_using_directives_may_change_code_meaning"> <source>Warning: Moving using directives may change code meaning.</source> <target state="translated">Uyarı: using yönergelerini taşımak, kodun anlamını değiştirebilir.</target> <note>{Locked="using"} "using" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="_0_can_be_simplified"> <source>{0} can be simplified</source> <target state="translated">{0} basitleştirilebilir</target> <note /> </trans-unit> <trans-unit id="default_expression_can_be_simplified"> <source>'default' expression can be simplified</source> <target state="translated">'default' ifadesi basitleştirilebilir</target> <note /> </trans-unit> <trans-unit id="if_statement_can_be_simplified"> <source>'if' statement can be simplified</source> <target state="translated">'If' deyimi basitleştirilebilir</target> <note /> </trans-unit> <trans-unit id="new_expression_can_be_simplified"> <source>'new' expression can be simplified</source> <target state="translated">'new' ifadesi basitleştirilebilir</target> <note /> </trans-unit> <trans-unit id="typeof_can_be_converted_ to_nameof"> <source>'typeof' can be converted to 'nameof'</source> <target state="translated">'typeof' metodu 'nameof' metoduna dönüştürülebilir</target> <note /> </trans-unit> <trans-unit id="use_var_instead_of_explicit_type"> <source>use 'var' instead of explicit type</source> <target state="translated">açık tür yerine 'var' kullan</target> <note /> </trans-unit> <trans-unit id="Using_directive_is_unnecessary"> <source>Using directive is unnecessary.</source> <target state="translated">Using yönergesi gerekli değildir.</target> <note /> </trans-unit> <trans-unit id="using_statement_can_be_simplified"> <source>'using' statement can be simplified</source> <target state="translated">'using' deyimi basitleştirilebilir</target> <note /> </trans-unit> </body> </file> </xliff>
1
dotnet/roslyn
55,427
Fixes #50462
Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
Blokyk
2021-08-05T01:17:37Z
2021-08-25T05:42:59Z
fefb8c2110625bc4908db4bbdaa367b12bfb1069
fb4ac545a1f1f365e7df570637699d9085ea4f87
Fixes #50462. Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
./src/Analyzers/CSharp/Analyzers/xlf/CSharpAnalyzersResources.zh-Hans.xlf
<?xml version="1.0" encoding="utf-8"?> <xliff xmlns="urn:oasis:names:tc:xliff:document:1.2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="1.2" xsi:schemaLocation="urn:oasis:names:tc:xliff:document:1.2 xliff-core-1.2-transitional.xsd"> <file datatype="xml" source-language="en" target-language="zh-Hans" original="../CSharpAnalyzersResources.resx"> <body> <trans-unit id="Add_braces"> <source>Add braces</source> <target state="translated">添加大括号</target> <note /> </trans-unit> <trans-unit id="Add_braces_to_0_statement"> <source>Add braces to '{0}' statement.</source> <target state="translated">向 “{0}” 语句添加大括号。</target> <note /> </trans-unit> <trans-unit id="Blank_line_not_allowed_after_constructor_initializer_colon"> <source>Blank line not allowed after constructor initializer colon</source> <target state="translated">构造函数初始值设定项冒号后面不允许有空白行</target> <note /> </trans-unit> <trans-unit id="Consecutive_braces_must_not_have_a_blank_between_them"> <source>Consecutive braces must not have blank line between them</source> <target state="translated">连续大括号之间不能有空白行</target> <note /> </trans-unit> <trans-unit id="Convert_switch_statement_to_expression"> <source>Convert switch statement to expression</source> <target state="translated">将 switch 语句转换为表达式</target> <note /> </trans-unit> <trans-unit id="Convert_to_block_scoped_namespace"> <source>Convert to block scoped namespace</source> <target state="new">Convert to block scoped namespace</target> <note>{Locked="namespace"} "namespace" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="Convert_to_file_scoped_namespace"> <source>Convert to file-scoped namespace</source> <target state="new">Convert to file-scoped namespace</target> <note>{Locked="namespace"} "namespace" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="Deconstruct_variable_declaration"> <source>Deconstruct variable declaration</source> <target state="translated">析构变量声明</target> <note /> </trans-unit> <trans-unit id="Delegate_invocation_can_be_simplified"> <source>Delegate invocation can be simplified.</source> <target state="translated">可简化委托调用。</target> <note /> </trans-unit> <trans-unit id="Discard_can_be_removed"> <source>Discard can be removed</source> <target state="translated">可删除放弃项</target> <note /> </trans-unit> <trans-unit id="Embedded_statements_must_be_on_their_own_line"> <source>Embedded statements must be on their own line</source> <target state="translated">嵌入的语句必须放在其自己的行上</target> <note /> </trans-unit> <trans-unit id="Indexing_can_be_simplified"> <source>Indexing can be simplified</source> <target state="translated">索引可以简化</target> <note /> </trans-unit> <trans-unit id="Inline_variable_declaration"> <source>Inline variable declaration</source> <target state="translated">内联变量声明</target> <note /> </trans-unit> <trans-unit id="Misplaced_using_directive"> <source>Misplaced using directive</source> <target state="translated">错放了 using 指令</target> <note>{Locked="using"} "using" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="Move_misplaced_using_directives"> <source>Move misplaced using directives</source> <target state="translated">移动错放的 using 指令</target> <note>{Locked="using"} "using" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="Make_readonly_fields_writable"> <source>Make readonly fields writable</source> <target state="translated">使 readonly 字段可写</target> <note>{Locked="readonly"} "readonly" is C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="Local_function_can_be_made_static"> <source>Local function can be made static</source> <target state="translated">可以使本地函数成为静态函数</target> <note /> </trans-unit> <trans-unit id="Make_local_function_static"> <source>Make local function 'static'</source> <target state="translated">使本地函数成为静态函数</target> <note /> </trans-unit> <trans-unit id="Negate_expression_changes_semantics"> <source>Negate expression (changes semantics)</source> <target state="translated">使用求反表达式(更改语义)</target> <note /> </trans-unit> <trans-unit id="Null_check_can_be_clarified"> <source>Null check can be clarified</source> <target state="new">Null check can be clarified</target> <note /> </trans-unit> <trans-unit id="Prefer_null_check_over_type_check"> <source>Prefer 'null' check over type check</source> <target state="new">Prefer 'null' check over type check</target> <note /> </trans-unit> <trans-unit id="Remove_operator_preserves_semantics"> <source>Remove operator (preserves semantics)</source> <target state="translated">删除运算符(保留语义)</target> <note /> </trans-unit> <trans-unit id="Remove_suppression_operators"> <source>Remove suppression operators</source> <target state="translated">请删除忽略运算符</target> <note /> </trans-unit> <trans-unit id="Remove_unnecessary_suppression_operator"> <source>Remove unnecessary suppression operator</source> <target state="translated">请删除不必要的忽略运算符</target> <note /> </trans-unit> <trans-unit id="Remove_unnessary_discard"> <source>Remove unnecessary discard</source> <target state="translated">删除不必要的放弃项</target> <note /> </trans-unit> <trans-unit id="Simplify_default_expression"> <source>Simplify 'default' expression</source> <target state="translated">简化 "default" 表达式</target> <note /> </trans-unit> <trans-unit id="Struct_contains_assignment_to_this_outside_of_constructor_Make_readonly_fields_writable"> <source>Struct contains assignment to 'this' outside of constructor. Make readonly fields writable.</source> <target state="translated">Struct 包含对构造函数之外的 "this" 的赋值。使只读字段可写。</target> <note>{Locked="Struct"}{Locked="this"} these are C#/VB keywords and should not be localized.</note> </trans-unit> <trans-unit id="Suppression_operator_has_no_effect_and_can_be_misinterpreted"> <source>Suppression operator has no effect and can be misinterpreted</source> <target state="translated">抑制运算符不起任何作用且可能被误解</target> <note /> </trans-unit> <trans-unit id="Unreachable_code_detected"> <source>Unreachable code detected</source> <target state="translated">检测到无法访问的代码</target> <note /> </trans-unit> <trans-unit id="Use_block_body_for_accessors"> <source>Use block body for accessors</source> <target state="translated">使用访问器的程序块主体</target> <note /> </trans-unit> <trans-unit id="Use_block_body_for_constructors"> <source>Use block body for constructors</source> <target state="translated">使用构造函数的程序块主体</target> <note /> </trans-unit> <trans-unit id="Use_block_body_for_indexers"> <source>Use block body for indexers</source> <target state="translated">使用索引器的程序块主体</target> <note /> </trans-unit> <trans-unit id="Use_block_body_for_local_functions"> <source>Use block body for local functions</source> <target state="translated">对本地函数使用块主体</target> <note /> </trans-unit> <trans-unit id="Use_block_body_for_methods"> <source>Use block body for methods</source> <target state="translated">使用方法的程序块主体</target> <note /> </trans-unit> <trans-unit id="Use_block_body_for_operators"> <source>Use block body for operators</source> <target state="translated">使用运算符的程序块主体</target> <note /> </trans-unit> <trans-unit id="Use_block_body_for_properties"> <source>Use block body for properties</source> <target state="translated">使用属性的程序块主体</target> <note /> </trans-unit> <trans-unit id="Use_explicit_type"> <source>Use explicit type</source> <target state="translated">使用显式类型</target> <note /> </trans-unit> <trans-unit id="Use_explicit_type_instead_of_var"> <source>Use explicit type instead of 'var'</source> <target state="translated">用显式类型代替 "var"</target> <note /> </trans-unit> <trans-unit id="Use_expression_body_for_accessors"> <source>Use expression body for accessors</source> <target state="translated">使用访问器的表达式主体</target> <note /> </trans-unit> <trans-unit id="Use_expression_body_for_constructors"> <source>Use expression body for constructors</source> <target state="translated">使用构造函数的表达式主体</target> <note /> </trans-unit> <trans-unit id="Use_expression_body_for_indexers"> <source>Use expression body for indexers</source> <target state="translated">使用索引器的表达式主体</target> <note /> </trans-unit> <trans-unit id="Use_expression_body_for_local_functions"> <source>Use expression body for local functions</source> <target state="translated">将表达式主体用于本地函数</target> <note /> </trans-unit> <trans-unit id="Use_expression_body_for_methods"> <source>Use expression body for methods</source> <target state="translated">使用方法的表达式主体</target> <note /> </trans-unit> <trans-unit id="Use_expression_body_for_operators"> <source>Use expression body for operators</source> <target state="translated">使用运算符的表达式主体</target> <note /> </trans-unit> <trans-unit id="Use_expression_body_for_properties"> <source>Use expression body for properties</source> <target state="translated">使用属性的表达式主体</target> <note /> </trans-unit> <trans-unit id="Use_implicit_type"> <source>Use implicit type</source> <target state="translated">使用隐式类型</target> <note /> </trans-unit> <trans-unit id="Use_index_operator"> <source>Use index operator</source> <target state="translated">使用索引运算符</target> <note /> </trans-unit> <trans-unit id="Use_is_null_check"> <source>Use 'is null' check</source> <target state="translated">使用 "is null" 检查</target> <note /> </trans-unit> <trans-unit id="Use_local_function"> <source>Use local function</source> <target state="translated">使用本地函数</target> <note /> </trans-unit> <trans-unit id="Use_new"> <source>Use 'new(...)'</source> <target state="translated">使用 "new(...)"</target> <note>{Locked="new(...)"} This is a C# construct and should not be localized.</note> </trans-unit> <trans-unit id="Use_pattern_matching"> <source>Use pattern matching</source> <target state="translated">使用模式匹配</target> <note /> </trans-unit> <trans-unit id="Use_range_operator"> <source>Use range operator</source> <target state="translated">使用范围运算符</target> <note /> </trans-unit> <trans-unit id="Use_simple_using_statement"> <source>Use simple 'using' statement</source> <target state="translated">使用简单的 "using" 语句</target> <note /> </trans-unit> <trans-unit id="Use_switch_expression"> <source>Use 'switch' expression</source> <target state="translated">使用 "switch" 表达式</target> <note /> </trans-unit> <trans-unit id="Using_directives_must_be_placed_inside_of_a_namespace_declaration"> <source>Using directives must be placed inside of a namespace declaration</source> <target state="translated">using 指令必须放在 namespace 声明的内部</target> <note>{Locked="using"} "using" is a C# keyword and should not be localized. {Locked="namespace"} "namespace" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="Using_directives_must_be_placed_outside_of_a_namespace_declaration"> <source>Using directives must be placed outside of a namespace declaration</source> <target state="translated">using 指令必须放在 namespace 声明之外</target> <note>{Locked="using"} "using" is a C# keyword and should not be localized. {Locked="namespace"} "namespace" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="Variable_declaration_can_be_deconstructed"> <source>Variable declaration can be deconstructed</source> <target state="translated">可以析构变量声明</target> <note /> </trans-unit> <trans-unit id="Variable_declaration_can_be_inlined"> <source>Variable declaration can be inlined</source> <target state="translated">可以内联变量声明</target> <note /> </trans-unit> <trans-unit id="Warning_colon_Moving_using_directives_may_change_code_meaning"> <source>Warning: Moving using directives may change code meaning.</source> <target state="translated">警告: 移动 using 指令可能会更改代码含义。</target> <note>{Locked="using"} "using" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="_0_can_be_simplified"> <source>{0} can be simplified</source> <target state="translated">{0} 可以简化</target> <note /> </trans-unit> <trans-unit id="default_expression_can_be_simplified"> <source>'default' expression can be simplified</source> <target state="translated">可以简化 "default" 表达式</target> <note /> </trans-unit> <trans-unit id="if_statement_can_be_simplified"> <source>'if' statement can be simplified</source> <target state="translated">可简化 "if" 语句</target> <note /> </trans-unit> <trans-unit id="new_expression_can_be_simplified"> <source>'new' expression can be simplified</source> <target state="translated">可简化 "new" 表达式</target> <note /> </trans-unit> <trans-unit id="typeof_can_be_converted_ to_nameof"> <source>'typeof' can be converted to 'nameof'</source> <target state="translated">"typeof" 可以转换为 "nameof"</target> <note /> </trans-unit> <trans-unit id="use_var_instead_of_explicit_type"> <source>use 'var' instead of explicit type</source> <target state="translated">用 "var" 代替显式类型</target> <note /> </trans-unit> <trans-unit id="Using_directive_is_unnecessary"> <source>Using directive is unnecessary.</source> <target state="translated">Using 指令是不需要的。</target> <note /> </trans-unit> <trans-unit id="using_statement_can_be_simplified"> <source>'using' statement can be simplified</source> <target state="translated">可简化 "using" 语句</target> <note /> </trans-unit> </body> </file> </xliff>
<?xml version="1.0" encoding="utf-8"?> <xliff xmlns="urn:oasis:names:tc:xliff:document:1.2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="1.2" xsi:schemaLocation="urn:oasis:names:tc:xliff:document:1.2 xliff-core-1.2-transitional.xsd"> <file datatype="xml" source-language="en" target-language="zh-Hans" original="../CSharpAnalyzersResources.resx"> <body> <trans-unit id="Add_braces"> <source>Add braces</source> <target state="translated">添加大括号</target> <note /> </trans-unit> <trans-unit id="Add_braces_to_0_statement"> <source>Add braces to '{0}' statement.</source> <target state="translated">向 “{0}” 语句添加大括号。</target> <note /> </trans-unit> <trans-unit id="Blank_line_not_allowed_after_constructor_initializer_colon"> <source>Blank line not allowed after constructor initializer colon</source> <target state="translated">构造函数初始值设定项冒号后面不允许有空白行</target> <note /> </trans-unit> <trans-unit id="Consecutive_braces_must_not_have_a_blank_between_them"> <source>Consecutive braces must not have blank line between them</source> <target state="translated">连续大括号之间不能有空白行</target> <note /> </trans-unit> <trans-unit id="Convert_switch_statement_to_expression"> <source>Convert switch statement to expression</source> <target state="translated">将 switch 语句转换为表达式</target> <note /> </trans-unit> <trans-unit id="Convert_to_block_scoped_namespace"> <source>Convert to block scoped namespace</source> <target state="new">Convert to block scoped namespace</target> <note>{Locked="namespace"} "namespace" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="Convert_to_file_scoped_namespace"> <source>Convert to file-scoped namespace</source> <target state="new">Convert to file-scoped namespace</target> <note>{Locked="namespace"} "namespace" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="Deconstruct_variable_declaration"> <source>Deconstruct variable declaration</source> <target state="translated">析构变量声明</target> <note /> </trans-unit> <trans-unit id="Delegate_invocation_can_be_simplified"> <source>Delegate invocation can be simplified.</source> <target state="translated">可简化委托调用。</target> <note /> </trans-unit> <trans-unit id="Discard_can_be_removed"> <source>Discard can be removed</source> <target state="translated">可删除放弃项</target> <note /> </trans-unit> <trans-unit id="Embedded_statements_must_be_on_their_own_line"> <source>Embedded statements must be on their own line</source> <target state="translated">嵌入的语句必须放在其自己的行上</target> <note /> </trans-unit> <trans-unit id="Indexing_can_be_simplified"> <source>Indexing can be simplified</source> <target state="translated">索引可以简化</target> <note /> </trans-unit> <trans-unit id="Inline_variable_declaration"> <source>Inline variable declaration</source> <target state="translated">内联变量声明</target> <note /> </trans-unit> <trans-unit id="Misplaced_using_directive"> <source>Misplaced using directive</source> <target state="translated">错放了 using 指令</target> <note>{Locked="using"} "using" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="Move_misplaced_using_directives"> <source>Move misplaced using directives</source> <target state="translated">移动错放的 using 指令</target> <note>{Locked="using"} "using" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="Make_readonly_fields_writable"> <source>Make readonly fields writable</source> <target state="translated">使 readonly 字段可写</target> <note>{Locked="readonly"} "readonly" is C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="Local_function_can_be_made_static"> <source>Local function can be made static</source> <target state="translated">可以使本地函数成为静态函数</target> <note /> </trans-unit> <trans-unit id="Make_local_function_static"> <source>Make local function 'static'</source> <target state="translated">使本地函数成为静态函数</target> <note /> </trans-unit> <trans-unit id="Negate_expression_changes_semantics"> <source>Negate expression (changes semantics)</source> <target state="translated">使用求反表达式(更改语义)</target> <note /> </trans-unit> <trans-unit id="Null_check_can_be_clarified"> <source>Null check can be clarified</source> <target state="new">Null check can be clarified</target> <note /> </trans-unit> <trans-unit id="Prefer_null_check_over_type_check"> <source>Prefer 'null' check over type check</source> <target state="new">Prefer 'null' check over type check</target> <note /> </trans-unit> <trans-unit id="Remove_operator_preserves_semantics"> <source>Remove operator (preserves semantics)</source> <target state="translated">删除运算符(保留语义)</target> <note /> </trans-unit> <trans-unit id="Remove_suppression_operators"> <source>Remove suppression operators</source> <target state="translated">请删除忽略运算符</target> <note /> </trans-unit> <trans-unit id="Remove_unnecessary_suppression_operator"> <source>Remove unnecessary suppression operator</source> <target state="translated">请删除不必要的忽略运算符</target> <note /> </trans-unit> <trans-unit id="Remove_unnessary_discard"> <source>Remove unnecessary discard</source> <target state="translated">删除不必要的放弃项</target> <note /> </trans-unit> <trans-unit id="Simplify_default_expression"> <source>Simplify 'default' expression</source> <target state="translated">简化 "default" 表达式</target> <note /> </trans-unit> <trans-unit id="Struct_contains_assignment_to_this_outside_of_constructor_Make_readonly_fields_writable"> <source>Struct contains assignment to 'this' outside of constructor. Make readonly fields writable.</source> <target state="translated">Struct 包含对构造函数之外的 "this" 的赋值。使只读字段可写。</target> <note>{Locked="Struct"}{Locked="this"} these are C#/VB keywords and should not be localized.</note> </trans-unit> <trans-unit id="Suppression_operator_has_no_effect_and_can_be_misinterpreted"> <source>Suppression operator has no effect and can be misinterpreted</source> <target state="translated">抑制运算符不起任何作用且可能被误解</target> <note /> </trans-unit> <trans-unit id="Unreachable_code_detected"> <source>Unreachable code detected</source> <target state="translated">检测到无法访问的代码</target> <note /> </trans-unit> <trans-unit id="Use_block_body_for_accessors"> <source>Use block body for accessors</source> <target state="translated">使用访问器的程序块主体</target> <note /> </trans-unit> <trans-unit id="Use_block_body_for_constructors"> <source>Use block body for constructors</source> <target state="translated">使用构造函数的程序块主体</target> <note /> </trans-unit> <trans-unit id="Use_block_body_for_indexers"> <source>Use block body for indexers</source> <target state="translated">使用索引器的程序块主体</target> <note /> </trans-unit> <trans-unit id="Use_block_body_for_local_functions"> <source>Use block body for local functions</source> <target state="translated">对本地函数使用块主体</target> <note /> </trans-unit> <trans-unit id="Use_block_body_for_methods"> <source>Use block body for methods</source> <target state="translated">使用方法的程序块主体</target> <note /> </trans-unit> <trans-unit id="Use_block_body_for_operators"> <source>Use block body for operators</source> <target state="translated">使用运算符的程序块主体</target> <note /> </trans-unit> <trans-unit id="Use_block_body_for_properties"> <source>Use block body for properties</source> <target state="translated">使用属性的程序块主体</target> <note /> </trans-unit> <trans-unit id="Use_explicit_type"> <source>Use explicit type</source> <target state="translated">使用显式类型</target> <note /> </trans-unit> <trans-unit id="Use_explicit_type_instead_of_var"> <source>Use explicit type instead of 'var'</source> <target state="translated">用显式类型代替 "var"</target> <note /> </trans-unit> <trans-unit id="Use_expression_body_for_accessors"> <source>Use expression body for accessors</source> <target state="translated">使用访问器的表达式主体</target> <note /> </trans-unit> <trans-unit id="Use_expression_body_for_constructors"> <source>Use expression body for constructors</source> <target state="translated">使用构造函数的表达式主体</target> <note /> </trans-unit> <trans-unit id="Use_expression_body_for_indexers"> <source>Use expression body for indexers</source> <target state="translated">使用索引器的表达式主体</target> <note /> </trans-unit> <trans-unit id="Use_expression_body_for_local_functions"> <source>Use expression body for local functions</source> <target state="translated">将表达式主体用于本地函数</target> <note /> </trans-unit> <trans-unit id="Use_expression_body_for_methods"> <source>Use expression body for methods</source> <target state="translated">使用方法的表达式主体</target> <note /> </trans-unit> <trans-unit id="Use_expression_body_for_operators"> <source>Use expression body for operators</source> <target state="translated">使用运算符的表达式主体</target> <note /> </trans-unit> <trans-unit id="Use_expression_body_for_properties"> <source>Use expression body for properties</source> <target state="translated">使用属性的表达式主体</target> <note /> </trans-unit> <trans-unit id="Use_implicit_type"> <source>Use implicit type</source> <target state="translated">使用隐式类型</target> <note /> </trans-unit> <trans-unit id="Use_index_operator"> <source>Use index operator</source> <target state="translated">使用索引运算符</target> <note /> </trans-unit> <trans-unit id="Use_is_null_check"> <source>Use 'is null' check</source> <target state="translated">使用 "is null" 检查</target> <note /> </trans-unit> <trans-unit id="Use_local_function"> <source>Use local function</source> <target state="translated">使用本地函数</target> <note /> </trans-unit> <trans-unit id="Use_new"> <source>Use 'new(...)'</source> <target state="translated">使用 "new(...)"</target> <note>{Locked="new(...)"} This is a C# construct and should not be localized.</note> </trans-unit> <trans-unit id="Use_pattern_matching"> <source>Use pattern matching</source> <target state="translated">使用模式匹配</target> <note /> </trans-unit> <trans-unit id="Use_pattern_matching_may_change_code_meaning"> <source>Use pattern matching (may change code meaning)</source> <target state="new">Use pattern matching (may change code meaning)</target> <note /> </trans-unit> <trans-unit id="Use_range_operator"> <source>Use range operator</source> <target state="translated">使用范围运算符</target> <note /> </trans-unit> <trans-unit id="Use_simple_using_statement"> <source>Use simple 'using' statement</source> <target state="translated">使用简单的 "using" 语句</target> <note /> </trans-unit> <trans-unit id="Use_switch_expression"> <source>Use 'switch' expression</source> <target state="translated">使用 "switch" 表达式</target> <note /> </trans-unit> <trans-unit id="Using_directives_must_be_placed_inside_of_a_namespace_declaration"> <source>Using directives must be placed inside of a namespace declaration</source> <target state="translated">using 指令必须放在 namespace 声明的内部</target> <note>{Locked="using"} "using" is a C# keyword and should not be localized. {Locked="namespace"} "namespace" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="Using_directives_must_be_placed_outside_of_a_namespace_declaration"> <source>Using directives must be placed outside of a namespace declaration</source> <target state="translated">using 指令必须放在 namespace 声明之外</target> <note>{Locked="using"} "using" is a C# keyword and should not be localized. {Locked="namespace"} "namespace" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="Variable_declaration_can_be_deconstructed"> <source>Variable declaration can be deconstructed</source> <target state="translated">可以析构变量声明</target> <note /> </trans-unit> <trans-unit id="Variable_declaration_can_be_inlined"> <source>Variable declaration can be inlined</source> <target state="translated">可以内联变量声明</target> <note /> </trans-unit> <trans-unit id="Warning_colon_Moving_using_directives_may_change_code_meaning"> <source>Warning: Moving using directives may change code meaning.</source> <target state="translated">警告: 移动 using 指令可能会更改代码含义。</target> <note>{Locked="using"} "using" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="_0_can_be_simplified"> <source>{0} can be simplified</source> <target state="translated">{0} 可以简化</target> <note /> </trans-unit> <trans-unit id="default_expression_can_be_simplified"> <source>'default' expression can be simplified</source> <target state="translated">可以简化 "default" 表达式</target> <note /> </trans-unit> <trans-unit id="if_statement_can_be_simplified"> <source>'if' statement can be simplified</source> <target state="translated">可简化 "if" 语句</target> <note /> </trans-unit> <trans-unit id="new_expression_can_be_simplified"> <source>'new' expression can be simplified</source> <target state="translated">可简化 "new" 表达式</target> <note /> </trans-unit> <trans-unit id="typeof_can_be_converted_ to_nameof"> <source>'typeof' can be converted to 'nameof'</source> <target state="translated">"typeof" 可以转换为 "nameof"</target> <note /> </trans-unit> <trans-unit id="use_var_instead_of_explicit_type"> <source>use 'var' instead of explicit type</source> <target state="translated">用 "var" 代替显式类型</target> <note /> </trans-unit> <trans-unit id="Using_directive_is_unnecessary"> <source>Using directive is unnecessary.</source> <target state="translated">Using 指令是不需要的。</target> <note /> </trans-unit> <trans-unit id="using_statement_can_be_simplified"> <source>'using' statement can be simplified</source> <target state="translated">可简化 "using" 语句</target> <note /> </trans-unit> </body> </file> </xliff>
1
dotnet/roslyn
55,427
Fixes #50462
Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
Blokyk
2021-08-05T01:17:37Z
2021-08-25T05:42:59Z
fefb8c2110625bc4908db4bbdaa367b12bfb1069
fb4ac545a1f1f365e7df570637699d9085ea4f87
Fixes #50462. Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
./src/Analyzers/CSharp/Analyzers/xlf/CSharpAnalyzersResources.zh-Hant.xlf
<?xml version="1.0" encoding="utf-8"?> <xliff xmlns="urn:oasis:names:tc:xliff:document:1.2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="1.2" xsi:schemaLocation="urn:oasis:names:tc:xliff:document:1.2 xliff-core-1.2-transitional.xsd"> <file datatype="xml" source-language="en" target-language="zh-Hant" original="../CSharpAnalyzersResources.resx"> <body> <trans-unit id="Add_braces"> <source>Add braces</source> <target state="translated">加入大括號</target> <note /> </trans-unit> <trans-unit id="Add_braces_to_0_statement"> <source>Add braces to '{0}' statement.</source> <target state="translated">為 '{0}' 陳述式加入大括號。</target> <note /> </trans-unit> <trans-unit id="Blank_line_not_allowed_after_constructor_initializer_colon"> <source>Blank line not allowed after constructor initializer colon</source> <target state="translated">不允許在建構函式初始設定式冒號後加上空白行</target> <note /> </trans-unit> <trans-unit id="Consecutive_braces_must_not_have_a_blank_between_them"> <source>Consecutive braces must not have blank line between them</source> <target state="translated">連續大括弧之間不能有空白行</target> <note /> </trans-unit> <trans-unit id="Convert_switch_statement_to_expression"> <source>Convert switch statement to expression</source> <target state="translated">將 switch 陳述式轉換為運算式</target> <note /> </trans-unit> <trans-unit id="Convert_to_block_scoped_namespace"> <source>Convert to block scoped namespace</source> <target state="new">Convert to block scoped namespace</target> <note>{Locked="namespace"} "namespace" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="Convert_to_file_scoped_namespace"> <source>Convert to file-scoped namespace</source> <target state="new">Convert to file-scoped namespace</target> <note>{Locked="namespace"} "namespace" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="Deconstruct_variable_declaration"> <source>Deconstruct variable declaration</source> <target state="translated">解構變數宣告</target> <note /> </trans-unit> <trans-unit id="Delegate_invocation_can_be_simplified"> <source>Delegate invocation can be simplified.</source> <target state="translated">可以簡化委派引動的過程。</target> <note /> </trans-unit> <trans-unit id="Discard_can_be_removed"> <source>Discard can be removed</source> <target state="translated">可以移除捨棄</target> <note /> </trans-unit> <trans-unit id="Embedded_statements_must_be_on_their_own_line"> <source>Embedded statements must be on their own line</source> <target state="translated">內嵌陳述式必須位於自己的行中</target> <note /> </trans-unit> <trans-unit id="Indexing_can_be_simplified"> <source>Indexing can be simplified</source> <target state="translated">可簡化索引</target> <note /> </trans-unit> <trans-unit id="Inline_variable_declaration"> <source>Inline variable declaration</source> <target state="translated">內嵌變數宣告</target> <note /> </trans-unit> <trans-unit id="Misplaced_using_directive"> <source>Misplaced using directive</source> <target state="translated">using 指示詞位置錯誤</target> <note>{Locked="using"} "using" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="Move_misplaced_using_directives"> <source>Move misplaced using directives</source> <target state="translated">移動位置錯誤的 using 指示詞</target> <note>{Locked="using"} "using" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="Make_readonly_fields_writable"> <source>Make readonly fields writable</source> <target state="translated">將 readonly 欄位設為可寫入</target> <note>{Locked="readonly"} "readonly" is C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="Local_function_can_be_made_static"> <source>Local function can be made static</source> <target state="translated">區域函式可以變成靜態</target> <note /> </trans-unit> <trans-unit id="Make_local_function_static"> <source>Make local function 'static'</source> <target state="translated">將區域函式設為 'static'</target> <note /> </trans-unit> <trans-unit id="Negate_expression_changes_semantics"> <source>Negate expression (changes semantics)</source> <target state="translated">否定運算式 (變更語義)</target> <note /> </trans-unit> <trans-unit id="Null_check_can_be_clarified"> <source>Null check can be clarified</source> <target state="new">Null check can be clarified</target> <note /> </trans-unit> <trans-unit id="Prefer_null_check_over_type_check"> <source>Prefer 'null' check over type check</source> <target state="new">Prefer 'null' check over type check</target> <note /> </trans-unit> <trans-unit id="Remove_operator_preserves_semantics"> <source>Remove operator (preserves semantics)</source> <target state="translated">移除運算子 (保留語義)</target> <note /> </trans-unit> <trans-unit id="Remove_suppression_operators"> <source>Remove suppression operators</source> <target state="translated">移除隱藏的運算子</target> <note /> </trans-unit> <trans-unit id="Remove_unnecessary_suppression_operator"> <source>Remove unnecessary suppression operator</source> <target state="translated">移除隱藏運算子中不需要的運算子</target> <note /> </trans-unit> <trans-unit id="Remove_unnessary_discard"> <source>Remove unnecessary discard</source> <target state="translated">移除不必要的捨棄</target> <note /> </trans-unit> <trans-unit id="Simplify_default_expression"> <source>Simplify 'default' expression</source> <target state="translated">簡化 'default' 運算式</target> <note /> </trans-unit> <trans-unit id="Struct_contains_assignment_to_this_outside_of_constructor_Make_readonly_fields_writable"> <source>Struct contains assignment to 'this' outside of constructor. Make readonly fields writable.</source> <target state="translated">Struct 包含建構函式外對 'this' 的指派。請將唯讀欄位設為可寫入。</target> <note>{Locked="Struct"}{Locked="this"} these are C#/VB keywords and should not be localized.</note> </trans-unit> <trans-unit id="Suppression_operator_has_no_effect_and_can_be_misinterpreted"> <source>Suppression operator has no effect and can be misinterpreted</source> <target state="translated">隱藏運算子沒有作用,而且可能會造成誤解</target> <note /> </trans-unit> <trans-unit id="Unreachable_code_detected"> <source>Unreachable code detected</source> <target state="translated">偵測到執行不到的程式碼</target> <note /> </trans-unit> <trans-unit id="Use_block_body_for_accessors"> <source>Use block body for accessors</source> <target state="translated">使用存取子的區塊主體</target> <note /> </trans-unit> <trans-unit id="Use_block_body_for_constructors"> <source>Use block body for constructors</source> <target state="translated">使用建構函式的區塊主體</target> <note /> </trans-unit> <trans-unit id="Use_block_body_for_indexers"> <source>Use block body for indexers</source> <target state="translated">使用索引子的區塊主體</target> <note /> </trans-unit> <trans-unit id="Use_block_body_for_local_functions"> <source>Use block body for local functions</source> <target state="translated">為區域函式使用區塊主體</target> <note /> </trans-unit> <trans-unit id="Use_block_body_for_methods"> <source>Use block body for methods</source> <target state="translated">使用方法的區塊主體</target> <note /> </trans-unit> <trans-unit id="Use_block_body_for_operators"> <source>Use block body for operators</source> <target state="translated">使用運算子的區塊主體</target> <note /> </trans-unit> <trans-unit id="Use_block_body_for_properties"> <source>Use block body for properties</source> <target state="translated">使用屬性的區塊主體</target> <note /> </trans-unit> <trans-unit id="Use_explicit_type"> <source>Use explicit type</source> <target state="translated">使用明確類型</target> <note /> </trans-unit> <trans-unit id="Use_explicit_type_instead_of_var"> <source>Use explicit type instead of 'var'</source> <target state="translated">使用明確類型,而非 'var'</target> <note /> </trans-unit> <trans-unit id="Use_expression_body_for_accessors"> <source>Use expression body for accessors</source> <target state="translated">使用存取子的運算式主體</target> <note /> </trans-unit> <trans-unit id="Use_expression_body_for_constructors"> <source>Use expression body for constructors</source> <target state="translated">使用建構函式的運算式主體</target> <note /> </trans-unit> <trans-unit id="Use_expression_body_for_indexers"> <source>Use expression body for indexers</source> <target state="translated">使用索引子的運算式主體</target> <note /> </trans-unit> <trans-unit id="Use_expression_body_for_local_functions"> <source>Use expression body for local functions</source> <target state="translated">為區域函式使用運算式主體</target> <note /> </trans-unit> <trans-unit id="Use_expression_body_for_methods"> <source>Use expression body for methods</source> <target state="translated">使用方法的運算式主體</target> <note /> </trans-unit> <trans-unit id="Use_expression_body_for_operators"> <source>Use expression body for operators</source> <target state="translated">使用運算子的運算式主體</target> <note /> </trans-unit> <trans-unit id="Use_expression_body_for_properties"> <source>Use expression body for properties</source> <target state="translated">使用屬性的運算式主體</target> <note /> </trans-unit> <trans-unit id="Use_implicit_type"> <source>Use implicit type</source> <target state="translated">使用隱含類型</target> <note /> </trans-unit> <trans-unit id="Use_index_operator"> <source>Use index operator</source> <target state="translated">使用索引運算子</target> <note /> </trans-unit> <trans-unit id="Use_is_null_check"> <source>Use 'is null' check</source> <target state="translated">使用 'is null' 檢查</target> <note /> </trans-unit> <trans-unit id="Use_local_function"> <source>Use local function</source> <target state="translated">使用區域函式</target> <note /> </trans-unit> <trans-unit id="Use_new"> <source>Use 'new(...)'</source> <target state="translated">使用 'new(...)'</target> <note>{Locked="new(...)"} This is a C# construct and should not be localized.</note> </trans-unit> <trans-unit id="Use_pattern_matching"> <source>Use pattern matching</source> <target state="translated">使用模式比對</target> <note /> </trans-unit> <trans-unit id="Use_range_operator"> <source>Use range operator</source> <target state="translated">使用範圍運算子</target> <note /> </trans-unit> <trans-unit id="Use_simple_using_statement"> <source>Use simple 'using' statement</source> <target state="translated">使用簡單的 'using' 陳述式</target> <note /> </trans-unit> <trans-unit id="Use_switch_expression"> <source>Use 'switch' expression</source> <target state="translated">使用 'switch' 運算式</target> <note /> </trans-unit> <trans-unit id="Using_directives_must_be_placed_inside_of_a_namespace_declaration"> <source>Using directives must be placed inside of a namespace declaration</source> <target state="translated">using 指示詞必須放在 namespace 宣告內</target> <note>{Locked="using"} "using" is a C# keyword and should not be localized. {Locked="namespace"} "namespace" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="Using_directives_must_be_placed_outside_of_a_namespace_declaration"> <source>Using directives must be placed outside of a namespace declaration</source> <target state="translated">using 指示詞必須放在 namespace 宣告外</target> <note>{Locked="using"} "using" is a C# keyword and should not be localized. {Locked="namespace"} "namespace" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="Variable_declaration_can_be_deconstructed"> <source>Variable declaration can be deconstructed</source> <target state="translated">變數宣告可進行解構</target> <note /> </trans-unit> <trans-unit id="Variable_declaration_can_be_inlined"> <source>Variable declaration can be inlined</source> <target state="translated">變數宣告可內置</target> <note /> </trans-unit> <trans-unit id="Warning_colon_Moving_using_directives_may_change_code_meaning"> <source>Warning: Moving using directives may change code meaning.</source> <target state="translated">警告: 移動 using 指示詞可能會變更程式碼意義。</target> <note>{Locked="using"} "using" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="_0_can_be_simplified"> <source>{0} can be simplified</source> <target state="translated">可簡化 {0}</target> <note /> </trans-unit> <trans-unit id="default_expression_can_be_simplified"> <source>'default' expression can be simplified</source> <target state="translated">'default' 運算式可予簡化</target> <note /> </trans-unit> <trans-unit id="if_statement_can_be_simplified"> <source>'if' statement can be simplified</source> <target state="translated">'if' 陳述式可簡化</target> <note /> </trans-unit> <trans-unit id="new_expression_can_be_simplified"> <source>'new' expression can be simplified</source> <target state="translated">'new' 運算式可簡化</target> <note /> </trans-unit> <trans-unit id="typeof_can_be_converted_ to_nameof"> <source>'typeof' can be converted to 'nameof'</source> <target state="translated">'typeof' 可轉換為 'nameof'</target> <note /> </trans-unit> <trans-unit id="use_var_instead_of_explicit_type"> <source>use 'var' instead of explicit type</source> <target state="translated">使用 'var',而非明確類型</target> <note /> </trans-unit> <trans-unit id="Using_directive_is_unnecessary"> <source>Using directive is unnecessary.</source> <target state="translated">無須使用指示詞。</target> <note /> </trans-unit> <trans-unit id="using_statement_can_be_simplified"> <source>'using' statement can be simplified</source> <target state="translated">'using' 陳述式可簡化</target> <note /> </trans-unit> </body> </file> </xliff>
<?xml version="1.0" encoding="utf-8"?> <xliff xmlns="urn:oasis:names:tc:xliff:document:1.2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="1.2" xsi:schemaLocation="urn:oasis:names:tc:xliff:document:1.2 xliff-core-1.2-transitional.xsd"> <file datatype="xml" source-language="en" target-language="zh-Hant" original="../CSharpAnalyzersResources.resx"> <body> <trans-unit id="Add_braces"> <source>Add braces</source> <target state="translated">加入大括號</target> <note /> </trans-unit> <trans-unit id="Add_braces_to_0_statement"> <source>Add braces to '{0}' statement.</source> <target state="translated">為 '{0}' 陳述式加入大括號。</target> <note /> </trans-unit> <trans-unit id="Blank_line_not_allowed_after_constructor_initializer_colon"> <source>Blank line not allowed after constructor initializer colon</source> <target state="translated">不允許在建構函式初始設定式冒號後加上空白行</target> <note /> </trans-unit> <trans-unit id="Consecutive_braces_must_not_have_a_blank_between_them"> <source>Consecutive braces must not have blank line between them</source> <target state="translated">連續大括弧之間不能有空白行</target> <note /> </trans-unit> <trans-unit id="Convert_switch_statement_to_expression"> <source>Convert switch statement to expression</source> <target state="translated">將 switch 陳述式轉換為運算式</target> <note /> </trans-unit> <trans-unit id="Convert_to_block_scoped_namespace"> <source>Convert to block scoped namespace</source> <target state="new">Convert to block scoped namespace</target> <note>{Locked="namespace"} "namespace" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="Convert_to_file_scoped_namespace"> <source>Convert to file-scoped namespace</source> <target state="new">Convert to file-scoped namespace</target> <note>{Locked="namespace"} "namespace" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="Deconstruct_variable_declaration"> <source>Deconstruct variable declaration</source> <target state="translated">解構變數宣告</target> <note /> </trans-unit> <trans-unit id="Delegate_invocation_can_be_simplified"> <source>Delegate invocation can be simplified.</source> <target state="translated">可以簡化委派引動的過程。</target> <note /> </trans-unit> <trans-unit id="Discard_can_be_removed"> <source>Discard can be removed</source> <target state="translated">可以移除捨棄</target> <note /> </trans-unit> <trans-unit id="Embedded_statements_must_be_on_their_own_line"> <source>Embedded statements must be on their own line</source> <target state="translated">內嵌陳述式必須位於自己的行中</target> <note /> </trans-unit> <trans-unit id="Indexing_can_be_simplified"> <source>Indexing can be simplified</source> <target state="translated">可簡化索引</target> <note /> </trans-unit> <trans-unit id="Inline_variable_declaration"> <source>Inline variable declaration</source> <target state="translated">內嵌變數宣告</target> <note /> </trans-unit> <trans-unit id="Misplaced_using_directive"> <source>Misplaced using directive</source> <target state="translated">using 指示詞位置錯誤</target> <note>{Locked="using"} "using" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="Move_misplaced_using_directives"> <source>Move misplaced using directives</source> <target state="translated">移動位置錯誤的 using 指示詞</target> <note>{Locked="using"} "using" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="Make_readonly_fields_writable"> <source>Make readonly fields writable</source> <target state="translated">將 readonly 欄位設為可寫入</target> <note>{Locked="readonly"} "readonly" is C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="Local_function_can_be_made_static"> <source>Local function can be made static</source> <target state="translated">區域函式可以變成靜態</target> <note /> </trans-unit> <trans-unit id="Make_local_function_static"> <source>Make local function 'static'</source> <target state="translated">將區域函式設為 'static'</target> <note /> </trans-unit> <trans-unit id="Negate_expression_changes_semantics"> <source>Negate expression (changes semantics)</source> <target state="translated">否定運算式 (變更語義)</target> <note /> </trans-unit> <trans-unit id="Null_check_can_be_clarified"> <source>Null check can be clarified</source> <target state="new">Null check can be clarified</target> <note /> </trans-unit> <trans-unit id="Prefer_null_check_over_type_check"> <source>Prefer 'null' check over type check</source> <target state="new">Prefer 'null' check over type check</target> <note /> </trans-unit> <trans-unit id="Remove_operator_preserves_semantics"> <source>Remove operator (preserves semantics)</source> <target state="translated">移除運算子 (保留語義)</target> <note /> </trans-unit> <trans-unit id="Remove_suppression_operators"> <source>Remove suppression operators</source> <target state="translated">移除隱藏的運算子</target> <note /> </trans-unit> <trans-unit id="Remove_unnecessary_suppression_operator"> <source>Remove unnecessary suppression operator</source> <target state="translated">移除隱藏運算子中不需要的運算子</target> <note /> </trans-unit> <trans-unit id="Remove_unnessary_discard"> <source>Remove unnecessary discard</source> <target state="translated">移除不必要的捨棄</target> <note /> </trans-unit> <trans-unit id="Simplify_default_expression"> <source>Simplify 'default' expression</source> <target state="translated">簡化 'default' 運算式</target> <note /> </trans-unit> <trans-unit id="Struct_contains_assignment_to_this_outside_of_constructor_Make_readonly_fields_writable"> <source>Struct contains assignment to 'this' outside of constructor. Make readonly fields writable.</source> <target state="translated">Struct 包含建構函式外對 'this' 的指派。請將唯讀欄位設為可寫入。</target> <note>{Locked="Struct"}{Locked="this"} these are C#/VB keywords and should not be localized.</note> </trans-unit> <trans-unit id="Suppression_operator_has_no_effect_and_can_be_misinterpreted"> <source>Suppression operator has no effect and can be misinterpreted</source> <target state="translated">隱藏運算子沒有作用,而且可能會造成誤解</target> <note /> </trans-unit> <trans-unit id="Unreachable_code_detected"> <source>Unreachable code detected</source> <target state="translated">偵測到執行不到的程式碼</target> <note /> </trans-unit> <trans-unit id="Use_block_body_for_accessors"> <source>Use block body for accessors</source> <target state="translated">使用存取子的區塊主體</target> <note /> </trans-unit> <trans-unit id="Use_block_body_for_constructors"> <source>Use block body for constructors</source> <target state="translated">使用建構函式的區塊主體</target> <note /> </trans-unit> <trans-unit id="Use_block_body_for_indexers"> <source>Use block body for indexers</source> <target state="translated">使用索引子的區塊主體</target> <note /> </trans-unit> <trans-unit id="Use_block_body_for_local_functions"> <source>Use block body for local functions</source> <target state="translated">為區域函式使用區塊主體</target> <note /> </trans-unit> <trans-unit id="Use_block_body_for_methods"> <source>Use block body for methods</source> <target state="translated">使用方法的區塊主體</target> <note /> </trans-unit> <trans-unit id="Use_block_body_for_operators"> <source>Use block body for operators</source> <target state="translated">使用運算子的區塊主體</target> <note /> </trans-unit> <trans-unit id="Use_block_body_for_properties"> <source>Use block body for properties</source> <target state="translated">使用屬性的區塊主體</target> <note /> </trans-unit> <trans-unit id="Use_explicit_type"> <source>Use explicit type</source> <target state="translated">使用明確類型</target> <note /> </trans-unit> <trans-unit id="Use_explicit_type_instead_of_var"> <source>Use explicit type instead of 'var'</source> <target state="translated">使用明確類型,而非 'var'</target> <note /> </trans-unit> <trans-unit id="Use_expression_body_for_accessors"> <source>Use expression body for accessors</source> <target state="translated">使用存取子的運算式主體</target> <note /> </trans-unit> <trans-unit id="Use_expression_body_for_constructors"> <source>Use expression body for constructors</source> <target state="translated">使用建構函式的運算式主體</target> <note /> </trans-unit> <trans-unit id="Use_expression_body_for_indexers"> <source>Use expression body for indexers</source> <target state="translated">使用索引子的運算式主體</target> <note /> </trans-unit> <trans-unit id="Use_expression_body_for_local_functions"> <source>Use expression body for local functions</source> <target state="translated">為區域函式使用運算式主體</target> <note /> </trans-unit> <trans-unit id="Use_expression_body_for_methods"> <source>Use expression body for methods</source> <target state="translated">使用方法的運算式主體</target> <note /> </trans-unit> <trans-unit id="Use_expression_body_for_operators"> <source>Use expression body for operators</source> <target state="translated">使用運算子的運算式主體</target> <note /> </trans-unit> <trans-unit id="Use_expression_body_for_properties"> <source>Use expression body for properties</source> <target state="translated">使用屬性的運算式主體</target> <note /> </trans-unit> <trans-unit id="Use_implicit_type"> <source>Use implicit type</source> <target state="translated">使用隱含類型</target> <note /> </trans-unit> <trans-unit id="Use_index_operator"> <source>Use index operator</source> <target state="translated">使用索引運算子</target> <note /> </trans-unit> <trans-unit id="Use_is_null_check"> <source>Use 'is null' check</source> <target state="translated">使用 'is null' 檢查</target> <note /> </trans-unit> <trans-unit id="Use_local_function"> <source>Use local function</source> <target state="translated">使用區域函式</target> <note /> </trans-unit> <trans-unit id="Use_new"> <source>Use 'new(...)'</source> <target state="translated">使用 'new(...)'</target> <note>{Locked="new(...)"} This is a C# construct and should not be localized.</note> </trans-unit> <trans-unit id="Use_pattern_matching"> <source>Use pattern matching</source> <target state="translated">使用模式比對</target> <note /> </trans-unit> <trans-unit id="Use_pattern_matching_may_change_code_meaning"> <source>Use pattern matching (may change code meaning)</source> <target state="new">Use pattern matching (may change code meaning)</target> <note /> </trans-unit> <trans-unit id="Use_range_operator"> <source>Use range operator</source> <target state="translated">使用範圍運算子</target> <note /> </trans-unit> <trans-unit id="Use_simple_using_statement"> <source>Use simple 'using' statement</source> <target state="translated">使用簡單的 'using' 陳述式</target> <note /> </trans-unit> <trans-unit id="Use_switch_expression"> <source>Use 'switch' expression</source> <target state="translated">使用 'switch' 運算式</target> <note /> </trans-unit> <trans-unit id="Using_directives_must_be_placed_inside_of_a_namespace_declaration"> <source>Using directives must be placed inside of a namespace declaration</source> <target state="translated">using 指示詞必須放在 namespace 宣告內</target> <note>{Locked="using"} "using" is a C# keyword and should not be localized. {Locked="namespace"} "namespace" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="Using_directives_must_be_placed_outside_of_a_namespace_declaration"> <source>Using directives must be placed outside of a namespace declaration</source> <target state="translated">using 指示詞必須放在 namespace 宣告外</target> <note>{Locked="using"} "using" is a C# keyword and should not be localized. {Locked="namespace"} "namespace" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="Variable_declaration_can_be_deconstructed"> <source>Variable declaration can be deconstructed</source> <target state="translated">變數宣告可進行解構</target> <note /> </trans-unit> <trans-unit id="Variable_declaration_can_be_inlined"> <source>Variable declaration can be inlined</source> <target state="translated">變數宣告可內置</target> <note /> </trans-unit> <trans-unit id="Warning_colon_Moving_using_directives_may_change_code_meaning"> <source>Warning: Moving using directives may change code meaning.</source> <target state="translated">警告: 移動 using 指示詞可能會變更程式碼意義。</target> <note>{Locked="using"} "using" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="_0_can_be_simplified"> <source>{0} can be simplified</source> <target state="translated">可簡化 {0}</target> <note /> </trans-unit> <trans-unit id="default_expression_can_be_simplified"> <source>'default' expression can be simplified</source> <target state="translated">'default' 運算式可予簡化</target> <note /> </trans-unit> <trans-unit id="if_statement_can_be_simplified"> <source>'if' statement can be simplified</source> <target state="translated">'if' 陳述式可簡化</target> <note /> </trans-unit> <trans-unit id="new_expression_can_be_simplified"> <source>'new' expression can be simplified</source> <target state="translated">'new' 運算式可簡化</target> <note /> </trans-unit> <trans-unit id="typeof_can_be_converted_ to_nameof"> <source>'typeof' can be converted to 'nameof'</source> <target state="translated">'typeof' 可轉換為 'nameof'</target> <note /> </trans-unit> <trans-unit id="use_var_instead_of_explicit_type"> <source>use 'var' instead of explicit type</source> <target state="translated">使用 'var',而非明確類型</target> <note /> </trans-unit> <trans-unit id="Using_directive_is_unnecessary"> <source>Using directive is unnecessary.</source> <target state="translated">無須使用指示詞。</target> <note /> </trans-unit> <trans-unit id="using_statement_can_be_simplified"> <source>'using' statement can be simplified</source> <target state="translated">'using' 陳述式可簡化</target> <note /> </trans-unit> </body> </file> </xliff>
1
dotnet/roslyn
55,427
Fixes #50462
Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
Blokyk
2021-08-05T01:17:37Z
2021-08-25T05:42:59Z
fefb8c2110625bc4908db4bbdaa367b12bfb1069
fb4ac545a1f1f365e7df570637699d9085ea4f87
Fixes #50462. Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
./src/EditorFeatures/CSharpTest/UsePatternCombinators/CSharpUsePatternCombinatorsDiagnosticAnalyzerTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.CodeStyle; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.CodeStyle; using Microsoft.CodeAnalysis.CSharp.Shared.Extensions; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.CSharp.UsePatternCombinators; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Diagnostics; using Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; using Xunit.Abstractions; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.UsePatternCombinators { public class CSharpUsePatternCombinatorsDiagnosticAnalyzerTests : AbstractCSharpDiagnosticProviderBasedUserDiagnosticTest { private static readonly ParseOptions CSharp9 = TestOptions.RegularPreview.WithLanguageVersion(LanguageVersion.CSharp9); private static readonly OptionsCollection s_disabled = new OptionsCollection(LanguageNames.CSharp) { { CSharpCodeStyleOptions.PreferPatternMatching, new CodeStyleOption2<bool>(false, NotificationOption2.None) } }; public CSharpUsePatternCombinatorsDiagnosticAnalyzerTests(ITestOutputHelper logger) : base(logger) { } internal override (DiagnosticAnalyzer, CodeFixProvider) CreateDiagnosticProviderAndFixer(Workspace workspace) => (new CSharpUsePatternCombinatorsDiagnosticAnalyzer(), new CSharpUsePatternCombinatorsCodeFixProvider()); private Task TestAllMissingOnExpressionAsync(string expression, ParseOptions parseOptions = null, bool enabled = true) => TestMissingAsync(FromExpression(expression), parseOptions, enabled); private Task TestMissingAsync(string initialMarkup, ParseOptions parseOptions = null, bool enabled = true) => TestMissingAsync(initialMarkup, new TestParameters( parseOptions: parseOptions ?? CSharp9, options: enabled ? null : s_disabled)); private Task TestAllAsync(string initialMarkup, string expectedMarkup) => TestInRegularAndScriptAsync(initialMarkup, expectedMarkup, parseOptions: CSharp9, options: null); private Task TestAllOnExpressionAsync(string expression, string expected) => TestAllAsync(FromExpression(expression), FromExpression(expected)); private static string FromExpression(string expression) { const string initialMarkup = @" using System; using System.Collections.Generic; class C { static bool field = {|FixAllInDocument:EXPRESSION|}; static bool Method() => EXPRESSION; static bool Prop1 => EXPRESSION; static bool Prop2 { get; } = EXPRESSION; static void If() { if (EXPRESSION) ; } static void Argument1() => Test(EXPRESSION); static void Argument2() => Test(() => EXPRESSION); static void Argument3() => Test(_ => EXPRESSION); static void Test(bool b) {} static void Test(Func<bool> b) {} static void Test(Func<object, bool> b) {} static void For() { for (; EXPRESSION; ); } static void Local() { var local = EXPRESSION; } static void Conditional() { _ = EXPRESSION ? EXPRESSION : EXPRESSION; } static void Assignment() { _ = EXPRESSION; } static void Do() { do ; while (EXPRESSION); } static void While() { while (EXPRESSION) ; } static bool When() => o switch { _ when EXPRESSION => EXPRESSION }; static bool Return() { return EXPRESSION; } static IEnumerable<bool> YieldReturn() { yield return EXPRESSION; } static Func<object, bool> SimpleLambda() => o => EXPRESSION; static Func<bool> ParenthesizedLambda() => () => EXPRESSION; static void LocalFunc() { bool LocalFunction() => EXPRESSION; } static int i; static int? nullable; static object o; static char ch; } "; return initialMarkup.Replace("EXPRESSION", expression); } [InlineData("i == 0")] [InlineData("i > 0")] [InlineData("o is C")] [InlineData("o is C c")] [InlineData("o != null")] [InlineData("!(o is null)")] [InlineData("o is int ii || o is long jj")] [Theory, Trait(Traits.Feature, Traits.Features.CodeActionsUsePatternCombinators)] public async Task TestMissingOnExpression(string expression) { await TestAllMissingOnExpressionAsync(expression); } [InlineData("i == default || i > default(int)", "i is default(int) or > (default(int))")] [InlineData("!(o is C c)", "o is not C c")] [InlineData("o is int ii && o is long jj", "o is int ii and long jj")] [InlineData("!(o is C)", "o is not C")] [InlineData("!(o is C _)", "o is not C _")] [InlineData("i == (0x02 | 0x04) || i != 0", "i is (0x02 | 0x04) or not 0")] [InlineData("i == 1 || 2 == i", "i is 1 or 2")] [InlineData("i == (short)1 || (short)2 == i", "i is ((short)1) or ((short)2)")] [InlineData("nullable == 1 || 2 == nullable", "nullable is 1 or 2")] [InlineData("i != 1 || 2 != i", "i is not 1 or not 2")] [InlineData("i != 1 && 2 != i", "i is not 1 and not 2")] [InlineData("!(i != 1 && 2 != i)", "i is 1 or 2")] [InlineData("i < 1 && 2 <= i", "i is < 1 and >= 2")] [InlineData("i < 1 && 2 <= i && i is not 0", "i is < 1 and >= 2 and not 0")] [InlineData("(int.MaxValue - 1D) < i && i > 0", "i is > (int)(int.MaxValue - 1D) and > 0")] [InlineData("ch < ' ' || ch >= 0x100 || 'a' == ch", "ch is < ' ' or >= (char)0x100 or 'a'")] [InlineData("ch == 'a' || 'b' == ch", "ch is 'a' or 'b'")] [Theory, Trait(Traits.Feature, Traits.Features.CodeActionsUsePatternCombinators)] public async Task TestOnExpression(string expression, string expected) { await TestAllOnExpressionAsync(expression, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUsePatternCombinators)] public async Task TestMissingIfDisabled() { await TestAllMissingOnExpressionAsync("o == 1 || o == 2", enabled: false); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUsePatternCombinators)] public async Task TestMissingOnCSharp8() { await TestAllMissingOnExpressionAsync("o == 1 || o == 2", parseOptions: TestOptions.Regular8); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUsePatternCombinators)] public async Task TestMultilineTrivia_01() { await TestAllAsync( @"class C { bool M0(int variable) { return {|FixAllInDocument:variable == 0 || /*1*/ variable == 1 || /*2*/ variable == 2|}; /*3*/ } bool M1(int variable) { return variable != 0 && /*1*/ variable != 1 && /*2*/ variable != 2; /*3*/ } }", @"class C { bool M0(int variable) { return variable is 0 or /*1*/ 1 or /*2*/ 2; /*3*/ } bool M1(int variable) { return variable is not 0 and /*1*/ not 1 and /*2*/ not 2; /*3*/ } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUsePatternCombinators)] public async Task TestMultilineTrivia_02() { await TestAllAsync( @"class C { bool M0(int variable) { return {|FixAllInDocument:variable == 0 /*1*/ || variable == 1 /*2*/ || variable == 2|}; /*3*/ } bool M1(int variable) { return variable != 0 /*1*/ && variable != 1 /*2*/ && variable != 2; /*3*/ } }", @"class C { bool M0(int variable) { return variable is 0 /*1*/ or 1 /*2*/ or 2; /*3*/ } bool M1(int variable) { return variable is not 0 /*1*/ and not 1 /*2*/ and not 2; /*3*/ } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUsePatternCombinators)] public async Task TestParenthesized() { await TestAllAsync( @"class C { bool M0(int v) { return {|FixAllInDocument:(v == 0 || v == 1 || v == 2)|}; } bool M1(int v) { return (v == 0) || (v == 1) || (v == 2); } }", @"class C { bool M0(int v) { return (v is 0 or 1 or 2); } bool M1(int v) { return v is 0 or 1 or 2; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUsePatternCombinators)] public async Task TestMissingInExpressionTree() { await TestMissingAsync( @"using System.Linq; class C { void M0(IQueryable<int> q) { q.Where(item => item == 1 [||]|| item == 2); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUsePatternCombinators)] [WorkItem(52397, "https://github.com/dotnet/roslyn/issues/52397")] public async Task TestMissingInPropertyAccess_NullCheckOnLeftSide() { await TestMissingAsync( @"using System; public class C { public int I { get; } public EventArgs Property { get; } public void M() { if (Property != null [|&&|] I == 1) { } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUsePatternCombinators)] [WorkItem(52397, "https://github.com/dotnet/roslyn/issues/52397")] public async Task TestMissingInPropertyAccess_NullCheckOnRightSide() { await TestMissingAsync( @"using System; public class C { public int I { get; } public EventArgs Property { get; } public void M() { if (I == 1 [|&&|] Property != null) { } } }"); } [Theory, Trait(Traits.Feature, Traits.Features.CodeActionsUsePatternCombinators)] [WorkItem(51691, "https://github.com/dotnet/roslyn/issues/51691")] [InlineData("&&")] [InlineData("||")] public async Task TestMissingInPropertyAccess_EnumCheckAndNullCheck(string logicalOperator) { await TestMissingAsync( $@"using System.Diagnostics; public class C {{ public void M() {{ var p = default(Process); if (p.StartInfo.WindowStyle == ProcessWindowStyle.Hidden [|{logicalOperator}|] p.StartInfo != null) {{ }} }} }}"); } [Theory, Trait(Traits.Feature, Traits.Features.CodeActionsUsePatternCombinators)] [WorkItem(51691, "https://github.com/dotnet/roslyn/issues/51691")] [InlineData("&&")] [InlineData("||")] public async Task TestMissingInPropertyAccess_EnumCheckAndNullCheckOnOtherType(string logicalOperator) { await TestMissingAsync( $@"using System.Diagnostics; public class C {{ public void M() {{ var p = default(Process); if (p.StartInfo.WindowStyle == ProcessWindowStyle.Hidden [|{logicalOperator}|] this != null) {{ }} }} }}"); } [Theory, Trait(Traits.Feature, Traits.Features.CodeActionsUsePatternCombinators)] [WorkItem(51693, "https://github.com/dotnet/roslyn/issues/51693")] [InlineData("&&")] [InlineData("||")] public async Task TestMissingInPropertyAccess_IsCheckAndNullCheck(string logicalOperator) { await TestMissingAsync( $@"using System; public class C {{ public void M() {{ var o1 = new object(); if (o1 is IAsyncResult ar [|{logicalOperator}|] ar.AsyncWaitHandle != null) {{ }} }} }}"); } [Theory, Trait(Traits.Feature, Traits.Features.CodeActionsUsePatternCombinators)] [WorkItem(52573, "https://github.com/dotnet/roslyn/issues/52573")] [InlineData("&&")] [InlineData("||")] public async Task TestMissingIntegerAndStringIndex(string logicalOperator) { await TestMissingAsync( $@"using System; public class C {{ private static bool IsS(char[] ch, int count) {{ return count == 1 [|{logicalOperator}|] ch[0] == 'S'; }} }}"); } } }
// Licensed to the .NET Foundation under one or more agreements. // 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.CodeFixes; using Microsoft.CodeAnalysis.CodeStyle; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.CodeStyle; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.CSharp.UsePatternCombinators; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Diagnostics; using Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; using Xunit.Abstractions; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.UsePatternCombinators { public class CSharpUsePatternCombinatorsDiagnosticAnalyzerTests : AbstractCSharpDiagnosticProviderBasedUserDiagnosticTest { private static readonly ParseOptions CSharp9 = TestOptions.RegularPreview.WithLanguageVersion(LanguageVersion.CSharp9); private static readonly OptionsCollection s_disabled = new OptionsCollection(LanguageNames.CSharp) { { CSharpCodeStyleOptions.PreferPatternMatching, new CodeStyleOption2<bool>(false, NotificationOption2.None) } }; public CSharpUsePatternCombinatorsDiagnosticAnalyzerTests(ITestOutputHelper logger) : base(logger) { } internal override (DiagnosticAnalyzer, CodeFixProvider) CreateDiagnosticProviderAndFixer(Workspace workspace) => (new CSharpUsePatternCombinatorsDiagnosticAnalyzer(), new CSharpUsePatternCombinatorsCodeFixProvider()); private Task TestAllMissingOnExpressionAsync(string expression, ParseOptions? parseOptions = null, bool enabled = true) => TestMissingAsync(FromExpression(expression), parseOptions, enabled); private Task TestMissingAsync(string initialMarkup, ParseOptions? parseOptions = null, bool enabled = true) => TestMissingAsync(initialMarkup, new TestParameters( parseOptions: parseOptions ?? CSharp9, options: enabled ? null : s_disabled)); private Task TestAllAsync(string initialMarkup, string expectedMarkup) => TestInRegularAndScriptAsync(initialMarkup, expectedMarkup, parseOptions: CSharp9, options: null); private Task TestAllOnExpressionAsync(string expression, string expected) => TestAllAsync(FromExpression(expression), FromExpression(expected)); private static string FromExpression(string expression) { const string initialMarkup = @" using System; using System.Collections.Generic; class C { static bool field = {|FixAllInDocument:EXPRESSION|}; static bool Method() => EXPRESSION; static bool Prop1 => EXPRESSION; static bool Prop2 { get; } = EXPRESSION; static void If() { if (EXPRESSION) ; } static void Argument1() => Test(EXPRESSION); static void Argument2() => Test(() => EXPRESSION); static void Argument3() => Test(_ => EXPRESSION); static void Test(bool b) {} static void Test(Func<bool> b) {} static void Test(Func<object, bool> b) {} static void For() { for (; EXPRESSION; ); } static void Local() { var local = EXPRESSION; } static void Conditional() { _ = EXPRESSION ? EXPRESSION : EXPRESSION; } static void Assignment() { _ = EXPRESSION; } static void Do() { do ; while (EXPRESSION); } static void While() { while (EXPRESSION) ; } static bool When() => o switch { _ when EXPRESSION => EXPRESSION }; static bool Return() { return EXPRESSION; } static IEnumerable<bool> YieldReturn() { yield return EXPRESSION; } static Func<object, bool> SimpleLambda() => o => EXPRESSION; static Func<bool> ParenthesizedLambda() => () => EXPRESSION; static void LocalFunc() { bool LocalFunction() => EXPRESSION; } static int i; static int? nullable; static object o; static char ch; } "; return initialMarkup.Replace("EXPRESSION", expression); } [InlineData("i == 0")] [InlineData("i > 0")] [InlineData("o is C")] [InlineData("o is C c")] [InlineData("o != null")] [InlineData("!(o is null)")] [InlineData("o is int ii || o is long jj")] [Theory, Trait(Traits.Feature, Traits.Features.CodeActionsUsePatternCombinators)] public async Task TestMissingOnExpression(string expression) { await TestAllMissingOnExpressionAsync(expression); } [InlineData("i == default || i > default(int)", "i is default(int) or > (default(int))")] [InlineData("!(o is C c)", "o is not C c")] [InlineData("o is int ii && o is long jj", "o is int ii and long jj")] [InlineData("!(o is C)", "o is not C")] [InlineData("!(o is C _)", "o is not C _")] [InlineData("i == (0x02 | 0x04) || i != 0", "i is (0x02 | 0x04) or not 0")] [InlineData("i == 1 || 2 == i", "i is 1 or 2")] [InlineData("i == (short)1 || (short)2 == i", "i is ((short)1) or ((short)2)")] [InlineData("nullable == 1 || 2 == nullable", "nullable is 1 or 2")] [InlineData("i != 1 || 2 != i", "i is not 1 or not 2")] [InlineData("i != 1 && 2 != i", "i is not 1 and not 2")] [InlineData("!(i != 1 && 2 != i)", "i is 1 or 2")] [InlineData("i < 1 && 2 <= i", "i is < 1 and >= 2")] [InlineData("i < 1 && 2 <= i && i is not 0", "i is < 1 and >= 2 and not 0")] [InlineData("(int.MaxValue - 1D) < i && i > 0", "i is > (int)(int.MaxValue - 1D) and > 0")] [InlineData("ch < ' ' || ch >= 0x100 || 'a' == ch", "ch is < ' ' or >= (char)0x100 or 'a'")] [InlineData("ch == 'a' || 'b' == ch", "ch is 'a' or 'b'")] [Theory, Trait(Traits.Feature, Traits.Features.CodeActionsUsePatternCombinators)] public async Task TestOnExpression(string expression, string expected) { await TestAllOnExpressionAsync(expression, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUsePatternCombinators)] public async Task TestMissingIfDisabled() { await TestAllMissingOnExpressionAsync("o == 1 || o == 2", enabled: false); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUsePatternCombinators)] public async Task TestMissingOnCSharp8() { await TestAllMissingOnExpressionAsync("o == 1 || o == 2", parseOptions: TestOptions.Regular8); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUsePatternCombinators)] public async Task TestMultilineTrivia_01() { await TestAllAsync( @"class C { bool M0(int variable) { return {|FixAllInDocument:variable == 0 || /*1*/ variable == 1 || /*2*/ variable == 2|}; /*3*/ } bool M1(int variable) { return variable != 0 && /*1*/ variable != 1 && /*2*/ variable != 2; /*3*/ } }", @"class C { bool M0(int variable) { return variable is 0 or /*1*/ 1 or /*2*/ 2; /*3*/ } bool M1(int variable) { return variable is not 0 and /*1*/ not 1 and /*2*/ not 2; /*3*/ } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUsePatternCombinators)] public async Task TestMultilineTrivia_02() { await TestAllAsync( @"class C { bool M0(int variable) { return {|FixAllInDocument:variable == 0 /*1*/ || variable == 1 /*2*/ || variable == 2|}; /*3*/ } bool M1(int variable) { return variable != 0 /*1*/ && variable != 1 /*2*/ && variable != 2; /*3*/ } }", @"class C { bool M0(int variable) { return variable is 0 /*1*/ or 1 /*2*/ or 2; /*3*/ } bool M1(int variable) { return variable is not 0 /*1*/ and not 1 /*2*/ and not 2; /*3*/ } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUsePatternCombinators)] public async Task TestParenthesized() { await TestAllAsync( @"class C { bool M0(int v) { return {|FixAllInDocument:(v == 0 || v == 1 || v == 2)|}; } bool M1(int v) { return (v == 0) || (v == 1) || (v == 2); } }", @"class C { bool M0(int v) { return (v is 0 or 1 or 2); } bool M1(int v) { return v is 0 or 1 or 2; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUsePatternCombinators)] public async Task TestMissingInExpressionTree() { await TestMissingAsync( @"using System.Linq; class C { void M0(IQueryable<int> q) { q.Where(item => item == 1 [||]|| item == 2); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUsePatternCombinators)] [WorkItem(52397, "https://github.com/dotnet/roslyn/issues/52397")] public async Task TestMissingInPropertyAccess_NullCheckOnLeftSide() { await TestMissingAsync( @"using System; public class C { public int I { get; } public EventArgs Property { get; } public void M() { if (Property != null [|&&|] I == 1) { } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUsePatternCombinators)] [WorkItem(52397, "https://github.com/dotnet/roslyn/issues/52397")] public async Task TestMissingInPropertyAccess_NullCheckOnRightSide() { await TestMissingAsync( @"using System; public class C { public int I { get; } public EventArgs Property { get; } public void M() { if (I == 1 [|&&|] Property != null) { } } }"); } [Theory, Trait(Traits.Feature, Traits.Features.CodeActionsUsePatternCombinators)] [WorkItem(51691, "https://github.com/dotnet/roslyn/issues/51691")] [InlineData("&&")] [InlineData("||")] public async Task TestMissingInPropertyAccess_EnumCheckAndNullCheck(string logicalOperator) { await TestMissingAsync( $@"using System.Diagnostics; public class C {{ public void M() {{ var p = default(Process); if (p.StartInfo.WindowStyle == ProcessWindowStyle.Hidden [|{logicalOperator}|] p.StartInfo != null) {{ }} }} }}"); } [Theory, Trait(Traits.Feature, Traits.Features.CodeActionsUsePatternCombinators)] [WorkItem(51691, "https://github.com/dotnet/roslyn/issues/51691")] [InlineData("&&")] [InlineData("||")] public async Task TestMissingInPropertyAccess_EnumCheckAndNullCheckOnOtherType(string logicalOperator) { await TestMissingAsync( $@"using System.Diagnostics; public class C {{ public void M() {{ var p = default(Process); if (p.StartInfo.WindowStyle == ProcessWindowStyle.Hidden [|{logicalOperator}|] this != null) {{ }} }} }}"); } [Theory, Trait(Traits.Feature, Traits.Features.CodeActionsUsePatternCombinators)] [WorkItem(51693, "https://github.com/dotnet/roslyn/issues/51693")] [InlineData("&&")] [InlineData("||")] public async Task TestMissingInPropertyAccess_IsCheckAndNullCheck(string logicalOperator) { await TestMissingAsync( $@"using System; public class C {{ public void M() {{ var o1 = new object(); if (o1 is IAsyncResult ar [|{logicalOperator}|] ar.AsyncWaitHandle != null) {{ }} }} }}"); } [Theory, Trait(Traits.Feature, Traits.Features.CodeActionsUsePatternCombinators)] [WorkItem(52573, "https://github.com/dotnet/roslyn/issues/52573")] [InlineData("&&")] [InlineData("||")] public async Task TestMissingIntegerAndStringIndex(string logicalOperator) { await TestMissingAsync( $@"using System; public class C {{ private static bool IsS(char[] ch, int count) {{ return count == 1 [|{logicalOperator}|] ch[0] == 'S'; }} }}"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUsePatternCombinators)] public async Task TestOnSideEffects1() { await TestInRegularAndScriptAsync( @" class C { char ReadChar() => default; void M(char c) { if ({|FixAllInDocument:c == 'x' && c == 'y'|}) { } if (c == 'x' && c == 'y') { } if (ReadChar() == 'x' && ReadChar() == 'y') { } } } ", @" class C { char ReadChar() => default; void M(char c) { if (c is 'x' and 'y') { } if (c is 'x' and 'y') { } if (ReadChar() == 'x' && ReadChar() == 'y') { } } } "); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUsePatternCombinators)] public async Task TestOnSideEffects2() { await TestInRegularAndScriptAsync( @" class C { char ReadChar() => default; void M(char c) { if ({|FixAllInDocument:ReadChar() == 'x' && ReadChar() == 'y'|}) { } if (ReadChar() == 'x' && ReadChar() == 'y') { } if (c == 'x' && c == 'y') { } } } ", @" class C { char ReadChar() => default; void M(char c) { if (ReadChar() is 'x' and 'y') { } if (ReadChar() is 'x' and 'y') { } if (c == 'x' && c == 'y') { } } } "); } } }
1
dotnet/roslyn
55,427
Fixes #50462
Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
Blokyk
2021-08-05T01:17:37Z
2021-08-25T05:42:59Z
fefb8c2110625bc4908db4bbdaa367b12bfb1069
fb4ac545a1f1f365e7df570637699d9085ea4f87
Fixes #50462. Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
./src/Features/CSharp/Portable/UsePatternCombinators/CSharpUsePatternCombinatorsCodeFixProvider.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Immutable; using System.Composition; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.Operations; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Simplification; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.UsePatternCombinators { using static SyntaxFactory; using static AnalyzedPattern; [ExportCodeFixProvider(LanguageNames.CSharp, Name = PredefinedCodeFixProviderNames.UsePatternCombinators), Shared] internal class CSharpUsePatternCombinatorsCodeFixProvider : SyntaxEditorBasedCodeFixProvider { [ImportingConstructor] [SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification = "Used in test code: https://github.com/dotnet/roslyn/issues/42814")] public CSharpUsePatternCombinatorsCodeFixProvider() { } private static SyntaxKind MapToSyntaxKind(BinaryOperatorKind kind) { return kind switch { BinaryOperatorKind.LessThan => SyntaxKind.LessThanToken, BinaryOperatorKind.GreaterThan => SyntaxKind.GreaterThanToken, BinaryOperatorKind.LessThanOrEqual => SyntaxKind.LessThanEqualsToken, BinaryOperatorKind.GreaterThanOrEqual => SyntaxKind.GreaterThanEqualsToken, _ => throw ExceptionUtilities.UnexpectedValue(kind) }; } public override ImmutableArray<string> FixableDiagnosticIds => ImmutableArray.Create(IDEDiagnosticIds.UsePatternCombinatorsDiagnosticId); internal sealed override CodeFixCategory CodeFixCategory => CodeFixCategory.CodeStyle; public override Task RegisterCodeFixesAsync(CodeFixContext context) { context.RegisterCodeFix( new MyCodeAction(c => FixAsync(context.Document, context.Diagnostics.First(), c)), context.Diagnostics); return Task.CompletedTask; } protected override async Task FixAllAsync( Document document, ImmutableArray<Diagnostic> diagnostics, SyntaxEditor editor, CancellationToken cancellationToken) { var semanticModel = await document.GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false); foreach (var diagnostic in diagnostics) { var location = diagnostic.Location; var expression = editor.OriginalRoot.FindNode(location.SourceSpan, getInnermostNodeForTie: true); var operation = semanticModel.GetOperation(expression, cancellationToken); RoslynDebug.AssertNotNull(operation); var pattern = CSharpUsePatternCombinatorsAnalyzer.Analyze(operation); RoslynDebug.AssertNotNull(pattern); var patternSyntax = AsPatternSyntax(pattern).WithAdditionalAnnotations(Formatter.Annotation); editor.ReplaceNode(expression, IsPatternExpression((ExpressionSyntax)pattern.Target.Syntax, patternSyntax)); } } private static PatternSyntax AsPatternSyntax(AnalyzedPattern pattern) { return pattern switch { Binary p => BinaryPattern( p.IsDisjunctive ? SyntaxKind.OrPattern : SyntaxKind.AndPattern, AsPatternSyntax(p.Left).Parenthesize(), Token(p.Token.LeadingTrivia, p.IsDisjunctive ? SyntaxKind.OrKeyword : SyntaxKind.AndKeyword, TriviaList(p.Token.GetAllTrailingTrivia())), AsPatternSyntax(p.Right).Parenthesize()), Constant p => ConstantPattern(AsExpressionSyntax(p.ExpressionSyntax, p)), Source p => p.PatternSyntax, Type p => TypePattern(p.TypeSyntax), Relational p => RelationalPattern(Token(MapToSyntaxKind(p.OperatorKind)), AsExpressionSyntax(p.Value, p)), Not p => UnaryPattern(AsPatternSyntax(p.Pattern).Parenthesize()), var p => throw ExceptionUtilities.UnexpectedValue(p) }; } private static ExpressionSyntax AsExpressionSyntax(ExpressionSyntax expr, AnalyzedPattern p) { var semanticModel = p.Target.SemanticModel; Debug.Assert(semanticModel != null); var type = semanticModel.GetTypeInfo(expr).Type; if (type != null) { if (expr.IsKind(SyntaxKind.DefaultLiteralExpression)) { // default literals are not permitted in patterns return DefaultExpression(type.GenerateTypeSyntax()); } var governingType = semanticModel.GetTypeInfo(p.Target.Syntax).Type; if (governingType != null && !governingType.Equals(type)) { return CastExpression(governingType.GenerateTypeSyntax(), expr.Parenthesize()).WithAdditionalAnnotations(Simplifier.Annotation); } } return expr.Parenthesize(); } private class MyCodeAction : CustomCodeActions.DocumentChangeAction { public MyCodeAction(Func<CancellationToken, Task<Document>> createChangedDocument) : base(CSharpAnalyzersResources.Use_pattern_matching, createChangedDocument, nameof(CSharpUsePatternCombinatorsCodeFixProvider)) { } internal override CodeActionPriority Priority => CodeActionPriority.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.Immutable; using System.Composition; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.Operations; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Simplification; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.UsePatternCombinators { using static SyntaxFactory; using static AnalyzedPattern; [ExportCodeFixProvider(LanguageNames.CSharp, Name = PredefinedCodeFixProviderNames.UsePatternCombinators), Shared] internal class CSharpUsePatternCombinatorsCodeFixProvider : SyntaxEditorBasedCodeFixProvider { private const string SafeEquivalenceKey = nameof(CSharpUsePatternCombinatorsCodeFixProvider) + "_safe"; private const string UnsafeEquivalenceKey = nameof(CSharpUsePatternCombinatorsCodeFixProvider) + "_unsafe"; [ImportingConstructor] [SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification = "Used in test code: https://github.com/dotnet/roslyn/issues/42814")] public CSharpUsePatternCombinatorsCodeFixProvider() { } private static SyntaxKind MapToSyntaxKind(BinaryOperatorKind kind) { return kind switch { BinaryOperatorKind.LessThan => SyntaxKind.LessThanToken, BinaryOperatorKind.GreaterThan => SyntaxKind.GreaterThanToken, BinaryOperatorKind.LessThanOrEqual => SyntaxKind.LessThanEqualsToken, BinaryOperatorKind.GreaterThanOrEqual => SyntaxKind.GreaterThanEqualsToken, _ => throw ExceptionUtilities.UnexpectedValue(kind) }; } public override ImmutableArray<string> FixableDiagnosticIds => ImmutableArray.Create(IDEDiagnosticIds.UsePatternCombinatorsDiagnosticId); internal sealed override CodeFixCategory CodeFixCategory => CodeFixCategory.CodeStyle; protected override bool IncludeDiagnosticDuringFixAll( Diagnostic diagnostic, Document document, string? equivalenceKey, CancellationToken cancellationToken) { var isSafe = CSharpUsePatternCombinatorsDiagnosticAnalyzer.IsSafe(diagnostic); return isSafe == (equivalenceKey == SafeEquivalenceKey); } public override Task RegisterCodeFixesAsync(CodeFixContext context) { var diagnostic = context.Diagnostics.First(); var isSafe = CSharpUsePatternCombinatorsDiagnosticAnalyzer.IsSafe(diagnostic); context.RegisterCodeFix( new MyCodeAction( isSafe ? CSharpAnalyzersResources.Use_pattern_matching : CSharpAnalyzersResources.Use_pattern_matching_may_change_code_meaning, c => FixAsync(context.Document, diagnostic, c), isSafe ? SafeEquivalenceKey : UnsafeEquivalenceKey), context.Diagnostics); return Task.CompletedTask; } protected override async Task FixAllAsync( Document document, ImmutableArray<Diagnostic> diagnostics, SyntaxEditor editor, CancellationToken cancellationToken) { var semanticModel = await document.GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false); foreach (var diagnostic in diagnostics) { var location = diagnostic.Location; var expression = editor.OriginalRoot.FindNode(location.SourceSpan, getInnermostNodeForTie: true); var operation = semanticModel.GetOperation(expression, cancellationToken); RoslynDebug.AssertNotNull(operation); var pattern = CSharpUsePatternCombinatorsAnalyzer.Analyze(operation); RoslynDebug.AssertNotNull(pattern); var patternSyntax = AsPatternSyntax(pattern).WithAdditionalAnnotations(Formatter.Annotation); editor.ReplaceNode(expression, IsPatternExpression((ExpressionSyntax)pattern.Target.Syntax, patternSyntax)); } } private static PatternSyntax AsPatternSyntax(AnalyzedPattern pattern) { return pattern switch { Binary p => BinaryPattern( p.IsDisjunctive ? SyntaxKind.OrPattern : SyntaxKind.AndPattern, AsPatternSyntax(p.Left).Parenthesize(), Token(p.Token.LeadingTrivia, p.IsDisjunctive ? SyntaxKind.OrKeyword : SyntaxKind.AndKeyword, TriviaList(p.Token.GetAllTrailingTrivia())), AsPatternSyntax(p.Right).Parenthesize()), Constant p => ConstantPattern(AsExpressionSyntax(p.ExpressionSyntax, p)), Source p => p.PatternSyntax, Type p => TypePattern(p.TypeSyntax), Relational p => RelationalPattern(Token(MapToSyntaxKind(p.OperatorKind)), AsExpressionSyntax(p.Value, p)), Not p => UnaryPattern(AsPatternSyntax(p.Pattern).Parenthesize()), var p => throw ExceptionUtilities.UnexpectedValue(p) }; } private static ExpressionSyntax AsExpressionSyntax(ExpressionSyntax expr, AnalyzedPattern p) { var semanticModel = p.Target.SemanticModel; Debug.Assert(semanticModel != null); var type = semanticModel.GetTypeInfo(expr).Type; if (type != null) { if (expr.IsKind(SyntaxKind.DefaultLiteralExpression)) { // default literals are not permitted in patterns return DefaultExpression(type.GenerateTypeSyntax()); } var governingType = semanticModel.GetTypeInfo(p.Target.Syntax).Type; if (governingType != null && !governingType.Equals(type)) { return CastExpression(governingType.GenerateTypeSyntax(), expr.Parenthesize()).WithAdditionalAnnotations(Simplifier.Annotation); } } return expr.Parenthesize(); } private class MyCodeAction : CustomCodeActions.DocumentChangeAction { public MyCodeAction(string title, Func<CancellationToken, Task<Document>> createChangedDocument, string equivalenceKey) : base(title, createChangedDocument, equivalenceKey) { } internal override CodeActionPriority Priority => CodeActionPriority.Low; } } }
1
dotnet/roslyn
55,427
Fixes #50462
Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
Blokyk
2021-08-05T01:17:37Z
2021-08-25T05:42:59Z
fefb8c2110625bc4908db4bbdaa367b12bfb1069
fb4ac545a1f1f365e7df570637699d9085ea4f87
Fixes #50462. Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
./src/Compilers/CSharp/Portable/Symbols/SubstitutedTypeParameterSymbol.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable //#define DEBUG_ALPHA // turn on DEBUG_ALPHA to help diagnose issues around type parameter alpha-renaming using System; using System.Collections.Immutable; using System.Diagnostics; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Symbols { internal class SubstitutedTypeParameterSymbol : WrappedTypeParameterSymbol { private readonly Symbol _container; private readonly TypeMap _map; private readonly int _ordinal; #if DEBUG_ALPHA private static int _nextSequence = 1; private readonly int _mySequence; #endif internal SubstitutedTypeParameterSymbol(Symbol newContainer, TypeMap map, TypeParameterSymbol substitutedFrom, int ordinal) : base(substitutedFrom) { _container = newContainer; // it is important that we don't use the map here in the constructor, as the map is still being filled // in by TypeMap.WithAlphaRename. Instead, we can use the map lazily when yielding the constraints. _map = map; _ordinal = ordinal; #if DEBUG_ALPHA _mySequence = _nextSequence++; #endif } public override Symbol ContainingSymbol { get { return _container; } } public override TypeParameterSymbol OriginalDefinition { get { // A substituted type parameter symbol is used as a type parameter of a frame type for lambda-captured // variables within a generic method. In that case the frame's own type parameter is an original. return ContainingSymbol.OriginalDefinition != _underlyingTypeParameter.ContainingSymbol.OriginalDefinition ? this : _underlyingTypeParameter.OriginalDefinition; } } public override TypeParameterSymbol ReducedFrom { get { if (_container.Kind == SymbolKind.Method) { MethodSymbol reducedFrom = ((MethodSymbol)_container).ReducedFrom; if ((object)reducedFrom != null) { return reducedFrom.TypeParameters[this.Ordinal]; } } return null; } } public override int Ordinal { get { return _ordinal; } } public override string Name { get { return base.Name #if DEBUG_ALPHA + "#" + _mySequence #endif ; } } internal override ImmutableArray<TypeWithAnnotations> GetConstraintTypes(ConsList<TypeParameterSymbol> inProgress) { var constraintTypes = ArrayBuilder<TypeWithAnnotations>.GetInstance(); _map.SubstituteConstraintTypesDistinctWithoutModifiers(_underlyingTypeParameter, _underlyingTypeParameter.GetConstraintTypes(inProgress), constraintTypes, null); TypeWithAnnotations bestObjectConstraint = default; // Strip all Object constraints. for (int i = constraintTypes.Count - 1; i >= 0; i--) { TypeWithAnnotations type = constraintTypes[i]; if (ConstraintsHelper.IsObjectConstraint(type, ref bestObjectConstraint)) { constraintTypes.RemoveAt(i); } } if (bestObjectConstraint.HasType) { // See if we need to put Object! or Object~ back in order to preserve nullability information for the type parameter. if (ConstraintsHelper.IsObjectConstraintSignificant(CalculateIsNotNullableFromNonTypeConstraints(), bestObjectConstraint)) { Debug.Assert(!HasNotNullConstraint && !HasValueTypeConstraint); if (constraintTypes.Count == 0) { if (bestObjectConstraint.NullableAnnotation.IsOblivious() && !HasReferenceTypeConstraint) { bestObjectConstraint = default; } } else { foreach (TypeWithAnnotations constraintType in constraintTypes) { if (!ConstraintsHelper.IsObjectConstraintSignificant(IsNotNullableFromConstraintType(constraintType, out _), bestObjectConstraint)) { bestObjectConstraint = default; break; } } } if (bestObjectConstraint.HasType) { constraintTypes.Insert(0, bestObjectConstraint); } } } return constraintTypes.ToImmutableAndFree(); } internal override bool? IsNotNullable { get { if (_underlyingTypeParameter.ConstraintTypesNoUseSiteDiagnostics.IsEmpty) { return _underlyingTypeParameter.IsNotNullable; } else if (!HasNotNullConstraint && !HasValueTypeConstraint && !HasReferenceTypeConstraint) { var constraintTypes = ArrayBuilder<TypeWithAnnotations>.GetInstance(); _map.SubstituteConstraintTypesDistinctWithoutModifiers(_underlyingTypeParameter, _underlyingTypeParameter.GetConstraintTypes(ConsList<TypeParameterSymbol>.Empty), constraintTypes, null); return IsNotNullableFromConstraintTypes(constraintTypes.ToImmutableAndFree()); } return CalculateIsNotNullable(); } } internal override ImmutableArray<NamedTypeSymbol> GetInterfaces(ConsList<TypeParameterSymbol> inProgress) { return _map.SubstituteNamedTypes(_underlyingTypeParameter.GetInterfaces(inProgress)); } internal override NamedTypeSymbol GetEffectiveBaseClass(ConsList<TypeParameterSymbol> inProgress) { return _map.SubstituteNamedType(_underlyingTypeParameter.GetEffectiveBaseClass(inProgress)); } internal override TypeSymbol GetDeducedBaseType(ConsList<TypeParameterSymbol> inProgress) { return _map.SubstituteType(_underlyingTypeParameter.GetDeducedBaseType(inProgress)).AsTypeSymbolOnly(); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable //#define DEBUG_ALPHA // turn on DEBUG_ALPHA to help diagnose issues around type parameter alpha-renaming using System; using System.Collections.Immutable; using System.Diagnostics; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Symbols { internal class SubstitutedTypeParameterSymbol : WrappedTypeParameterSymbol { private readonly Symbol _container; private readonly TypeMap _map; private readonly int _ordinal; #if DEBUG_ALPHA private static int _nextSequence = 1; private readonly int _mySequence; #endif internal SubstitutedTypeParameterSymbol(Symbol newContainer, TypeMap map, TypeParameterSymbol substitutedFrom, int ordinal) : base(substitutedFrom) { _container = newContainer; // it is important that we don't use the map here in the constructor, as the map is still being filled // in by TypeMap.WithAlphaRename. Instead, we can use the map lazily when yielding the constraints. _map = map; _ordinal = ordinal; #if DEBUG_ALPHA _mySequence = _nextSequence++; #endif } public override Symbol ContainingSymbol { get { return _container; } } public override TypeParameterSymbol OriginalDefinition { get { // A substituted type parameter symbol is used as a type parameter of a frame type for lambda-captured // variables within a generic method. In that case the frame's own type parameter is an original. return ContainingSymbol.OriginalDefinition != _underlyingTypeParameter.ContainingSymbol.OriginalDefinition ? this : _underlyingTypeParameter.OriginalDefinition; } } public override TypeParameterSymbol ReducedFrom { get { if (_container.Kind == SymbolKind.Method) { MethodSymbol reducedFrom = ((MethodSymbol)_container).ReducedFrom; if ((object)reducedFrom != null) { return reducedFrom.TypeParameters[this.Ordinal]; } } return null; } } public override int Ordinal { get { return _ordinal; } } public override string Name { get { return base.Name #if DEBUG_ALPHA + "#" + _mySequence #endif ; } } internal override ImmutableArray<TypeWithAnnotations> GetConstraintTypes(ConsList<TypeParameterSymbol> inProgress) { var constraintTypes = ArrayBuilder<TypeWithAnnotations>.GetInstance(); _map.SubstituteConstraintTypesDistinctWithoutModifiers(_underlyingTypeParameter, _underlyingTypeParameter.GetConstraintTypes(inProgress), constraintTypes, null); TypeWithAnnotations bestObjectConstraint = default; // Strip all Object constraints. for (int i = constraintTypes.Count - 1; i >= 0; i--) { TypeWithAnnotations type = constraintTypes[i]; if (ConstraintsHelper.IsObjectConstraint(type, ref bestObjectConstraint)) { constraintTypes.RemoveAt(i); } } if (bestObjectConstraint.HasType) { // See if we need to put Object! or Object~ back in order to preserve nullability information for the type parameter. if (ConstraintsHelper.IsObjectConstraintSignificant(CalculateIsNotNullableFromNonTypeConstraints(), bestObjectConstraint)) { Debug.Assert(!HasNotNullConstraint && !HasValueTypeConstraint); if (constraintTypes.Count == 0) { if (bestObjectConstraint.NullableAnnotation.IsOblivious() && !HasReferenceTypeConstraint) { bestObjectConstraint = default; } } else { foreach (TypeWithAnnotations constraintType in constraintTypes) { if (!ConstraintsHelper.IsObjectConstraintSignificant(IsNotNullableFromConstraintType(constraintType, out _), bestObjectConstraint)) { bestObjectConstraint = default; break; } } } if (bestObjectConstraint.HasType) { constraintTypes.Insert(0, bestObjectConstraint); } } } return constraintTypes.ToImmutableAndFree(); } internal override bool? IsNotNullable { get { if (_underlyingTypeParameter.ConstraintTypesNoUseSiteDiagnostics.IsEmpty) { return _underlyingTypeParameter.IsNotNullable; } else if (!HasNotNullConstraint && !HasValueTypeConstraint && !HasReferenceTypeConstraint) { var constraintTypes = ArrayBuilder<TypeWithAnnotations>.GetInstance(); _map.SubstituteConstraintTypesDistinctWithoutModifiers(_underlyingTypeParameter, _underlyingTypeParameter.GetConstraintTypes(ConsList<TypeParameterSymbol>.Empty), constraintTypes, null); return IsNotNullableFromConstraintTypes(constraintTypes.ToImmutableAndFree()); } return CalculateIsNotNullable(); } } internal override ImmutableArray<NamedTypeSymbol> GetInterfaces(ConsList<TypeParameterSymbol> inProgress) { return _map.SubstituteNamedTypes(_underlyingTypeParameter.GetInterfaces(inProgress)); } internal override NamedTypeSymbol GetEffectiveBaseClass(ConsList<TypeParameterSymbol> inProgress) { return _map.SubstituteNamedType(_underlyingTypeParameter.GetEffectiveBaseClass(inProgress)); } internal override TypeSymbol GetDeducedBaseType(ConsList<TypeParameterSymbol> inProgress) { return _map.SubstituteType(_underlyingTypeParameter.GetDeducedBaseType(inProgress)).AsTypeSymbolOnly(); } } }
-1
dotnet/roslyn
55,427
Fixes #50462
Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
Blokyk
2021-08-05T01:17:37Z
2021-08-25T05:42:59Z
fefb8c2110625bc4908db4bbdaa367b12bfb1069
fb4ac545a1f1f365e7df570637699d9085ea4f87
Fixes #50462. Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
./src/Workspaces/Core/Portable/FindSymbols/FindReferences/FindReferencesSearchEngine.UnidirectionalSymbolSet.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Collections.Immutable; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; namespace Microsoft.CodeAnalysis.FindSymbols { internal partial class FindReferencesSearchEngine { /// <summary> /// Symbol set used when <see cref="FindReferencesSearchOptions.UnidirectionalHierarchyCascade"/> is <see /// langword="true"/>. This symbol set will only cascade in a uniform direction once it walks either up or down /// from the initial set of symbols. This is the symbol set used for features like 'Find Refs', where we only /// want to return location results for members that could feasible actually end up calling into that member at /// runtime. See the docs of <see cref="FindReferencesSearchOptions.UnidirectionalHierarchyCascade"/> for more /// information on this. /// </summary> private sealed class UnidirectionalSymbolSet : SymbolSet { private readonly HashSet<ISymbol> _initialAndDownSymbols; /// <summary> /// When we're doing a unidirectional find-references, the initial set of up-symbols can never change. /// That's because we have computed the up set entirely up front, and no down symbols can produce new /// up-symbols (as going down then up would not be unidirectional). /// </summary> private readonly ImmutableHashSet<ISymbol> _upSymbols; public UnidirectionalSymbolSet(FindReferencesSearchEngine engine, HashSet<ISymbol> initialSymbols, HashSet<ISymbol> upSymbols) : base(engine) { _initialAndDownSymbols = initialSymbols; _upSymbols = upSymbols.ToImmutableHashSet(); } public override ImmutableArray<ISymbol> GetAllSymbols() { using var _ = ArrayBuilder<ISymbol>.GetInstance(_upSymbols.Count + _initialAndDownSymbols.Count, out var result); result.AddRange(_upSymbols); result.AddRange(_initialAndDownSymbols); result.RemoveDuplicates(); return result.ToImmutable(); } public override async Task InheritanceCascadeAsync(Project project, CancellationToken cancellationToken) { // Start searching using the existing set of symbols found at the start (or anything found below that). var workQueue = new Stack<ISymbol>(); workQueue.Push(_initialAndDownSymbols); var projects = ImmutableHashSet.Create(project); while (workQueue.Count > 0) { var current = workQueue.Pop(); // Keep adding symbols downwards in this project as long as we keep finding new symbols. await AddDownSymbolsAsync(this.Engine, current, _initialAndDownSymbols, workQueue, projects, 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.Collections.Generic; using System.Collections.Immutable; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; namespace Microsoft.CodeAnalysis.FindSymbols { internal partial class FindReferencesSearchEngine { /// <summary> /// Symbol set used when <see cref="FindReferencesSearchOptions.UnidirectionalHierarchyCascade"/> is <see /// langword="true"/>. This symbol set will only cascade in a uniform direction once it walks either up or down /// from the initial set of symbols. This is the symbol set used for features like 'Find Refs', where we only /// want to return location results for members that could feasible actually end up calling into that member at /// runtime. See the docs of <see cref="FindReferencesSearchOptions.UnidirectionalHierarchyCascade"/> for more /// information on this. /// </summary> private sealed class UnidirectionalSymbolSet : SymbolSet { private readonly HashSet<ISymbol> _initialAndDownSymbols; /// <summary> /// When we're doing a unidirectional find-references, the initial set of up-symbols can never change. /// That's because we have computed the up set entirely up front, and no down symbols can produce new /// up-symbols (as going down then up would not be unidirectional). /// </summary> private readonly ImmutableHashSet<ISymbol> _upSymbols; public UnidirectionalSymbolSet(FindReferencesSearchEngine engine, HashSet<ISymbol> initialSymbols, HashSet<ISymbol> upSymbols) : base(engine) { _initialAndDownSymbols = initialSymbols; _upSymbols = upSymbols.ToImmutableHashSet(); } public override ImmutableArray<ISymbol> GetAllSymbols() { using var _ = ArrayBuilder<ISymbol>.GetInstance(_upSymbols.Count + _initialAndDownSymbols.Count, out var result); result.AddRange(_upSymbols); result.AddRange(_initialAndDownSymbols); result.RemoveDuplicates(); return result.ToImmutable(); } public override async Task InheritanceCascadeAsync(Project project, CancellationToken cancellationToken) { // Start searching using the existing set of symbols found at the start (or anything found below that). var workQueue = new Stack<ISymbol>(); workQueue.Push(_initialAndDownSymbols); var projects = ImmutableHashSet.Create(project); while (workQueue.Count > 0) { var current = workQueue.Pop(); // Keep adding symbols downwards in this project as long as we keep finding new symbols. await AddDownSymbolsAsync(this.Engine, current, _initialAndDownSymbols, workQueue, projects, cancellationToken).ConfigureAwait(false); } } } } }
-1
dotnet/roslyn
55,427
Fixes #50462
Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
Blokyk
2021-08-05T01:17:37Z
2021-08-25T05:42:59Z
fefb8c2110625bc4908db4bbdaa367b12bfb1069
fb4ac545a1f1f365e7df570637699d9085ea4f87
Fixes #50462. Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
./src/Features/Core/Portable/Common/TaggedTextStyle.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; namespace Microsoft.CodeAnalysis { [Flags] internal enum TaggedTextStyle { None = 0, Strong = 1 << 0, Emphasis = 1 << 1, Underline = 1 << 2, Code = 1 << 3, PreserveWhitespace = 1 << 4, } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; namespace Microsoft.CodeAnalysis { [Flags] internal enum TaggedTextStyle { None = 0, Strong = 1 << 0, Emphasis = 1 << 1, Underline = 1 << 2, Code = 1 << 3, PreserveWhitespace = 1 << 4, } }
-1
dotnet/roslyn
55,427
Fixes #50462
Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
Blokyk
2021-08-05T01:17:37Z
2021-08-25T05:42:59Z
fefb8c2110625bc4908db4bbdaa367b12bfb1069
fb4ac545a1f1f365e7df570637699d9085ea4f87
Fixes #50462. Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
./src/Features/Core/Portable/ImplementInterface/AbstractImplementInterfaceService.State.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Generic; using System.Collections.Immutable; using System.Threading; using Microsoft.CodeAnalysis.CodeGeneration; using Microsoft.CodeAnalysis.Shared.Extensions; namespace Microsoft.CodeAnalysis.ImplementInterface { internal abstract partial class AbstractImplementInterfaceService { internal class State { public SyntaxNode Location { get; } public SyntaxNode ClassOrStructDecl { get; } public INamedTypeSymbol ClassOrStructType { get; } public IEnumerable<INamedTypeSymbol> InterfaceTypes { get; } public SemanticModel Model { get; } // The members that are not implemented at all. public ImmutableArray<(INamedTypeSymbol type, ImmutableArray<ISymbol> members)> MembersWithoutExplicitOrImplicitImplementationWhichCanBeImplicitlyImplemented { get; private set; } = ImmutableArray<(INamedTypeSymbol type, ImmutableArray<ISymbol> members)>.Empty; public ImmutableArray<(INamedTypeSymbol type, ImmutableArray<ISymbol> members)> MembersWithoutExplicitOrImplicitImplementation { get; private set; } = ImmutableArray<(INamedTypeSymbol type, ImmutableArray<ISymbol> members)>.Empty; // The members that have no explicit implementation. public ImmutableArray<(INamedTypeSymbol type, ImmutableArray<ISymbol> members)> MembersWithoutExplicitImplementation { get; private set; } = ImmutableArray<(INamedTypeSymbol type, ImmutableArray<ISymbol> members)>.Empty; public State(SyntaxNode interfaceNode, SyntaxNode classOrStructDecl, INamedTypeSymbol classOrStructType, IEnumerable<INamedTypeSymbol> interfaceTypes, SemanticModel model) { Location = interfaceNode; ClassOrStructDecl = classOrStructDecl; ClassOrStructType = classOrStructType; InterfaceTypes = interfaceTypes; Model = model; } public static State Generate( AbstractImplementInterfaceService service, Document document, SemanticModel model, SyntaxNode interfaceNode, CancellationToken cancellationToken) { if (!service.TryInitializeState(document, model, interfaceNode, cancellationToken, out var classOrStructDecl, out var classOrStructType, out var interfaceTypes)) { return null; } if (!CodeGenerator.CanAdd(document.Project.Solution, classOrStructType, cancellationToken)) { return null; } var state = new State(interfaceNode, classOrStructDecl, classOrStructType, interfaceTypes, model); if (service.CanImplementImplicitly) { state.MembersWithoutExplicitOrImplicitImplementationWhichCanBeImplicitlyImplemented = state.ClassOrStructType.GetAllUnimplementedMembers( interfaceTypes, includeMembersRequiringExplicitImplementation: false, cancellationToken); state.MembersWithoutExplicitOrImplicitImplementation = state.ClassOrStructType.GetAllUnimplementedMembers( interfaceTypes, includeMembersRequiringExplicitImplementation: true, cancellationToken); state.MembersWithoutExplicitImplementation = state.ClassOrStructType.GetAllUnimplementedExplicitMembers( interfaceTypes, cancellationToken); var allMembersImplemented = state.MembersWithoutExplicitOrImplicitImplementationWhichCanBeImplicitlyImplemented.Length == 0; var allMembersImplementedExplicitly = state.MembersWithoutExplicitImplementation.Length == 0; return !allMembersImplementedExplicitly || !allMembersImplemented ? state : null; } else { // We put the members in this bucket so that the code fix title is "Implement Interface" state.MembersWithoutExplicitOrImplicitImplementationWhichCanBeImplicitlyImplemented = state.ClassOrStructType.GetAllUnimplementedExplicitMembers( interfaceTypes, cancellationToken); var allMembersImplemented = state.MembersWithoutExplicitOrImplicitImplementationWhichCanBeImplicitlyImplemented.Length == 0; return !allMembersImplemented ? state : 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.Generic; using System.Collections.Immutable; using System.Threading; using Microsoft.CodeAnalysis.CodeGeneration; using Microsoft.CodeAnalysis.Shared.Extensions; namespace Microsoft.CodeAnalysis.ImplementInterface { internal abstract partial class AbstractImplementInterfaceService { internal class State { public SyntaxNode Location { get; } public SyntaxNode ClassOrStructDecl { get; } public INamedTypeSymbol ClassOrStructType { get; } public IEnumerable<INamedTypeSymbol> InterfaceTypes { get; } public SemanticModel Model { get; } // The members that are not implemented at all. public ImmutableArray<(INamedTypeSymbol type, ImmutableArray<ISymbol> members)> MembersWithoutExplicitOrImplicitImplementationWhichCanBeImplicitlyImplemented { get; private set; } = ImmutableArray<(INamedTypeSymbol type, ImmutableArray<ISymbol> members)>.Empty; public ImmutableArray<(INamedTypeSymbol type, ImmutableArray<ISymbol> members)> MembersWithoutExplicitOrImplicitImplementation { get; private set; } = ImmutableArray<(INamedTypeSymbol type, ImmutableArray<ISymbol> members)>.Empty; // The members that have no explicit implementation. public ImmutableArray<(INamedTypeSymbol type, ImmutableArray<ISymbol> members)> MembersWithoutExplicitImplementation { get; private set; } = ImmutableArray<(INamedTypeSymbol type, ImmutableArray<ISymbol> members)>.Empty; public State(SyntaxNode interfaceNode, SyntaxNode classOrStructDecl, INamedTypeSymbol classOrStructType, IEnumerable<INamedTypeSymbol> interfaceTypes, SemanticModel model) { Location = interfaceNode; ClassOrStructDecl = classOrStructDecl; ClassOrStructType = classOrStructType; InterfaceTypes = interfaceTypes; Model = model; } public static State Generate( AbstractImplementInterfaceService service, Document document, SemanticModel model, SyntaxNode interfaceNode, CancellationToken cancellationToken) { if (!service.TryInitializeState(document, model, interfaceNode, cancellationToken, out var classOrStructDecl, out var classOrStructType, out var interfaceTypes)) { return null; } if (!CodeGenerator.CanAdd(document.Project.Solution, classOrStructType, cancellationToken)) { return null; } var state = new State(interfaceNode, classOrStructDecl, classOrStructType, interfaceTypes, model); if (service.CanImplementImplicitly) { state.MembersWithoutExplicitOrImplicitImplementationWhichCanBeImplicitlyImplemented = state.ClassOrStructType.GetAllUnimplementedMembers( interfaceTypes, includeMembersRequiringExplicitImplementation: false, cancellationToken); state.MembersWithoutExplicitOrImplicitImplementation = state.ClassOrStructType.GetAllUnimplementedMembers( interfaceTypes, includeMembersRequiringExplicitImplementation: true, cancellationToken); state.MembersWithoutExplicitImplementation = state.ClassOrStructType.GetAllUnimplementedExplicitMembers( interfaceTypes, cancellationToken); var allMembersImplemented = state.MembersWithoutExplicitOrImplicitImplementationWhichCanBeImplicitlyImplemented.Length == 0; var allMembersImplementedExplicitly = state.MembersWithoutExplicitImplementation.Length == 0; return !allMembersImplementedExplicitly || !allMembersImplemented ? state : null; } else { // We put the members in this bucket so that the code fix title is "Implement Interface" state.MembersWithoutExplicitOrImplicitImplementationWhichCanBeImplicitlyImplemented = state.ClassOrStructType.GetAllUnimplementedExplicitMembers( interfaceTypes, cancellationToken); var allMembersImplemented = state.MembersWithoutExplicitOrImplicitImplementationWhichCanBeImplicitlyImplemented.Length == 0; return !allMembersImplemented ? state : null; } } } } }
-1
dotnet/roslyn
55,427
Fixes #50462
Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
Blokyk
2021-08-05T01:17:37Z
2021-08-25T05:42:59Z
fefb8c2110625bc4908db4bbdaa367b12bfb1069
fb4ac545a1f1f365e7df570637699d9085ea4f87
Fixes #50462. Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
./src/Features/Core/Portable/Diagnostics/EngineV2/DiagnosticIncrementalAnalyzer.AnalysisData.cs
// Licensed to the .NET Foundation under one or more agreements. // 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.Diagnostics; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Workspaces.Diagnostics; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Diagnostics.EngineV2 { internal partial class DiagnosticIncrementalAnalyzer { /// <summary> /// Simple data holder for local diagnostics for an analyzer /// </summary> private readonly struct DocumentAnalysisData { public static readonly DocumentAnalysisData Empty = new(VersionStamp.Default, ImmutableArray<DiagnosticData>.Empty); /// <summary> /// Version of the diagnostic data. /// </summary> public readonly VersionStamp Version; /// <summary> /// Current data that matches the version. /// </summary> public readonly ImmutableArray<DiagnosticData> Items; /// <summary> /// Last set of data we broadcasted to outer world, or <see langword="default"/>. /// </summary> public readonly ImmutableArray<DiagnosticData> OldItems; public DocumentAnalysisData(VersionStamp version, ImmutableArray<DiagnosticData> items) { Debug.Assert(!items.IsDefault); Version = version; Items = items; OldItems = default; } public DocumentAnalysisData(VersionStamp version, ImmutableArray<DiagnosticData> oldItems, ImmutableArray<DiagnosticData> newItems) : this(version, newItems) { Debug.Assert(!oldItems.IsDefault); OldItems = oldItems; } public DocumentAnalysisData ToPersistData() => new(Version, Items); public bool FromCache { get { return OldItems.IsDefault; } } } /// <summary> /// Data holder for all diagnostics for a project for an analyzer /// </summary> private readonly struct ProjectAnalysisData { /// <summary> /// ProjectId of this data /// </summary> public readonly ProjectId ProjectId; /// <summary> /// Version of the Items /// </summary> public readonly VersionStamp Version; /// <summary> /// Current data that matches the version /// </summary> public readonly ImmutableDictionary<DiagnosticAnalyzer, DiagnosticAnalysisResult> Result; /// <summary> /// When present, holds onto last data we broadcasted to outer world. /// </summary> public readonly ImmutableDictionary<DiagnosticAnalyzer, DiagnosticAnalysisResult>? OldResult; public ProjectAnalysisData(ProjectId projectId, VersionStamp version, ImmutableDictionary<DiagnosticAnalyzer, DiagnosticAnalysisResult> result) { ProjectId = projectId; Version = version; Result = result; OldResult = null; } public ProjectAnalysisData( ProjectId projectId, VersionStamp version, ImmutableDictionary<DiagnosticAnalyzer, DiagnosticAnalysisResult> oldResult, ImmutableDictionary<DiagnosticAnalyzer, DiagnosticAnalysisResult> newResult) : this(projectId, version, newResult) { OldResult = oldResult; } public DiagnosticAnalysisResult GetResult(DiagnosticAnalyzer analyzer) => GetResultOrEmpty(Result, analyzer, ProjectId, Version); public static async Task<ProjectAnalysisData> CreateAsync(Project project, IEnumerable<StateSet> stateSets, bool avoidLoadingData, CancellationToken cancellationToken) { VersionStamp? version = null; var builder = ImmutableDictionary.CreateBuilder<DiagnosticAnalyzer, DiagnosticAnalysisResult>(); foreach (var stateSet in stateSets) { var state = stateSet.GetOrCreateProjectState(project.Id); var result = await state.GetAnalysisDataAsync(project, avoidLoadingData, cancellationToken).ConfigureAwait(false); Contract.ThrowIfFalse(project.Id == result.ProjectId); if (!version.HasValue) { version = result.Version; } else if (version.Value != VersionStamp.Default && version.Value != result.Version) { // if not all version is same, set version as default. // this can happen at the initial data loading or // when document is closed and we put active file state to project state version = VersionStamp.Default; } builder.Add(stateSet.Analyzer, result); } if (!version.HasValue) { // there is no saved data to return. return new ProjectAnalysisData(project.Id, VersionStamp.Default, ImmutableDictionary<DiagnosticAnalyzer, DiagnosticAnalysisResult>.Empty); } return new ProjectAnalysisData(project.Id, version.Value, builder.ToImmutable()); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Workspaces.Diagnostics; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Diagnostics.EngineV2 { internal partial class DiagnosticIncrementalAnalyzer { /// <summary> /// Simple data holder for local diagnostics for an analyzer /// </summary> private readonly struct DocumentAnalysisData { public static readonly DocumentAnalysisData Empty = new(VersionStamp.Default, ImmutableArray<DiagnosticData>.Empty); /// <summary> /// Version of the diagnostic data. /// </summary> public readonly VersionStamp Version; /// <summary> /// Current data that matches the version. /// </summary> public readonly ImmutableArray<DiagnosticData> Items; /// <summary> /// Last set of data we broadcasted to outer world, or <see langword="default"/>. /// </summary> public readonly ImmutableArray<DiagnosticData> OldItems; public DocumentAnalysisData(VersionStamp version, ImmutableArray<DiagnosticData> items) { Debug.Assert(!items.IsDefault); Version = version; Items = items; OldItems = default; } public DocumentAnalysisData(VersionStamp version, ImmutableArray<DiagnosticData> oldItems, ImmutableArray<DiagnosticData> newItems) : this(version, newItems) { Debug.Assert(!oldItems.IsDefault); OldItems = oldItems; } public DocumentAnalysisData ToPersistData() => new(Version, Items); public bool FromCache { get { return OldItems.IsDefault; } } } /// <summary> /// Data holder for all diagnostics for a project for an analyzer /// </summary> private readonly struct ProjectAnalysisData { /// <summary> /// ProjectId of this data /// </summary> public readonly ProjectId ProjectId; /// <summary> /// Version of the Items /// </summary> public readonly VersionStamp Version; /// <summary> /// Current data that matches the version /// </summary> public readonly ImmutableDictionary<DiagnosticAnalyzer, DiagnosticAnalysisResult> Result; /// <summary> /// When present, holds onto last data we broadcasted to outer world. /// </summary> public readonly ImmutableDictionary<DiagnosticAnalyzer, DiagnosticAnalysisResult>? OldResult; public ProjectAnalysisData(ProjectId projectId, VersionStamp version, ImmutableDictionary<DiagnosticAnalyzer, DiagnosticAnalysisResult> result) { ProjectId = projectId; Version = version; Result = result; OldResult = null; } public ProjectAnalysisData( ProjectId projectId, VersionStamp version, ImmutableDictionary<DiagnosticAnalyzer, DiagnosticAnalysisResult> oldResult, ImmutableDictionary<DiagnosticAnalyzer, DiagnosticAnalysisResult> newResult) : this(projectId, version, newResult) { OldResult = oldResult; } public DiagnosticAnalysisResult GetResult(DiagnosticAnalyzer analyzer) => GetResultOrEmpty(Result, analyzer, ProjectId, Version); public static async Task<ProjectAnalysisData> CreateAsync(Project project, IEnumerable<StateSet> stateSets, bool avoidLoadingData, CancellationToken cancellationToken) { VersionStamp? version = null; var builder = ImmutableDictionary.CreateBuilder<DiagnosticAnalyzer, DiagnosticAnalysisResult>(); foreach (var stateSet in stateSets) { var state = stateSet.GetOrCreateProjectState(project.Id); var result = await state.GetAnalysisDataAsync(project, avoidLoadingData, cancellationToken).ConfigureAwait(false); Contract.ThrowIfFalse(project.Id == result.ProjectId); if (!version.HasValue) { version = result.Version; } else if (version.Value != VersionStamp.Default && version.Value != result.Version) { // if not all version is same, set version as default. // this can happen at the initial data loading or // when document is closed and we put active file state to project state version = VersionStamp.Default; } builder.Add(stateSet.Analyzer, result); } if (!version.HasValue) { // there is no saved data to return. return new ProjectAnalysisData(project.Id, VersionStamp.Default, ImmutableDictionary<DiagnosticAnalyzer, DiagnosticAnalysisResult>.Empty); } return new ProjectAnalysisData(project.Id, version.Value, builder.ToImmutable()); } } } }
-1
dotnet/roslyn
55,427
Fixes #50462
Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
Blokyk
2021-08-05T01:17:37Z
2021-08-25T05:42:59Z
fefb8c2110625bc4908db4bbdaa367b12bfb1069
fb4ac545a1f1f365e7df570637699d9085ea4f87
Fixes #50462. Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
./src/Analyzers/CSharp/Tests/UseConditionalExpression/UseConditionalExpressionForReturnTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.UseConditionalExpression; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Diagnostics; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; using Xunit.Abstractions; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.UseConditionalExpression { public partial class UseConditionalExpressionForReturnTests : AbstractCSharpDiagnosticProviderBasedUserDiagnosticTest { public UseConditionalExpressionForReturnTests(ITestOutputHelper logger) : base(logger) { } internal override (DiagnosticAnalyzer, CodeFixProvider) CreateDiagnosticProviderAndFixer(Workspace workspace) => (new CSharpUseConditionalExpressionForReturnDiagnosticAnalyzer(), new CSharpUseConditionalExpressionForReturnCodeFixProvider()); [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseConditionalExpression)] public async Task TestOnSimpleReturn() { await TestInRegularAndScript1Async( @" class C { int M() { [||]if (true) { return 0; } else { return 1; } } }", @" class C { int M() { return true ? 0 : 1; } }"); } [WorkItem(43291, "https://github.com/dotnet/roslyn/issues/43291")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseConditionalExpression)] public async Task TestOnSimpleReturn_Throw1() { await TestInRegularAndScript1Async( @" class C { int M() { [||]if (true) { throw new System.Exception(); } else { return 1; } } }", @" class C { int M() { return true ? throw new System.Exception() : 1; } }"); } [WorkItem(43291, "https://github.com/dotnet/roslyn/issues/43291")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseConditionalExpression)] public async Task TestOnSimpleReturn_Throw2() { await TestInRegularAndScript1Async( @" class C { int M() { [||]if (true) { return 0; } else { throw new System.Exception(); } } }", @" class C { int M() { return true ? 0 : throw new System.Exception(); } }"); } [WorkItem(43291, "https://github.com/dotnet/roslyn/issues/43291")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseConditionalExpression)] public async Task TestNotWithTwoThrows() { await TestMissingAsync( @" class C { int M() { [||]if (true) { throw new System.Exception(); } else { throw new System.Exception(); } } }"); } [WorkItem(43291, "https://github.com/dotnet/roslyn/issues/43291")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseConditionalExpression)] public async Task TestNotOnSimpleReturn_Throw1_CSharp6() { await TestMissingAsync( @" class C { int M() { [||]if (true) { throw new System.Exception(); } else { return 1; } } }", parameters: new TestParameters(parseOptions: CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.CSharp6))); } [WorkItem(43291, "https://github.com/dotnet/roslyn/issues/43291")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseConditionalExpression)] public async Task TestNotWithSimpleThrow() { await TestMissingAsync( @" class C { int M() { [||]if (true) { throw; } else { return 1; } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseConditionalExpression)] public async Task TestOnSimpleReturnNoBlocks() { await TestInRegularAndScript1Async( @" class C { int M() { [||]if (true) return 0; else return 1; } }", @" class C { int M() { return true ? 0 : 1; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseConditionalExpression)] public async Task TestOnSimpleReturnNoBlocks_NotInBlock() { await TestInRegularAndScript1Async( @" class C { int M() { if (true) [||]if (true) return 0; else return 1; } }", @" class C { int M() { if (true) return true ? 0 : 1; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseConditionalExpression)] public async Task TestMissingReturnValue1() { await TestMissingInRegularAndScriptAsync( @" class C { int M() { [||]if (true) { return 0; } else { return; } } }"); } [WorkItem(43291, "https://github.com/dotnet/roslyn/issues/43291")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseConditionalExpression)] public async Task TestMissingReturnValue1_Throw() { await TestMissingInRegularAndScriptAsync( @" class C { int M() { [||]if (true) { throw new System.Exception(); } else { return; } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseConditionalExpression)] public async Task TestMissingReturnValue2() { await TestMissingInRegularAndScriptAsync( @" class C { int M() { [||]if (true) { return; } else { return 1; } } }"); } [WorkItem(43291, "https://github.com/dotnet/roslyn/issues/43291")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseConditionalExpression)] public async Task TestMissingReturnValue2_Throw() { await TestMissingInRegularAndScriptAsync( @" class C { int M() { [||]if (true) { return; } else { throw new System.Exception(); } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseConditionalExpression)] public async Task TestMissingReturnValue3() { await TestMissingInRegularAndScriptAsync( @" class C { int M() { [||]if (true) { return; } else { return; } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseConditionalExpression)] public async Task TestWithNoElseBlockButFollowingReturn() { await TestInRegularAndScript1Async( @" class C { void M() { [||]if (true) { return 0; } return 1; } }", @" class C { void M() { return true ? 0 : 1; } }"); } [WorkItem(43291, "https://github.com/dotnet/roslyn/issues/43291")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseConditionalExpression)] public async Task TestWithNoElseBlockButFollowingReturn_Throw1() { await TestInRegularAndScript1Async( @" class C { void M() { [||]if (true) { throw new System.Exception(); } return 1; } }", @" class C { void M() { return true ? throw new System.Exception() : 1; } }"); } [WorkItem(43291, "https://github.com/dotnet/roslyn/issues/43291")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseConditionalExpression)] public async Task TestWithNoElseBlockButFollowingReturn_Throw2() { await TestInRegularAndScript1Async( @" class C { void M() { [||]if (true) { return 0; } throw new System.Exception(); } }", @" class C { void M() { return true ? 0 : throw new System.Exception(); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseConditionalExpression)] public async Task TestMissingWithoutElse() { await TestMissingInRegularAndScriptAsync( @" class C { int M() { [||]if (true) { return 0; } } }"); } [WorkItem(43291, "https://github.com/dotnet/roslyn/issues/43291")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseConditionalExpression)] public async Task TestMissingWithoutElse_Throw() { await TestMissingInRegularAndScriptAsync( @" class C { int M() { [||]if (true) { throw new System.Exception(); } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseConditionalExpression)] public async Task TestConversion1() { await TestInRegularAndScript1Async( @" class C { object M() { [||]if (true) { return ""a""; } else { return ""b""; } } }", @" class C { object M() { return true ? ""a"" : ""b""; } }"); } [WorkItem(43291, "https://github.com/dotnet/roslyn/issues/43291")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseConditionalExpression)] public async Task TestConversion1_Throw1() { await TestInRegularAndScript1Async( @" class C { object M() { [||]if (true) { throw new System.Exception(); } else { return ""b""; } } }", @" class C { object M() { return true ? throw new System.Exception() : ""b""; } }"); } [WorkItem(43291, "https://github.com/dotnet/roslyn/issues/43291")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseConditionalExpression)] public async Task TestConversion1_Throw2() { await TestInRegularAndScript1Async( @" class C { object M() { [||]if (true) { return ""a""; } else { throw new System.Exception(); } } }", @" class C { object M() { return true ? ""a"" : throw new System.Exception(); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseConditionalExpression)] public async Task TestConversion2() { await TestInRegularAndScript1Async( @" class C { string M() { [||]if (true) { return ""a""; } else { return null; } } }", @" class C { string M() { return true ? ""a"" : null; } }"); } [WorkItem(43291, "https://github.com/dotnet/roslyn/issues/43291")] [Theory, Trait(Traits.Feature, Traits.Features.CodeActionsUseConditionalExpression)] [InlineData(LanguageVersion.CSharp8, "(string)null")] [InlineData(LanguageVersion.CSharp9, "null")] public async Task TestConversion2_Throw1(LanguageVersion languageVersion, string expectedFalseExpression) { await TestInRegularAndScript1Async( @" class C { string M() { [||]if (true) { throw new System.Exception(); } else { return null; } } }", @" class C { string M() { return true ? throw new System.Exception() : " + expectedFalseExpression + @"; } }", parameters: new(parseOptions: CSharpParseOptions.Default.WithLanguageVersion(languageVersion))); } [WorkItem(43291, "https://github.com/dotnet/roslyn/issues/43291")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseConditionalExpression)] public async Task TestConversion2_Throw2() { await TestInRegularAndScript1Async( @" class C { string M() { [||]if (true) { return ""a""; } else { throw new System.Exception(); } } }", @" class C { string M() { return true ? ""a"" : throw new System.Exception(); } }"); } [Theory, Trait(Traits.Feature, Traits.Features.CodeActionsUseConditionalExpression)] [InlineData(LanguageVersion.CSharp8, "(string)null")] [InlineData(LanguageVersion.CSharp9, "null")] public async Task TestConversion3(LanguageVersion languageVersion, string expectedFalseExpression) { await TestInRegularAndScript1Async( @" class C { string M() { [||]if (true) { return null; } else { return null; } } }", @" class C { string M() { return true ? null : " + expectedFalseExpression + @"; } }", parameters: new(parseOptions: CSharpParseOptions.Default.WithLanguageVersion(languageVersion))); } [WorkItem(43291, "https://github.com/dotnet/roslyn/issues/43291")] [Theory, Trait(Traits.Feature, Traits.Features.CodeActionsUseConditionalExpression)] [InlineData(LanguageVersion.CSharp8, "(string)null")] [InlineData(LanguageVersion.CSharp9, "null")] public async Task TestConversion3_Throw1(LanguageVersion languageVersion, string expectedFalseExpression) { await TestInRegularAndScript1Async( @" class C { string M() { [||]if (true) { throw new System.Exception(); } else { return null; } } }", @" class C { string M() { return true ? throw new System.Exception() : " + expectedFalseExpression + @"; } }", parameters: new(parseOptions: CSharpParseOptions.Default.WithLanguageVersion(languageVersion))); } [WorkItem(43291, "https://github.com/dotnet/roslyn/issues/43291")] [Theory, Trait(Traits.Feature, Traits.Features.CodeActionsUseConditionalExpression)] [InlineData(LanguageVersion.CSharp8, "(string)null")] [InlineData(LanguageVersion.CSharp9, "null")] public async Task TestConversion3_Throw2(LanguageVersion languageVersion, string expectedTrue) { await TestInRegularAndScript1Async( @" class C { string M() { [||]if (true) { return null; } else { throw new System.Exception(); } } }", @" class C { string M() { return true ? " + expectedTrue + @" : throw new System.Exception(); } }", parameters: new(parseOptions: CSharpParseOptions.Default.WithLanguageVersion(languageVersion))); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseConditionalExpression)] public async Task TestKeepTriviaAroundIf() { await TestInRegularAndScript1Async( @" class C { int M() { // leading [||]if (true) { return 0; } else { return 1; } // trailing } }", @" class C { int M() { // leading return true ? 0 : 1; // trailing } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseConditionalExpression)] public async Task TestFixAll1() { await TestInRegularAndScript1Async( @" class C { int M() { {|FixAllInDocument:if|} (true) { return 0; } else { return 1; } if (true) { return 2; } return 3; } }", @" class C { int M() { return true ? 0 : 1; return true ? 2 : 3; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseConditionalExpression)] public async Task TestMultiLine1() { await TestInRegularAndScript1Async( @" class C { int M() { [||]if (true) { return Foo( 1, 2, 3); } else { return 1; } } }", @" class C { int M() { return true ? Foo( 1, 2, 3) : 1; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseConditionalExpression)] public async Task TestMultiLine2() { await TestInRegularAndScript1Async( @" class C { int M() { [||]if (true) { return 0; } else { return Foo( 1, 2, 3); } } }", @" class C { int M() { return true ? 0 : Foo( 1, 2, 3); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseConditionalExpression)] public async Task TestMultiLine3() { await TestInRegularAndScript1Async( @" class C { int M() { [||]if (true) { return Foo( 1, 2, 3); } else { return Foo( 4, 5, 6); } } }", @" class C { int M() { return true ? Foo( 1, 2, 3) : Foo( 4, 5, 6); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseConditionalExpression)] public async Task TestElseIfWithBlock() { await TestInRegularAndScript1Async( @" class C { int M() { if (true) { } else [||]if (false) { return 1; } else { return 0; } } }", @" class C { int M() { if (true) { } else { return false ? 1 : 0; } } }"); } [WorkItem(43291, "https://github.com/dotnet/roslyn/issues/43291")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseConditionalExpression)] public async Task TestElseIfWithBlock_Throw1() { await TestInRegularAndScript1Async( @" class C { int M() { if (true) { } else [||]if (false) { throw new System.Exception(); } else { return 0; } } }", @" class C { int M() { if (true) { } else { return false ? throw new System.Exception() : 0; } } }"); } [WorkItem(43291, "https://github.com/dotnet/roslyn/issues/43291")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseConditionalExpression)] public async Task TestElseIfWithBlock_Throw2() { await TestInRegularAndScript1Async( @" class C { int M() { if (true) { } else [||]if (false) { return 1; } else { throw new System.Exception(); } } }", @" class C { int M() { if (true) { } else { return false ? 1 : throw new System.Exception(); } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseConditionalExpression)] public async Task TestElseIfWithoutBlock() { await TestInRegularAndScript1Async( @" class C { int M() { if (true) return 2; else [||]if (false) return 1; else return 0; } }", @" class C { int M() { if (true) return 2; else return false ? 1 : 0; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseConditionalExpression)] public async Task TestRefReturns1() { await TestInRegularAndScript1Async( @" class C { ref int M(ref int i, ref int j) { [||]if (true) { return ref i; } else { return ref j; } } }", @" class C { ref int M(ref int i, ref int j) { return ref true ? ref i : ref j; } }"); } [WorkItem(43291, "https://github.com/dotnet/roslyn/issues/43291")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseConditionalExpression)] public async Task TestRefReturns1_Throw1() { await TestMissingAsync( @" class C { ref int M(ref int i, ref int j) { [||]if (true) { throw new System.Exception(); } else { return ref j; } } }"); } [WorkItem(43291, "https://github.com/dotnet/roslyn/issues/43291")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseConditionalExpression)] public async Task TestRefReturns1_Throw2() { await TestMissingAsync( @" class C { ref int M(ref int i, ref int j) { [||]if (true) { return ref i; } else { throw new System.Exception(); } } }"); } [WorkItem(27960, "https://github.com/dotnet/roslyn/issues/27960")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseConditionalExpression)] public async Task TestOnYieldReturn() { await TestInRegularAndScript1Async( @" class C { int M() { [||]if (true) { yield return 0; } else { yield return 1; } } }", @" class C { int M() { yield return true ? 0 : 1; } }"); } [WorkItem(43291, "https://github.com/dotnet/roslyn/issues/43291")] [WorkItem(27960, "https://github.com/dotnet/roslyn/issues/27960")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseConditionalExpression)] public async Task TestOnYieldReturn_Throw1() { await TestInRegularAndScript1Async( @" class C { int M() { [||]if (true) { throw new System.Exception(); } else { yield return 1; } } }", @" class C { int M() { yield return true ? throw new System.Exception() : 1; } }"); } [WorkItem(43291, "https://github.com/dotnet/roslyn/issues/43291")] [WorkItem(27960, "https://github.com/dotnet/roslyn/issues/27960")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseConditionalExpression)] public async Task TestOnYieldReturn_Throw2() { await TestInRegularAndScript1Async( @" class C { int M() { [||]if (true) { yield return 0; } else { throw new System.Exception(); } } }", @" class C { int M() { yield return true ? 0 : throw new System.Exception(); } }"); } [WorkItem(27960, "https://github.com/dotnet/roslyn/issues/27960")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseConditionalExpression)] public async Task TestOnYieldReturn_IEnumerableReturnType() { await TestInRegularAndScript1Async( @" using System.Collections.Generic; class C { IEnumerable<int> M() { [||]if (true) { yield return 0; } else { yield return 1; } } }", @" using System.Collections.Generic; class C { IEnumerable<int> M() { yield return true ? 0 : 1; } }"); } [WorkItem(27960, "https://github.com/dotnet/roslyn/issues/27960")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseConditionalExpression)] public async Task TestNotOnMixedYields() { await TestMissingAsync( @" class C { int M() { [||]if (true) { yield break; } else { yield return 1; } } }"); } [WorkItem(43291, "https://github.com/dotnet/roslyn/issues/43291")] [WorkItem(27960, "https://github.com/dotnet/roslyn/issues/27960")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseConditionalExpression)] public async Task TestNotOnMixedYields_Throw1() { await TestMissingAsync( @" class C { int M() { [||]if (true) { yield break; } else { throw new System.Exception(); } } }"); } [WorkItem(27960, "https://github.com/dotnet/roslyn/issues/27960")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseConditionalExpression)] public async Task TestNotOnMixedYields_IEnumerableReturnType() { await TestMissingAsync( @" using System.Collections.Generic; class C { IEnumerable<int> M() { [||]if (true) { yield break; } else { yield return 1; } } }"); } [WorkItem(27960, "https://github.com/dotnet/roslyn/issues/27960")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseConditionalExpression)] public async Task TestNotWithNoElseBlockButFollowingYieldReturn() { await TestMissingAsync( @" class C { void M() { [||]if (true) { yield return 0; } yield return 1; } }"); } [WorkItem(43291, "https://github.com/dotnet/roslyn/issues/43291")] [WorkItem(27960, "https://github.com/dotnet/roslyn/issues/27960")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseConditionalExpression)] public async Task TestWithNoElseBlockButFollowingYieldReturn_Throw1() { await TestInRegularAndScript1Async( @" class C { void M() { [||]if (true) { throw new System.Exception(); } yield return 1; } }", @" class C { void M() { yield return true ? throw new System.Exception() : 1; } }"); } [WorkItem(43291, "https://github.com/dotnet/roslyn/issues/43291")] [WorkItem(27960, "https://github.com/dotnet/roslyn/issues/27960")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseConditionalExpression)] public async Task TestNotWithNoElseBlockButFollowingYieldReturn_Throw2() { await TestMissingAsync( @" class C { void M() { [||]if (true) { yield return 0; } throw new System.Exception(); } }"); } [WorkItem(27960, "https://github.com/dotnet/roslyn/issues/27960")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseConditionalExpression)] public async Task TestNotWithNoElseBlockButFollowingYieldReturn_IEnumerableReturnType() { await TestMissingAsync( @" using System.Collections.Generic; class C { IEnumerable<int> M() { [||]if (true) { yield return 0; } yield return 1; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseConditionalExpression)] public async Task TestReturnTrueFalse1() { await TestInRegularAndScript1Async( @" class C { bool M(int a) { [||]if (a == 0) { return true; } else { return false; } } }", @" class C { bool M(int a) { return a == 0; } }"); } [WorkItem(43291, "https://github.com/dotnet/roslyn/issues/43291")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseConditionalExpression)] public async Task TestReturnTrueFalse1_Throw1() { await TestInRegularAndScript1Async( @" class C { bool M(int a) { [||]if (a == 0) { throw new System.Exception(); } else { return false; } } }", @" class C { bool M(int a) { return a == 0 ? throw new System.Exception() : false; } }"); } [WorkItem(43291, "https://github.com/dotnet/roslyn/issues/43291")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseConditionalExpression)] public async Task TestReturnTrueFalse1_Throw2() { await TestInRegularAndScript1Async( @" class C { bool M(int a) { [||]if (a == 0) { return true; } else { throw new System.Exception(); } } }", @" class C { bool M(int a) { return a == 0 ? true : throw new System.Exception(); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseConditionalExpression)] public async Task TestReturnTrueFalse2() { await TestInRegularAndScript1Async( @" class C { bool M(int a) { [||]if (a == 0) { return false; } else { return true; } } }", @" class C { bool M(int a) { return a != 0; } }"); } [WorkItem(43291, "https://github.com/dotnet/roslyn/issues/43291")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseConditionalExpression)] public async Task TestReturnTrueFalse2_Throw1() { await TestInRegularAndScript1Async( @" class C { bool M(int a) { [||]if (a == 0) { throw new System.Exception(); } else { return true; } } }", @" class C { bool M(int a) { return a == 0 ? throw new System.Exception() : true; } }"); } [WorkItem(43291, "https://github.com/dotnet/roslyn/issues/43291")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseConditionalExpression)] public async Task TestReturnTrueFalse2_Throw2() { await TestInRegularAndScript1Async( @" class C { bool M(int a) { [||]if (a == 0) { return false; } else { throw new System.Exception(); } } }", @" class C { bool M(int a) { return a == 0 ? false : throw new System.Exception(); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseConditionalExpression)] public async Task TestReturnTrueFalse3() { await TestInRegularAndScript1Async( @" class C { bool M(int a) { [||]if (a == 0) { return false; } return true; } }", @" class C { bool M(int a) { return a != 0; } }"); } [WorkItem(43291, "https://github.com/dotnet/roslyn/issues/43291")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseConditionalExpression)] public async Task TestReturnTrueFalse3_Throw1() { await TestInRegularAndScript1Async( @" class C { bool M(int a) { [||]if (a == 0) { throw new System.Exception(); } return true; } }", @" class C { bool M(int a) { return a == 0 ? throw new System.Exception() : true; } }"); } [WorkItem(43291, "https://github.com/dotnet/roslyn/issues/43291")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseConditionalExpression)] public async Task TestReturnTrueFalse3_Throw2() { await TestInRegularAndScript1Async( @" class C { bool M(int a) { [||]if (a == 0) { return false; } throw new System.Exception(); } }", @" class C { bool M(int a) { return a == 0 ? false : throw new System.Exception(); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseConditionalExpression)] public async Task TestReturnTrueFalse4() { await TestInRegularAndScript1Async( @" using System.Collections.Generic; class C { IEnumerable<bool> M(int a) { [||]if (a == 0) { yield return false; } else { yield return true; } } }", @" using System.Collections.Generic; class C { IEnumerable<bool> M(int a) { yield return a != 0; } }"); } [WorkItem(43291, "https://github.com/dotnet/roslyn/issues/43291")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseConditionalExpression)] public async Task TestReturnTrueFalse4_Throw1() { await TestInRegularAndScript1Async( @" using System.Collections.Generic; class C { IEnumerable<bool> M(int a) { [||]if (a == 0) { throw new System.Exception(); } else { yield return true; } } }", @" using System.Collections.Generic; class C { IEnumerable<bool> M(int a) { yield return a == 0 ? throw new System.Exception() : true; } }"); } [WorkItem(43291, "https://github.com/dotnet/roslyn/issues/43291")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseConditionalExpression)] public async Task TestReturnTrueFalse4_Throw2() { await TestInRegularAndScript1Async( @" using System.Collections.Generic; class C { IEnumerable<bool> M(int a) { [||]if (a == 0) { yield return false; } else { throw new System.Exception(); } } }", @" using System.Collections.Generic; class C { IEnumerable<bool> M(int a) { yield return a == 0 ? false : throw new System.Exception(); } }"); } [WorkItem(36117, "https://github.com/dotnet/roslyn/issues/36117")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseConditionalExpression)] public async Task TestMissingWhenCrossingPreprocessorDirective() { await TestMissingInRegularAndScriptAsync( @" class C { int M() { bool check = true; #if true [||]if (check) return 3; #endif return 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. #nullable disable using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.UseConditionalExpression; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Diagnostics; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; using Xunit.Abstractions; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.UseConditionalExpression { public partial class UseConditionalExpressionForReturnTests : AbstractCSharpDiagnosticProviderBasedUserDiagnosticTest { public UseConditionalExpressionForReturnTests(ITestOutputHelper logger) : base(logger) { } internal override (DiagnosticAnalyzer, CodeFixProvider) CreateDiagnosticProviderAndFixer(Workspace workspace) => (new CSharpUseConditionalExpressionForReturnDiagnosticAnalyzer(), new CSharpUseConditionalExpressionForReturnCodeFixProvider()); [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseConditionalExpression)] public async Task TestOnSimpleReturn() { await TestInRegularAndScript1Async( @" class C { int M() { [||]if (true) { return 0; } else { return 1; } } }", @" class C { int M() { return true ? 0 : 1; } }"); } [WorkItem(43291, "https://github.com/dotnet/roslyn/issues/43291")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseConditionalExpression)] public async Task TestOnSimpleReturn_Throw1() { await TestInRegularAndScript1Async( @" class C { int M() { [||]if (true) { throw new System.Exception(); } else { return 1; } } }", @" class C { int M() { return true ? throw new System.Exception() : 1; } }"); } [WorkItem(43291, "https://github.com/dotnet/roslyn/issues/43291")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseConditionalExpression)] public async Task TestOnSimpleReturn_Throw2() { await TestInRegularAndScript1Async( @" class C { int M() { [||]if (true) { return 0; } else { throw new System.Exception(); } } }", @" class C { int M() { return true ? 0 : throw new System.Exception(); } }"); } [WorkItem(43291, "https://github.com/dotnet/roslyn/issues/43291")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseConditionalExpression)] public async Task TestNotWithTwoThrows() { await TestMissingAsync( @" class C { int M() { [||]if (true) { throw new System.Exception(); } else { throw new System.Exception(); } } }"); } [WorkItem(43291, "https://github.com/dotnet/roslyn/issues/43291")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseConditionalExpression)] public async Task TestNotOnSimpleReturn_Throw1_CSharp6() { await TestMissingAsync( @" class C { int M() { [||]if (true) { throw new System.Exception(); } else { return 1; } } }", parameters: new TestParameters(parseOptions: CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.CSharp6))); } [WorkItem(43291, "https://github.com/dotnet/roslyn/issues/43291")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseConditionalExpression)] public async Task TestNotWithSimpleThrow() { await TestMissingAsync( @" class C { int M() { [||]if (true) { throw; } else { return 1; } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseConditionalExpression)] public async Task TestOnSimpleReturnNoBlocks() { await TestInRegularAndScript1Async( @" class C { int M() { [||]if (true) return 0; else return 1; } }", @" class C { int M() { return true ? 0 : 1; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseConditionalExpression)] public async Task TestOnSimpleReturnNoBlocks_NotInBlock() { await TestInRegularAndScript1Async( @" class C { int M() { if (true) [||]if (true) return 0; else return 1; } }", @" class C { int M() { if (true) return true ? 0 : 1; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseConditionalExpression)] public async Task TestMissingReturnValue1() { await TestMissingInRegularAndScriptAsync( @" class C { int M() { [||]if (true) { return 0; } else { return; } } }"); } [WorkItem(43291, "https://github.com/dotnet/roslyn/issues/43291")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseConditionalExpression)] public async Task TestMissingReturnValue1_Throw() { await TestMissingInRegularAndScriptAsync( @" class C { int M() { [||]if (true) { throw new System.Exception(); } else { return; } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseConditionalExpression)] public async Task TestMissingReturnValue2() { await TestMissingInRegularAndScriptAsync( @" class C { int M() { [||]if (true) { return; } else { return 1; } } }"); } [WorkItem(43291, "https://github.com/dotnet/roslyn/issues/43291")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseConditionalExpression)] public async Task TestMissingReturnValue2_Throw() { await TestMissingInRegularAndScriptAsync( @" class C { int M() { [||]if (true) { return; } else { throw new System.Exception(); } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseConditionalExpression)] public async Task TestMissingReturnValue3() { await TestMissingInRegularAndScriptAsync( @" class C { int M() { [||]if (true) { return; } else { return; } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseConditionalExpression)] public async Task TestWithNoElseBlockButFollowingReturn() { await TestInRegularAndScript1Async( @" class C { void M() { [||]if (true) { return 0; } return 1; } }", @" class C { void M() { return true ? 0 : 1; } }"); } [WorkItem(43291, "https://github.com/dotnet/roslyn/issues/43291")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseConditionalExpression)] public async Task TestWithNoElseBlockButFollowingReturn_Throw1() { await TestInRegularAndScript1Async( @" class C { void M() { [||]if (true) { throw new System.Exception(); } return 1; } }", @" class C { void M() { return true ? throw new System.Exception() : 1; } }"); } [WorkItem(43291, "https://github.com/dotnet/roslyn/issues/43291")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseConditionalExpression)] public async Task TestWithNoElseBlockButFollowingReturn_Throw2() { await TestInRegularAndScript1Async( @" class C { void M() { [||]if (true) { return 0; } throw new System.Exception(); } }", @" class C { void M() { return true ? 0 : throw new System.Exception(); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseConditionalExpression)] public async Task TestMissingWithoutElse() { await TestMissingInRegularAndScriptAsync( @" class C { int M() { [||]if (true) { return 0; } } }"); } [WorkItem(43291, "https://github.com/dotnet/roslyn/issues/43291")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseConditionalExpression)] public async Task TestMissingWithoutElse_Throw() { await TestMissingInRegularAndScriptAsync( @" class C { int M() { [||]if (true) { throw new System.Exception(); } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseConditionalExpression)] public async Task TestConversion1() { await TestInRegularAndScript1Async( @" class C { object M() { [||]if (true) { return ""a""; } else { return ""b""; } } }", @" class C { object M() { return true ? ""a"" : ""b""; } }"); } [WorkItem(43291, "https://github.com/dotnet/roslyn/issues/43291")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseConditionalExpression)] public async Task TestConversion1_Throw1() { await TestInRegularAndScript1Async( @" class C { object M() { [||]if (true) { throw new System.Exception(); } else { return ""b""; } } }", @" class C { object M() { return true ? throw new System.Exception() : ""b""; } }"); } [WorkItem(43291, "https://github.com/dotnet/roslyn/issues/43291")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseConditionalExpression)] public async Task TestConversion1_Throw2() { await TestInRegularAndScript1Async( @" class C { object M() { [||]if (true) { return ""a""; } else { throw new System.Exception(); } } }", @" class C { object M() { return true ? ""a"" : throw new System.Exception(); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseConditionalExpression)] public async Task TestConversion2() { await TestInRegularAndScript1Async( @" class C { string M() { [||]if (true) { return ""a""; } else { return null; } } }", @" class C { string M() { return true ? ""a"" : null; } }"); } [WorkItem(43291, "https://github.com/dotnet/roslyn/issues/43291")] [Theory, Trait(Traits.Feature, Traits.Features.CodeActionsUseConditionalExpression)] [InlineData(LanguageVersion.CSharp8, "(string)null")] [InlineData(LanguageVersion.CSharp9, "null")] public async Task TestConversion2_Throw1(LanguageVersion languageVersion, string expectedFalseExpression) { await TestInRegularAndScript1Async( @" class C { string M() { [||]if (true) { throw new System.Exception(); } else { return null; } } }", @" class C { string M() { return true ? throw new System.Exception() : " + expectedFalseExpression + @"; } }", parameters: new(parseOptions: CSharpParseOptions.Default.WithLanguageVersion(languageVersion))); } [WorkItem(43291, "https://github.com/dotnet/roslyn/issues/43291")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseConditionalExpression)] public async Task TestConversion2_Throw2() { await TestInRegularAndScript1Async( @" class C { string M() { [||]if (true) { return ""a""; } else { throw new System.Exception(); } } }", @" class C { string M() { return true ? ""a"" : throw new System.Exception(); } }"); } [Theory, Trait(Traits.Feature, Traits.Features.CodeActionsUseConditionalExpression)] [InlineData(LanguageVersion.CSharp8, "(string)null")] [InlineData(LanguageVersion.CSharp9, "null")] public async Task TestConversion3(LanguageVersion languageVersion, string expectedFalseExpression) { await TestInRegularAndScript1Async( @" class C { string M() { [||]if (true) { return null; } else { return null; } } }", @" class C { string M() { return true ? null : " + expectedFalseExpression + @"; } }", parameters: new(parseOptions: CSharpParseOptions.Default.WithLanguageVersion(languageVersion))); } [WorkItem(43291, "https://github.com/dotnet/roslyn/issues/43291")] [Theory, Trait(Traits.Feature, Traits.Features.CodeActionsUseConditionalExpression)] [InlineData(LanguageVersion.CSharp8, "(string)null")] [InlineData(LanguageVersion.CSharp9, "null")] public async Task TestConversion3_Throw1(LanguageVersion languageVersion, string expectedFalseExpression) { await TestInRegularAndScript1Async( @" class C { string M() { [||]if (true) { throw new System.Exception(); } else { return null; } } }", @" class C { string M() { return true ? throw new System.Exception() : " + expectedFalseExpression + @"; } }", parameters: new(parseOptions: CSharpParseOptions.Default.WithLanguageVersion(languageVersion))); } [WorkItem(43291, "https://github.com/dotnet/roslyn/issues/43291")] [Theory, Trait(Traits.Feature, Traits.Features.CodeActionsUseConditionalExpression)] [InlineData(LanguageVersion.CSharp8, "(string)null")] [InlineData(LanguageVersion.CSharp9, "null")] public async Task TestConversion3_Throw2(LanguageVersion languageVersion, string expectedTrue) { await TestInRegularAndScript1Async( @" class C { string M() { [||]if (true) { return null; } else { throw new System.Exception(); } } }", @" class C { string M() { return true ? " + expectedTrue + @" : throw new System.Exception(); } }", parameters: new(parseOptions: CSharpParseOptions.Default.WithLanguageVersion(languageVersion))); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseConditionalExpression)] public async Task TestKeepTriviaAroundIf() { await TestInRegularAndScript1Async( @" class C { int M() { // leading [||]if (true) { return 0; } else { return 1; } // trailing } }", @" class C { int M() { // leading return true ? 0 : 1; // trailing } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseConditionalExpression)] public async Task TestFixAll1() { await TestInRegularAndScript1Async( @" class C { int M() { {|FixAllInDocument:if|} (true) { return 0; } else { return 1; } if (true) { return 2; } return 3; } }", @" class C { int M() { return true ? 0 : 1; return true ? 2 : 3; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseConditionalExpression)] public async Task TestMultiLine1() { await TestInRegularAndScript1Async( @" class C { int M() { [||]if (true) { return Foo( 1, 2, 3); } else { return 1; } } }", @" class C { int M() { return true ? Foo( 1, 2, 3) : 1; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseConditionalExpression)] public async Task TestMultiLine2() { await TestInRegularAndScript1Async( @" class C { int M() { [||]if (true) { return 0; } else { return Foo( 1, 2, 3); } } }", @" class C { int M() { return true ? 0 : Foo( 1, 2, 3); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseConditionalExpression)] public async Task TestMultiLine3() { await TestInRegularAndScript1Async( @" class C { int M() { [||]if (true) { return Foo( 1, 2, 3); } else { return Foo( 4, 5, 6); } } }", @" class C { int M() { return true ? Foo( 1, 2, 3) : Foo( 4, 5, 6); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseConditionalExpression)] public async Task TestElseIfWithBlock() { await TestInRegularAndScript1Async( @" class C { int M() { if (true) { } else [||]if (false) { return 1; } else { return 0; } } }", @" class C { int M() { if (true) { } else { return false ? 1 : 0; } } }"); } [WorkItem(43291, "https://github.com/dotnet/roslyn/issues/43291")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseConditionalExpression)] public async Task TestElseIfWithBlock_Throw1() { await TestInRegularAndScript1Async( @" class C { int M() { if (true) { } else [||]if (false) { throw new System.Exception(); } else { return 0; } } }", @" class C { int M() { if (true) { } else { return false ? throw new System.Exception() : 0; } } }"); } [WorkItem(43291, "https://github.com/dotnet/roslyn/issues/43291")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseConditionalExpression)] public async Task TestElseIfWithBlock_Throw2() { await TestInRegularAndScript1Async( @" class C { int M() { if (true) { } else [||]if (false) { return 1; } else { throw new System.Exception(); } } }", @" class C { int M() { if (true) { } else { return false ? 1 : throw new System.Exception(); } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseConditionalExpression)] public async Task TestElseIfWithoutBlock() { await TestInRegularAndScript1Async( @" class C { int M() { if (true) return 2; else [||]if (false) return 1; else return 0; } }", @" class C { int M() { if (true) return 2; else return false ? 1 : 0; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseConditionalExpression)] public async Task TestRefReturns1() { await TestInRegularAndScript1Async( @" class C { ref int M(ref int i, ref int j) { [||]if (true) { return ref i; } else { return ref j; } } }", @" class C { ref int M(ref int i, ref int j) { return ref true ? ref i : ref j; } }"); } [WorkItem(43291, "https://github.com/dotnet/roslyn/issues/43291")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseConditionalExpression)] public async Task TestRefReturns1_Throw1() { await TestMissingAsync( @" class C { ref int M(ref int i, ref int j) { [||]if (true) { throw new System.Exception(); } else { return ref j; } } }"); } [WorkItem(43291, "https://github.com/dotnet/roslyn/issues/43291")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseConditionalExpression)] public async Task TestRefReturns1_Throw2() { await TestMissingAsync( @" class C { ref int M(ref int i, ref int j) { [||]if (true) { return ref i; } else { throw new System.Exception(); } } }"); } [WorkItem(27960, "https://github.com/dotnet/roslyn/issues/27960")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseConditionalExpression)] public async Task TestOnYieldReturn() { await TestInRegularAndScript1Async( @" class C { int M() { [||]if (true) { yield return 0; } else { yield return 1; } } }", @" class C { int M() { yield return true ? 0 : 1; } }"); } [WorkItem(43291, "https://github.com/dotnet/roslyn/issues/43291")] [WorkItem(27960, "https://github.com/dotnet/roslyn/issues/27960")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseConditionalExpression)] public async Task TestOnYieldReturn_Throw1() { await TestInRegularAndScript1Async( @" class C { int M() { [||]if (true) { throw new System.Exception(); } else { yield return 1; } } }", @" class C { int M() { yield return true ? throw new System.Exception() : 1; } }"); } [WorkItem(43291, "https://github.com/dotnet/roslyn/issues/43291")] [WorkItem(27960, "https://github.com/dotnet/roslyn/issues/27960")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseConditionalExpression)] public async Task TestOnYieldReturn_Throw2() { await TestInRegularAndScript1Async( @" class C { int M() { [||]if (true) { yield return 0; } else { throw new System.Exception(); } } }", @" class C { int M() { yield return true ? 0 : throw new System.Exception(); } }"); } [WorkItem(27960, "https://github.com/dotnet/roslyn/issues/27960")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseConditionalExpression)] public async Task TestOnYieldReturn_IEnumerableReturnType() { await TestInRegularAndScript1Async( @" using System.Collections.Generic; class C { IEnumerable<int> M() { [||]if (true) { yield return 0; } else { yield return 1; } } }", @" using System.Collections.Generic; class C { IEnumerable<int> M() { yield return true ? 0 : 1; } }"); } [WorkItem(27960, "https://github.com/dotnet/roslyn/issues/27960")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseConditionalExpression)] public async Task TestNotOnMixedYields() { await TestMissingAsync( @" class C { int M() { [||]if (true) { yield break; } else { yield return 1; } } }"); } [WorkItem(43291, "https://github.com/dotnet/roslyn/issues/43291")] [WorkItem(27960, "https://github.com/dotnet/roslyn/issues/27960")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseConditionalExpression)] public async Task TestNotOnMixedYields_Throw1() { await TestMissingAsync( @" class C { int M() { [||]if (true) { yield break; } else { throw new System.Exception(); } } }"); } [WorkItem(27960, "https://github.com/dotnet/roslyn/issues/27960")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseConditionalExpression)] public async Task TestNotOnMixedYields_IEnumerableReturnType() { await TestMissingAsync( @" using System.Collections.Generic; class C { IEnumerable<int> M() { [||]if (true) { yield break; } else { yield return 1; } } }"); } [WorkItem(27960, "https://github.com/dotnet/roslyn/issues/27960")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseConditionalExpression)] public async Task TestNotWithNoElseBlockButFollowingYieldReturn() { await TestMissingAsync( @" class C { void M() { [||]if (true) { yield return 0; } yield return 1; } }"); } [WorkItem(43291, "https://github.com/dotnet/roslyn/issues/43291")] [WorkItem(27960, "https://github.com/dotnet/roslyn/issues/27960")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseConditionalExpression)] public async Task TestWithNoElseBlockButFollowingYieldReturn_Throw1() { await TestInRegularAndScript1Async( @" class C { void M() { [||]if (true) { throw new System.Exception(); } yield return 1; } }", @" class C { void M() { yield return true ? throw new System.Exception() : 1; } }"); } [WorkItem(43291, "https://github.com/dotnet/roslyn/issues/43291")] [WorkItem(27960, "https://github.com/dotnet/roslyn/issues/27960")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseConditionalExpression)] public async Task TestNotWithNoElseBlockButFollowingYieldReturn_Throw2() { await TestMissingAsync( @" class C { void M() { [||]if (true) { yield return 0; } throw new System.Exception(); } }"); } [WorkItem(27960, "https://github.com/dotnet/roslyn/issues/27960")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseConditionalExpression)] public async Task TestNotWithNoElseBlockButFollowingYieldReturn_IEnumerableReturnType() { await TestMissingAsync( @" using System.Collections.Generic; class C { IEnumerable<int> M() { [||]if (true) { yield return 0; } yield return 1; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseConditionalExpression)] public async Task TestReturnTrueFalse1() { await TestInRegularAndScript1Async( @" class C { bool M(int a) { [||]if (a == 0) { return true; } else { return false; } } }", @" class C { bool M(int a) { return a == 0; } }"); } [WorkItem(43291, "https://github.com/dotnet/roslyn/issues/43291")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseConditionalExpression)] public async Task TestReturnTrueFalse1_Throw1() { await TestInRegularAndScript1Async( @" class C { bool M(int a) { [||]if (a == 0) { throw new System.Exception(); } else { return false; } } }", @" class C { bool M(int a) { return a == 0 ? throw new System.Exception() : false; } }"); } [WorkItem(43291, "https://github.com/dotnet/roslyn/issues/43291")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseConditionalExpression)] public async Task TestReturnTrueFalse1_Throw2() { await TestInRegularAndScript1Async( @" class C { bool M(int a) { [||]if (a == 0) { return true; } else { throw new System.Exception(); } } }", @" class C { bool M(int a) { return a == 0 ? true : throw new System.Exception(); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseConditionalExpression)] public async Task TestReturnTrueFalse2() { await TestInRegularAndScript1Async( @" class C { bool M(int a) { [||]if (a == 0) { return false; } else { return true; } } }", @" class C { bool M(int a) { return a != 0; } }"); } [WorkItem(43291, "https://github.com/dotnet/roslyn/issues/43291")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseConditionalExpression)] public async Task TestReturnTrueFalse2_Throw1() { await TestInRegularAndScript1Async( @" class C { bool M(int a) { [||]if (a == 0) { throw new System.Exception(); } else { return true; } } }", @" class C { bool M(int a) { return a == 0 ? throw new System.Exception() : true; } }"); } [WorkItem(43291, "https://github.com/dotnet/roslyn/issues/43291")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseConditionalExpression)] public async Task TestReturnTrueFalse2_Throw2() { await TestInRegularAndScript1Async( @" class C { bool M(int a) { [||]if (a == 0) { return false; } else { throw new System.Exception(); } } }", @" class C { bool M(int a) { return a == 0 ? false : throw new System.Exception(); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseConditionalExpression)] public async Task TestReturnTrueFalse3() { await TestInRegularAndScript1Async( @" class C { bool M(int a) { [||]if (a == 0) { return false; } return true; } }", @" class C { bool M(int a) { return a != 0; } }"); } [WorkItem(43291, "https://github.com/dotnet/roslyn/issues/43291")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseConditionalExpression)] public async Task TestReturnTrueFalse3_Throw1() { await TestInRegularAndScript1Async( @" class C { bool M(int a) { [||]if (a == 0) { throw new System.Exception(); } return true; } }", @" class C { bool M(int a) { return a == 0 ? throw new System.Exception() : true; } }"); } [WorkItem(43291, "https://github.com/dotnet/roslyn/issues/43291")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseConditionalExpression)] public async Task TestReturnTrueFalse3_Throw2() { await TestInRegularAndScript1Async( @" class C { bool M(int a) { [||]if (a == 0) { return false; } throw new System.Exception(); } }", @" class C { bool M(int a) { return a == 0 ? false : throw new System.Exception(); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseConditionalExpression)] public async Task TestReturnTrueFalse4() { await TestInRegularAndScript1Async( @" using System.Collections.Generic; class C { IEnumerable<bool> M(int a) { [||]if (a == 0) { yield return false; } else { yield return true; } } }", @" using System.Collections.Generic; class C { IEnumerable<bool> M(int a) { yield return a != 0; } }"); } [WorkItem(43291, "https://github.com/dotnet/roslyn/issues/43291")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseConditionalExpression)] public async Task TestReturnTrueFalse4_Throw1() { await TestInRegularAndScript1Async( @" using System.Collections.Generic; class C { IEnumerable<bool> M(int a) { [||]if (a == 0) { throw new System.Exception(); } else { yield return true; } } }", @" using System.Collections.Generic; class C { IEnumerable<bool> M(int a) { yield return a == 0 ? throw new System.Exception() : true; } }"); } [WorkItem(43291, "https://github.com/dotnet/roslyn/issues/43291")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseConditionalExpression)] public async Task TestReturnTrueFalse4_Throw2() { await TestInRegularAndScript1Async( @" using System.Collections.Generic; class C { IEnumerable<bool> M(int a) { [||]if (a == 0) { yield return false; } else { throw new System.Exception(); } } }", @" using System.Collections.Generic; class C { IEnumerable<bool> M(int a) { yield return a == 0 ? false : throw new System.Exception(); } }"); } [WorkItem(36117, "https://github.com/dotnet/roslyn/issues/36117")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseConditionalExpression)] public async Task TestMissingWhenCrossingPreprocessorDirective() { await TestMissingInRegularAndScriptAsync( @" class C { int M() { bool check = true; #if true [||]if (check) return 3; #endif return 2; } }"); } } }
-1
dotnet/roslyn
55,427
Fixes #50462
Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
Blokyk
2021-08-05T01:17:37Z
2021-08-25T05:42:59Z
fefb8c2110625bc4908db4bbdaa367b12bfb1069
fb4ac545a1f1f365e7df570637699d9085ea4f87
Fixes #50462. Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Extensions/SyntaxTreeExtensions.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Diagnostics.CodeAnalysis; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Shared.Extensions { internal static partial class SyntaxTreeExtensions { public static bool OverlapsHiddenPosition([NotNullWhen(returnValue: true)] this SyntaxTree? tree, TextSpan span, CancellationToken cancellationToken) { if (tree == null) { return false; } var text = tree.GetText(cancellationToken); return text.OverlapsHiddenPosition(span, (position, cancellationToken2) => { // implements the ASP.NET IsHidden rule var lineVisibility = tree.GetLineVisibility(position, cancellationToken2); return lineVisibility == LineVisibility.Hidden || lineVisibility == LineVisibility.BeforeFirstLineDirective; }, cancellationToken); } public static bool IsScript(this SyntaxTree syntaxTree) => syntaxTree.Options.Kind != SourceCodeKind.Regular; /// <summary> /// Returns the identifier, keyword, contextual keyword or preprocessor keyword touching this /// position, or a token of Kind = None if the caret is not touching either. /// </summary> public static Task<SyntaxToken> GetTouchingWordAsync( this SyntaxTree syntaxTree, int position, ISyntaxFacts syntaxFacts, CancellationToken cancellationToken, bool findInsideTrivia = false) { return GetTouchingTokenAsync(syntaxTree, position, syntaxFacts.IsWord, cancellationToken, findInsideTrivia); } public static Task<SyntaxToken> GetTouchingTokenAsync( this SyntaxTree syntaxTree, int position, CancellationToken cancellationToken, bool findInsideTrivia = false) { return GetTouchingTokenAsync(syntaxTree, position, _ => true, cancellationToken, findInsideTrivia); } public static async Task<SyntaxToken> GetTouchingTokenAsync( this SyntaxTree syntaxTree, int position, Predicate<SyntaxToken> predicate, CancellationToken cancellationToken, bool findInsideTrivia = false) { Contract.ThrowIfNull(syntaxTree); if (position >= syntaxTree.Length) { return default; } var root = await syntaxTree.GetRootAsync(cancellationToken).ConfigureAwait(false); var token = root.FindToken(position, findInsideTrivia); if ((token.Span.Contains(position) || token.Span.End == position) && predicate(token)) { return token; } token = token.GetPreviousToken(); if (token.Span.End == position && predicate(token)) { return token; } // SyntaxKind = None return default; } public static bool IsEntirelyHidden(this SyntaxTree tree, TextSpan span, CancellationToken cancellationToken) { if (!tree.HasHiddenRegions()) { return false; } var text = tree.GetText(cancellationToken); var startLineNumber = text.Lines.IndexOf(span.Start); var endLineNumber = text.Lines.IndexOf(span.End); for (var lineNumber = startLineNumber; lineNumber <= endLineNumber; lineNumber++) { cancellationToken.ThrowIfCancellationRequested(); var linePosition = text.Lines[lineNumber].Start; if (!tree.IsHiddenPosition(linePosition, cancellationToken)) { return false; } } return true; } public static bool IsBeforeFirstToken(this SyntaxTree syntaxTree, int position, CancellationToken cancellationToken) { var root = syntaxTree.GetRoot(cancellationToken); var firstToken = root.GetFirstToken(includeZeroWidth: true, includeSkipped: true); return position <= firstToken.SpanStart; } public static SyntaxToken FindTokenOrEndToken( this SyntaxTree syntaxTree, int position, CancellationToken cancellationToken) { Contract.ThrowIfNull(syntaxTree); var root = syntaxTree.GetRoot(cancellationToken); var result = root.FindToken(position, findInsideTrivia: true); if (result.RawKind != 0) { return result; } // Special cases. See if we're actually at the end of a: // a) doc comment // b) pp directive // c) file var compilationUnit = (ICompilationUnitSyntax)root; var triviaList = compilationUnit.EndOfFileToken.LeadingTrivia; foreach (var trivia in triviaList.Reverse()) { if (trivia.HasStructure) { var token = trivia.GetStructure()!.GetLastToken(includeZeroWidth: true); if (token.Span.End == position) { return token; } } } if (position == root.FullSpan.End) { return compilationUnit.EndOfFileToken; } return default; } internal static SyntaxTrivia FindTriviaAndAdjustForEndOfFile( this SyntaxTree syntaxTree, int position, CancellationToken cancellationToken, bool findInsideTrivia = false) { var root = syntaxTree.GetRoot(cancellationToken); var trivia = root.FindTrivia(position, findInsideTrivia); // If we ask right at the end of the file, we'll get back nothing. // We handle that case specially for now, though SyntaxTree.FindTrivia should // work at the end of a file. if (position == root.FullWidth()) { var compilationUnit = (ICompilationUnitSyntax)root; var endOfFileToken = compilationUnit.EndOfFileToken; if (endOfFileToken.HasLeadingTrivia) { trivia = endOfFileToken.LeadingTrivia.Last(); } else { var token = endOfFileToken.GetPreviousToken(includeSkipped: true); if (token.HasTrailingTrivia) { trivia = token.TrailingTrivia.Last(); } } } return trivia; } /// <summary> /// If the position is inside of token, return that token; otherwise, return the token to the right. /// </summary> public static SyntaxToken FindTokenOnRightOfPosition( this SyntaxTree syntaxTree, int position, CancellationToken cancellationToken, bool includeSkipped = true, bool includeDirectives = false, bool includeDocumentationComments = false) { return syntaxTree.GetRoot(cancellationToken).FindTokenOnRightOfPosition( position, includeSkipped, includeDirectives, includeDocumentationComments); } /// <summary> /// If the position is inside of token, return that token; otherwise, return the token to the left. /// </summary> public static SyntaxToken FindTokenOnLeftOfPosition( this SyntaxTree syntaxTree, int position, CancellationToken cancellationToken, bool includeSkipped = true, bool includeDirectives = false, bool includeDocumentationComments = false) { return syntaxTree.GetRoot(cancellationToken).FindTokenOnLeftOfPosition( position, includeSkipped, includeDirectives, includeDocumentationComments); } public static bool IsGeneratedCode(this SyntaxTree syntaxTree, AnalyzerOptions? analyzerOptions, ISyntaxFacts syntaxFacts, CancellationToken cancellationToken) { // First check if user has configured "generated_code = true | false" in .editorconfig if (analyzerOptions != null) { var analyzerConfigOptions = analyzerOptions.AnalyzerConfigOptionsProvider.GetOptions(syntaxTree); var isUserConfiguredGeneratedCode = GeneratedCodeUtilities.GetIsGeneratedCodeFromOptions(analyzerConfigOptions); if (isUserConfiguredGeneratedCode.HasValue) { return isUserConfiguredGeneratedCode.Value; } } // Otherwise, fallback to generated code heuristic. return GeneratedCodeUtilities.IsGeneratedCode( syntaxTree, t => syntaxFacts.IsRegularComment(t) || syntaxFacts.IsDocumentationComment(t), 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.Diagnostics.CodeAnalysis; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Shared.Extensions { internal static partial class SyntaxTreeExtensions { public static bool OverlapsHiddenPosition([NotNullWhen(returnValue: true)] this SyntaxTree? tree, TextSpan span, CancellationToken cancellationToken) { if (tree == null) { return false; } var text = tree.GetText(cancellationToken); return text.OverlapsHiddenPosition(span, (position, cancellationToken2) => { // implements the ASP.NET IsHidden rule var lineVisibility = tree.GetLineVisibility(position, cancellationToken2); return lineVisibility == LineVisibility.Hidden || lineVisibility == LineVisibility.BeforeFirstLineDirective; }, cancellationToken); } public static bool IsScript(this SyntaxTree syntaxTree) => syntaxTree.Options.Kind != SourceCodeKind.Regular; /// <summary> /// Returns the identifier, keyword, contextual keyword or preprocessor keyword touching this /// position, or a token of Kind = None if the caret is not touching either. /// </summary> public static Task<SyntaxToken> GetTouchingWordAsync( this SyntaxTree syntaxTree, int position, ISyntaxFacts syntaxFacts, CancellationToken cancellationToken, bool findInsideTrivia = false) { return GetTouchingTokenAsync(syntaxTree, position, syntaxFacts.IsWord, cancellationToken, findInsideTrivia); } public static Task<SyntaxToken> GetTouchingTokenAsync( this SyntaxTree syntaxTree, int position, CancellationToken cancellationToken, bool findInsideTrivia = false) { return GetTouchingTokenAsync(syntaxTree, position, _ => true, cancellationToken, findInsideTrivia); } public static async Task<SyntaxToken> GetTouchingTokenAsync( this SyntaxTree syntaxTree, int position, Predicate<SyntaxToken> predicate, CancellationToken cancellationToken, bool findInsideTrivia = false) { Contract.ThrowIfNull(syntaxTree); if (position >= syntaxTree.Length) { return default; } var root = await syntaxTree.GetRootAsync(cancellationToken).ConfigureAwait(false); var token = root.FindToken(position, findInsideTrivia); if ((token.Span.Contains(position) || token.Span.End == position) && predicate(token)) { return token; } token = token.GetPreviousToken(); if (token.Span.End == position && predicate(token)) { return token; } // SyntaxKind = None return default; } public static bool IsEntirelyHidden(this SyntaxTree tree, TextSpan span, CancellationToken cancellationToken) { if (!tree.HasHiddenRegions()) { return false; } var text = tree.GetText(cancellationToken); var startLineNumber = text.Lines.IndexOf(span.Start); var endLineNumber = text.Lines.IndexOf(span.End); for (var lineNumber = startLineNumber; lineNumber <= endLineNumber; lineNumber++) { cancellationToken.ThrowIfCancellationRequested(); var linePosition = text.Lines[lineNumber].Start; if (!tree.IsHiddenPosition(linePosition, cancellationToken)) { return false; } } return true; } public static bool IsBeforeFirstToken(this SyntaxTree syntaxTree, int position, CancellationToken cancellationToken) { var root = syntaxTree.GetRoot(cancellationToken); var firstToken = root.GetFirstToken(includeZeroWidth: true, includeSkipped: true); return position <= firstToken.SpanStart; } public static SyntaxToken FindTokenOrEndToken( this SyntaxTree syntaxTree, int position, CancellationToken cancellationToken) { Contract.ThrowIfNull(syntaxTree); var root = syntaxTree.GetRoot(cancellationToken); var result = root.FindToken(position, findInsideTrivia: true); if (result.RawKind != 0) { return result; } // Special cases. See if we're actually at the end of a: // a) doc comment // b) pp directive // c) file var compilationUnit = (ICompilationUnitSyntax)root; var triviaList = compilationUnit.EndOfFileToken.LeadingTrivia; foreach (var trivia in triviaList.Reverse()) { if (trivia.HasStructure) { var token = trivia.GetStructure()!.GetLastToken(includeZeroWidth: true); if (token.Span.End == position) { return token; } } } if (position == root.FullSpan.End) { return compilationUnit.EndOfFileToken; } return default; } internal static SyntaxTrivia FindTriviaAndAdjustForEndOfFile( this SyntaxTree syntaxTree, int position, CancellationToken cancellationToken, bool findInsideTrivia = false) { var root = syntaxTree.GetRoot(cancellationToken); var trivia = root.FindTrivia(position, findInsideTrivia); // If we ask right at the end of the file, we'll get back nothing. // We handle that case specially for now, though SyntaxTree.FindTrivia should // work at the end of a file. if (position == root.FullWidth()) { var compilationUnit = (ICompilationUnitSyntax)root; var endOfFileToken = compilationUnit.EndOfFileToken; if (endOfFileToken.HasLeadingTrivia) { trivia = endOfFileToken.LeadingTrivia.Last(); } else { var token = endOfFileToken.GetPreviousToken(includeSkipped: true); if (token.HasTrailingTrivia) { trivia = token.TrailingTrivia.Last(); } } } return trivia; } /// <summary> /// If the position is inside of token, return that token; otherwise, return the token to the right. /// </summary> public static SyntaxToken FindTokenOnRightOfPosition( this SyntaxTree syntaxTree, int position, CancellationToken cancellationToken, bool includeSkipped = true, bool includeDirectives = false, bool includeDocumentationComments = false) { return syntaxTree.GetRoot(cancellationToken).FindTokenOnRightOfPosition( position, includeSkipped, includeDirectives, includeDocumentationComments); } /// <summary> /// If the position is inside of token, return that token; otherwise, return the token to the left. /// </summary> public static SyntaxToken FindTokenOnLeftOfPosition( this SyntaxTree syntaxTree, int position, CancellationToken cancellationToken, bool includeSkipped = true, bool includeDirectives = false, bool includeDocumentationComments = false) { return syntaxTree.GetRoot(cancellationToken).FindTokenOnLeftOfPosition( position, includeSkipped, includeDirectives, includeDocumentationComments); } public static bool IsGeneratedCode(this SyntaxTree syntaxTree, AnalyzerOptions? analyzerOptions, ISyntaxFacts syntaxFacts, CancellationToken cancellationToken) { // First check if user has configured "generated_code = true | false" in .editorconfig if (analyzerOptions != null) { var analyzerConfigOptions = analyzerOptions.AnalyzerConfigOptionsProvider.GetOptions(syntaxTree); var isUserConfiguredGeneratedCode = GeneratedCodeUtilities.GetIsGeneratedCodeFromOptions(analyzerConfigOptions); if (isUserConfiguredGeneratedCode.HasValue) { return isUserConfiguredGeneratedCode.Value; } } // Otherwise, fallback to generated code heuristic. return GeneratedCodeUtilities.IsGeneratedCode( syntaxTree, t => syntaxFacts.IsRegularComment(t) || syntaxFacts.IsDocumentationComment(t), cancellationToken); } } }
-1
dotnet/roslyn
55,427
Fixes #50462
Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
Blokyk
2021-08-05T01:17:37Z
2021-08-25T05:42:59Z
fefb8c2110625bc4908db4bbdaa367b12bfb1069
fb4ac545a1f1f365e7df570637699d9085ea4f87
Fixes #50462. Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
./src/Features/Core/Portable/SyncNamespaces/ISyncNamespacesService.cs
// Licensed to the .NET Foundation under one or more agreements. // 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; namespace Microsoft.CodeAnalysis.SyncNamespaces { internal interface ISyncNamespacesService : ILanguageService { /// <summary> /// This will update documents in the specified projects so that their namespace matches the RootNamespace /// and their relative folder path. /// </summary> Task<Solution> SyncNamespacesAsync(ImmutableArray<Project> projects, 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.Collections.Immutable; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Host; namespace Microsoft.CodeAnalysis.SyncNamespaces { internal interface ISyncNamespacesService : ILanguageService { /// <summary> /// This will update documents in the specified projects so that their namespace matches the RootNamespace /// and their relative folder path. /// </summary> Task<Solution> SyncNamespacesAsync(ImmutableArray<Project> projects, CancellationToken cancellationToken); } }
-1
dotnet/roslyn
55,427
Fixes #50462
Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
Blokyk
2021-08-05T01:17:37Z
2021-08-25T05:42:59Z
fefb8c2110625bc4908db4bbdaa367b12bfb1069
fb4ac545a1f1f365e7df570637699d9085ea4f87
Fixes #50462. Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
./src/EditorFeatures/DiagnosticsTestUtilities/CodeActions/AbstractCodeActionTest.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.Composition; using System.Diagnostics; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.CodeRefactorings; using Microsoft.CodeAnalysis.Editor.Implementation.Preview; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.PickMembers; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Utilities; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions { public abstract partial class AbstractCodeActionTest : AbstractCodeActionOrUserDiagnosticTest { protected abstract CodeRefactoringProvider CreateCodeRefactoringProvider( Workspace workspace, TestParameters parameters); protected override async Task<(ImmutableArray<CodeAction>, CodeAction actionToInvoke)> GetCodeActionsAsync( TestWorkspace workspace, TestParameters parameters) { var refactoring = await GetCodeRefactoringAsync(workspace, parameters); var actions = refactoring == null ? ImmutableArray<CodeAction>.Empty : refactoring.CodeActions.Select(n => n.action).AsImmutable(); actions = MassageActions(actions); return (actions, actions.IsDefaultOrEmpty ? null : actions[parameters.index]); } protected override Task<ImmutableArray<Diagnostic>> GetDiagnosticsWorkerAsync(TestWorkspace workspace, TestParameters parameters) => SpecializedTasks.EmptyImmutableArray<Diagnostic>(); internal async Task<CodeRefactoring> GetCodeRefactoringAsync( TestWorkspace workspace, TestParameters parameters) { return (await GetCodeRefactoringsAsync(workspace, parameters)).FirstOrDefault(); } private async Task<IEnumerable<CodeRefactoring>> GetCodeRefactoringsAsync( TestWorkspace workspace, TestParameters parameters) { var provider = CreateCodeRefactoringProvider(workspace, parameters); return SpecializedCollections.SingletonEnumerable( await GetCodeRefactoringAsync(provider, workspace)); } private static async Task<CodeRefactoring> GetCodeRefactoringAsync( CodeRefactoringProvider provider, TestWorkspace workspace) { var documentsWithSelections = workspace.Documents.Where(d => !d.IsLinkFile && d.SelectedSpans.Count == 1); Debug.Assert(documentsWithSelections.Count() == 1, "One document must have a single span annotation"); var span = documentsWithSelections.Single().SelectedSpans.Single(); var actions = ArrayBuilder<(CodeAction, TextSpan?)>.GetInstance(); var document = workspace.CurrentSolution.GetDocument(documentsWithSelections.Single().Id); var context = new CodeRefactoringContext(document, span, (a, t) => actions.Add((a, t)), isBlocking: false, CancellationToken.None); await provider.ComputeRefactoringsAsync(context); var result = actions.Count > 0 ? new CodeRefactoring(provider, actions.ToImmutable()) : null; actions.Free(); return result; } protected async Task TestActionOnLinkedFiles( TestWorkspace workspace, string expectedText, CodeAction action, string expectedPreviewContents = null) { var operations = await VerifyActionAndGetOperationsAsync(workspace, action, default); await VerifyPreviewContents(workspace, expectedPreviewContents, operations); var applyChangesOperation = operations.OfType<ApplyChangesOperation>().First(); applyChangesOperation.TryApply(workspace, new ProgressTracker(), CancellationToken.None); foreach (var document in workspace.Documents) { var fixedRoot = await workspace.CurrentSolution.GetDocument(document.Id).GetSyntaxRootAsync(); var actualText = fixedRoot.ToFullString(); Assert.Equal(expectedText, actualText); } } private static async Task VerifyPreviewContents( TestWorkspace workspace, string expectedPreviewContents, ImmutableArray<CodeActionOperation> operations) { if (expectedPreviewContents != null) { var editHandler = workspace.ExportProvider.GetExportedValue<ICodeActionEditHandlerService>(); var content = (await editHandler.GetPreviews(workspace, operations, CancellationToken.None).GetPreviewsAsync())[0]; var diffView = content as DifferenceViewerPreview; Assert.NotNull(diffView.Viewer); var previewContents = diffView.Viewer.RightView.TextBuffer.AsTextContainer().CurrentText.ToString(); diffView.Dispose(); Assert.Equal(expectedPreviewContents, previewContents); } } protected static Document GetDocument(TestWorkspace workspace) => workspace.CurrentSolution.GetDocument(workspace.Documents.First().Id); internal static void EnableOptions( ImmutableArray<PickMembersOption> options, params string[] ids) { foreach (var id in ids) { EnableOption(options, id); } } internal static void EnableOption(ImmutableArray<PickMembersOption> options, string id) { var option = options.FirstOrDefault(o => o.Id == id); if (option != null) { option.Value = true; } } internal Task TestWithPickMembersDialogAsync( string initialMarkup, string expectedMarkup, string[] chosenSymbols, Action<ImmutableArray<PickMembersOption>> optionsCallback = null, int index = 0, TestParameters parameters = default) { var pickMembersService = new TestPickMembersService(chosenSymbols.AsImmutableOrNull(), optionsCallback); return TestInRegularAndScript1Async( initialMarkup, expectedMarkup, index, parameters.WithFixProviderData(pickMembersService)); } } [ExportWorkspaceService(typeof(IPickMembersService), ServiceLayer.Host), Shared, PartNotDiscoverable] internal class TestPickMembersService : IPickMembersService { public ImmutableArray<string> MemberNames; public Action<ImmutableArray<PickMembersOption>> OptionsCallback; [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public TestPickMembersService() { } #pragma warning disable RS0034 // Exported parts should be marked with 'ImportingConstructorAttribute' public TestPickMembersService( ImmutableArray<string> memberNames, Action<ImmutableArray<PickMembersOption>> optionsCallback) { MemberNames = memberNames; OptionsCallback = optionsCallback; } #pragma warning restore RS0034 // Exported parts should be marked with 'ImportingConstructorAttribute' public PickMembersResult PickMembers( string title, ImmutableArray<ISymbol> members, ImmutableArray<PickMembersOption> options, bool selectAll) { OptionsCallback?.Invoke(options); return new PickMembersResult( MemberNames.IsDefault ? members : MemberNames.SelectAsArray(n => members.Single(m => m.Name == n)), options, selectAll); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.Composition; using System.Diagnostics; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.CodeRefactorings; using Microsoft.CodeAnalysis.Editor.Implementation.Preview; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.PickMembers; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Utilities; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions { public abstract partial class AbstractCodeActionTest : AbstractCodeActionOrUserDiagnosticTest { protected abstract CodeRefactoringProvider CreateCodeRefactoringProvider( Workspace workspace, TestParameters parameters); protected override async Task<(ImmutableArray<CodeAction>, CodeAction actionToInvoke)> GetCodeActionsAsync( TestWorkspace workspace, TestParameters parameters) { var refactoring = await GetCodeRefactoringAsync(workspace, parameters); var actions = refactoring == null ? ImmutableArray<CodeAction>.Empty : refactoring.CodeActions.Select(n => n.action).AsImmutable(); actions = MassageActions(actions); return (actions, actions.IsDefaultOrEmpty ? null : actions[parameters.index]); } protected override Task<ImmutableArray<Diagnostic>> GetDiagnosticsWorkerAsync(TestWorkspace workspace, TestParameters parameters) => SpecializedTasks.EmptyImmutableArray<Diagnostic>(); internal async Task<CodeRefactoring> GetCodeRefactoringAsync( TestWorkspace workspace, TestParameters parameters) { return (await GetCodeRefactoringsAsync(workspace, parameters)).FirstOrDefault(); } private async Task<IEnumerable<CodeRefactoring>> GetCodeRefactoringsAsync( TestWorkspace workspace, TestParameters parameters) { var provider = CreateCodeRefactoringProvider(workspace, parameters); return SpecializedCollections.SingletonEnumerable( await GetCodeRefactoringAsync(provider, workspace)); } private static async Task<CodeRefactoring> GetCodeRefactoringAsync( CodeRefactoringProvider provider, TestWorkspace workspace) { var documentsWithSelections = workspace.Documents.Where(d => !d.IsLinkFile && d.SelectedSpans.Count == 1); Debug.Assert(documentsWithSelections.Count() == 1, "One document must have a single span annotation"); var span = documentsWithSelections.Single().SelectedSpans.Single(); var actions = ArrayBuilder<(CodeAction, TextSpan?)>.GetInstance(); var document = workspace.CurrentSolution.GetDocument(documentsWithSelections.Single().Id); var context = new CodeRefactoringContext(document, span, (a, t) => actions.Add((a, t)), isBlocking: false, CancellationToken.None); await provider.ComputeRefactoringsAsync(context); var result = actions.Count > 0 ? new CodeRefactoring(provider, actions.ToImmutable()) : null; actions.Free(); return result; } protected async Task TestActionOnLinkedFiles( TestWorkspace workspace, string expectedText, CodeAction action, string expectedPreviewContents = null) { var operations = await VerifyActionAndGetOperationsAsync(workspace, action, default); await VerifyPreviewContents(workspace, expectedPreviewContents, operations); var applyChangesOperation = operations.OfType<ApplyChangesOperation>().First(); applyChangesOperation.TryApply(workspace, new ProgressTracker(), CancellationToken.None); foreach (var document in workspace.Documents) { var fixedRoot = await workspace.CurrentSolution.GetDocument(document.Id).GetSyntaxRootAsync(); var actualText = fixedRoot.ToFullString(); Assert.Equal(expectedText, actualText); } } private static async Task VerifyPreviewContents( TestWorkspace workspace, string expectedPreviewContents, ImmutableArray<CodeActionOperation> operations) { if (expectedPreviewContents != null) { var editHandler = workspace.ExportProvider.GetExportedValue<ICodeActionEditHandlerService>(); var content = (await editHandler.GetPreviews(workspace, operations, CancellationToken.None).GetPreviewsAsync())[0]; var diffView = content as DifferenceViewerPreview; Assert.NotNull(diffView.Viewer); var previewContents = diffView.Viewer.RightView.TextBuffer.AsTextContainer().CurrentText.ToString(); diffView.Dispose(); Assert.Equal(expectedPreviewContents, previewContents); } } protected static Document GetDocument(TestWorkspace workspace) => workspace.CurrentSolution.GetDocument(workspace.Documents.First().Id); internal static void EnableOptions( ImmutableArray<PickMembersOption> options, params string[] ids) { foreach (var id in ids) { EnableOption(options, id); } } internal static void EnableOption(ImmutableArray<PickMembersOption> options, string id) { var option = options.FirstOrDefault(o => o.Id == id); if (option != null) { option.Value = true; } } internal Task TestWithPickMembersDialogAsync( string initialMarkup, string expectedMarkup, string[] chosenSymbols, Action<ImmutableArray<PickMembersOption>> optionsCallback = null, int index = 0, TestParameters parameters = default) { var pickMembersService = new TestPickMembersService(chosenSymbols.AsImmutableOrNull(), optionsCallback); return TestInRegularAndScript1Async( initialMarkup, expectedMarkup, index, parameters.WithFixProviderData(pickMembersService)); } } [ExportWorkspaceService(typeof(IPickMembersService), ServiceLayer.Host), Shared, PartNotDiscoverable] internal class TestPickMembersService : IPickMembersService { public ImmutableArray<string> MemberNames; public Action<ImmutableArray<PickMembersOption>> OptionsCallback; [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public TestPickMembersService() { } #pragma warning disable RS0034 // Exported parts should be marked with 'ImportingConstructorAttribute' public TestPickMembersService( ImmutableArray<string> memberNames, Action<ImmutableArray<PickMembersOption>> optionsCallback) { MemberNames = memberNames; OptionsCallback = optionsCallback; } #pragma warning restore RS0034 // Exported parts should be marked with 'ImportingConstructorAttribute' public PickMembersResult PickMembers( string title, ImmutableArray<ISymbol> members, ImmutableArray<PickMembersOption> options, bool selectAll) { OptionsCallback?.Invoke(options); return new PickMembersResult( MemberNames.IsDefault ? members : MemberNames.SelectAsArray(n => members.Single(m => m.Name == n)), options, selectAll); } } }
-1
dotnet/roslyn
55,427
Fixes #50462
Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
Blokyk
2021-08-05T01:17:37Z
2021-08-25T05:42:59Z
fefb8c2110625bc4908db4bbdaa367b12bfb1069
fb4ac545a1f1f365e7df570637699d9085ea4f87
Fixes #50462. Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
./src/Features/CSharp/Portable/EncapsulateField/CSharpEncapsulateFieldService.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.Composition; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeGeneration; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.EncapsulateField; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Shared.Utilities; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.EncapsulateField { [ExportLanguageService(typeof(AbstractEncapsulateFieldService), LanguageNames.CSharp), Shared] internal class CSharpEncapsulateFieldService : AbstractEncapsulateFieldService { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public CSharpEncapsulateFieldService() { } protected override async Task<SyntaxNode> RewriteFieldNameAndAccessibilityAsync(string originalFieldName, bool makePrivate, Document document, SyntaxAnnotation declarationAnnotation, CancellationToken cancellationToken) { var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); var declarator = root.GetAnnotatedNodes<VariableDeclaratorSyntax>(declarationAnnotation).FirstOrDefault(); // There may be no field to rewrite if this document is part of a set of linked files // and the declaration is not conditionally compiled in this document's project. if (declarator == null) { return root; } var tempAnnotation = new SyntaxAnnotation(); var escapedName = originalFieldName.EscapeIdentifier(); var newIdentifier = SyntaxFactory.Identifier( leading: SyntaxTriviaList.Create(SyntaxFactory.ElasticMarker), contextualKind: SyntaxKind.IdentifierName, text: escapedName, valueText: originalFieldName, trailing: SyntaxTriviaList.Create(SyntaxFactory.ElasticMarker)) .WithTrailingTrivia(declarator.Identifier.TrailingTrivia) .WithLeadingTrivia(declarator.Identifier.LeadingTrivia); var updatedDeclarator = declarator.WithIdentifier(newIdentifier).WithAdditionalAnnotations(tempAnnotation); root = root.ReplaceNode(declarator, updatedDeclarator); document = document.WithSyntaxRoot(root); var declaration = root.GetAnnotatedNodes<SyntaxNode>(tempAnnotation).First().Parent as VariableDeclarationSyntax; if (declaration.Variables.Count == 1) { var fieldSyntax = declaration.Parent as FieldDeclarationSyntax; var modifierKinds = new[] { SyntaxKind.PrivateKeyword, SyntaxKind.ProtectedKeyword, SyntaxKind.InternalKeyword, SyntaxKind.PublicKeyword }; if (makePrivate) { var modifiers = SpecializedCollections.SingletonEnumerable(SyntaxFactory.Token(SyntaxKind.PrivateKeyword)) .Concat(fieldSyntax.Modifiers.Where(m => !modifierKinds.Contains(m.Kind()))); root = root.ReplaceNode(fieldSyntax, fieldSyntax.WithModifiers( SyntaxFactory.TokenList(modifiers)) .WithAdditionalAnnotations(Formatter.Annotation) .WithLeadingTrivia(fieldSyntax.GetLeadingTrivia()) .WithTrailingTrivia(fieldSyntax.GetTrailingTrivia())); } } else if (declaration.Variables.Count > 1 && makePrivate) { document = document.WithSyntaxRoot(root); var codeGenService = document.GetLanguageService<ICodeGenerationService>(); var semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false); root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); declarator = root.GetAnnotatedNodes<VariableDeclaratorSyntax>(tempAnnotation).First(); declaration = declarator.Parent as VariableDeclarationSyntax; var field = semanticModel.GetDeclaredSymbol(declarator, cancellationToken) as IFieldSymbol; var fieldToAdd = declarationAnnotation.AddAnnotationToSymbol(CodeGenerationSymbolFactory.CreateFieldSymbol( field.GetAttributes(), Accessibility.Private, new DeclarationModifiers(isStatic: field.IsStatic, isReadOnly: field.IsReadOnly, isConst: field.IsConst), field.Type, field.Name, field.HasConstantValue, field.ConstantValue, declarator.Initializer)); var withField = await codeGenService.AddFieldAsync(document.Project.Solution, field.ContainingType, fieldToAdd, new CodeGenerationOptions(), cancellationToken).ConfigureAwait(false); root = await withField.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); declarator = root.GetAnnotatedNodes<VariableDeclaratorSyntax>(tempAnnotation).First(); declaration = declarator.Parent as VariableDeclarationSyntax; return root.RemoveNode(declarator, SyntaxRemoveOptions.KeepNoTrivia); } return root; } protected override async Task<ImmutableArray<IFieldSymbol>> GetFieldsAsync(Document document, TextSpan span, CancellationToken cancellationToken) { var semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false); var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); var fields = root.DescendantNodes(d => d.Span.IntersectsWith(span)) .OfType<FieldDeclarationSyntax>() .Where(n => n.Span.IntersectsWith(span)); var declarations = fields.Where(CanEncapsulate).Select(f => f.Declaration); IEnumerable<VariableDeclaratorSyntax> declarators; if (span.IsEmpty) { // no selection, get all variables declarators = declarations.SelectMany(d => d.Variables); } else { // has selection, get only the ones that are included in the selection declarators = declarations.SelectMany(d => d.Variables.Where(v => v.Span.IntersectsWith(span))); } return declarators.Select(d => semanticModel.GetDeclaredSymbol(d, cancellationToken) as IFieldSymbol) .WhereNotNull() .Where(f => f.Name.Length != 0) .ToImmutableArray(); } private bool CanEncapsulate(FieldDeclarationSyntax field) => field.Parent is TypeDeclarationSyntax; protected override (string fieldName, string propertyName) GenerateFieldAndPropertyNames(IFieldSymbol field) { // Special case: if the field is "new", we will preserve its original name and the new keyword. if (field.DeclaredAccessibility == Accessibility.Private || IsNew(field)) { // Create some capitalized version of the field name for the property return (field.Name, MakeUnique(GeneratePropertyName(field.Name), field.ContainingType)); } else { // Generate the new property name using the rules from 695042 var newPropertyName = GeneratePropertyName(field.Name); if (newPropertyName == field.Name) { // If we wind up with the field's old name, give the field the unique version of its current name. return (MakeUnique(GenerateFieldName(field.Name), field.ContainingType), newPropertyName); } // Otherwise, ensure the property's name is unique. newPropertyName = MakeUnique(newPropertyName, field.ContainingType); var newFieldName = GenerateFieldName(newPropertyName); // If converting the new property's name into a field name results in the old field name, we're done. if (newFieldName == field.Name) { return (newFieldName, newPropertyName); } // Otherwise, ensure the new field name is unique. return (MakeUnique(newFieldName, field.ContainingType), newPropertyName); } } private static bool IsNew(IFieldSymbol field) => field.DeclaringSyntaxReferences.Any(d => d.GetSyntax().GetAncestor<FieldDeclarationSyntax>().Modifiers.Any(SyntaxKind.NewKeyword)); private static string GenerateFieldName(string correspondingPropertyName) => char.ToLower(correspondingPropertyName[0]).ToString() + correspondingPropertyName.Substring(1); protected static string MakeUnique(string baseName, INamedTypeSymbol containingType) { var containingTypeMemberNames = containingType.GetAccessibleMembersInThisAndBaseTypes<ISymbol>(containingType).Select(m => m.Name); return NameGenerator.GenerateUniqueName(baseName, containingTypeMemberNames.ToSet(), StringComparer.Ordinal); } internal override IEnumerable<SyntaxNode> GetConstructorNodes(INamedTypeSymbol containingType) => containingType.Constructors.SelectMany(c => c.DeclaringSyntaxReferences.Select(d => d.GetSyntax())); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.Composition; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeGeneration; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.EncapsulateField; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Shared.Utilities; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.EncapsulateField { [ExportLanguageService(typeof(AbstractEncapsulateFieldService), LanguageNames.CSharp), Shared] internal class CSharpEncapsulateFieldService : AbstractEncapsulateFieldService { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public CSharpEncapsulateFieldService() { } protected override async Task<SyntaxNode> RewriteFieldNameAndAccessibilityAsync(string originalFieldName, bool makePrivate, Document document, SyntaxAnnotation declarationAnnotation, CancellationToken cancellationToken) { var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); var declarator = root.GetAnnotatedNodes<VariableDeclaratorSyntax>(declarationAnnotation).FirstOrDefault(); // There may be no field to rewrite if this document is part of a set of linked files // and the declaration is not conditionally compiled in this document's project. if (declarator == null) { return root; } var tempAnnotation = new SyntaxAnnotation(); var escapedName = originalFieldName.EscapeIdentifier(); var newIdentifier = SyntaxFactory.Identifier( leading: SyntaxTriviaList.Create(SyntaxFactory.ElasticMarker), contextualKind: SyntaxKind.IdentifierName, text: escapedName, valueText: originalFieldName, trailing: SyntaxTriviaList.Create(SyntaxFactory.ElasticMarker)) .WithTrailingTrivia(declarator.Identifier.TrailingTrivia) .WithLeadingTrivia(declarator.Identifier.LeadingTrivia); var updatedDeclarator = declarator.WithIdentifier(newIdentifier).WithAdditionalAnnotations(tempAnnotation); root = root.ReplaceNode(declarator, updatedDeclarator); document = document.WithSyntaxRoot(root); var declaration = root.GetAnnotatedNodes<SyntaxNode>(tempAnnotation).First().Parent as VariableDeclarationSyntax; if (declaration.Variables.Count == 1) { var fieldSyntax = declaration.Parent as FieldDeclarationSyntax; var modifierKinds = new[] { SyntaxKind.PrivateKeyword, SyntaxKind.ProtectedKeyword, SyntaxKind.InternalKeyword, SyntaxKind.PublicKeyword }; if (makePrivate) { var modifiers = SpecializedCollections.SingletonEnumerable(SyntaxFactory.Token(SyntaxKind.PrivateKeyword)) .Concat(fieldSyntax.Modifiers.Where(m => !modifierKinds.Contains(m.Kind()))); root = root.ReplaceNode(fieldSyntax, fieldSyntax.WithModifiers( SyntaxFactory.TokenList(modifiers)) .WithAdditionalAnnotations(Formatter.Annotation) .WithLeadingTrivia(fieldSyntax.GetLeadingTrivia()) .WithTrailingTrivia(fieldSyntax.GetTrailingTrivia())); } } else if (declaration.Variables.Count > 1 && makePrivate) { document = document.WithSyntaxRoot(root); var codeGenService = document.GetLanguageService<ICodeGenerationService>(); var semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false); root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); declarator = root.GetAnnotatedNodes<VariableDeclaratorSyntax>(tempAnnotation).First(); declaration = declarator.Parent as VariableDeclarationSyntax; var field = semanticModel.GetDeclaredSymbol(declarator, cancellationToken) as IFieldSymbol; var fieldToAdd = declarationAnnotation.AddAnnotationToSymbol(CodeGenerationSymbolFactory.CreateFieldSymbol( field.GetAttributes(), Accessibility.Private, new DeclarationModifiers(isStatic: field.IsStatic, isReadOnly: field.IsReadOnly, isConst: field.IsConst), field.Type, field.Name, field.HasConstantValue, field.ConstantValue, declarator.Initializer)); var withField = await codeGenService.AddFieldAsync(document.Project.Solution, field.ContainingType, fieldToAdd, new CodeGenerationOptions(), cancellationToken).ConfigureAwait(false); root = await withField.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); declarator = root.GetAnnotatedNodes<VariableDeclaratorSyntax>(tempAnnotation).First(); declaration = declarator.Parent as VariableDeclarationSyntax; return root.RemoveNode(declarator, SyntaxRemoveOptions.KeepNoTrivia); } return root; } protected override async Task<ImmutableArray<IFieldSymbol>> GetFieldsAsync(Document document, TextSpan span, CancellationToken cancellationToken) { var semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false); var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); var fields = root.DescendantNodes(d => d.Span.IntersectsWith(span)) .OfType<FieldDeclarationSyntax>() .Where(n => n.Span.IntersectsWith(span)); var declarations = fields.Where(CanEncapsulate).Select(f => f.Declaration); IEnumerable<VariableDeclaratorSyntax> declarators; if (span.IsEmpty) { // no selection, get all variables declarators = declarations.SelectMany(d => d.Variables); } else { // has selection, get only the ones that are included in the selection declarators = declarations.SelectMany(d => d.Variables.Where(v => v.Span.IntersectsWith(span))); } return declarators.Select(d => semanticModel.GetDeclaredSymbol(d, cancellationToken) as IFieldSymbol) .WhereNotNull() .Where(f => f.Name.Length != 0) .ToImmutableArray(); } private bool CanEncapsulate(FieldDeclarationSyntax field) => field.Parent is TypeDeclarationSyntax; protected override (string fieldName, string propertyName) GenerateFieldAndPropertyNames(IFieldSymbol field) { // Special case: if the field is "new", we will preserve its original name and the new keyword. if (field.DeclaredAccessibility == Accessibility.Private || IsNew(field)) { // Create some capitalized version of the field name for the property return (field.Name, MakeUnique(GeneratePropertyName(field.Name), field.ContainingType)); } else { // Generate the new property name using the rules from 695042 var newPropertyName = GeneratePropertyName(field.Name); if (newPropertyName == field.Name) { // If we wind up with the field's old name, give the field the unique version of its current name. return (MakeUnique(GenerateFieldName(field.Name), field.ContainingType), newPropertyName); } // Otherwise, ensure the property's name is unique. newPropertyName = MakeUnique(newPropertyName, field.ContainingType); var newFieldName = GenerateFieldName(newPropertyName); // If converting the new property's name into a field name results in the old field name, we're done. if (newFieldName == field.Name) { return (newFieldName, newPropertyName); } // Otherwise, ensure the new field name is unique. return (MakeUnique(newFieldName, field.ContainingType), newPropertyName); } } private static bool IsNew(IFieldSymbol field) => field.DeclaringSyntaxReferences.Any(d => d.GetSyntax().GetAncestor<FieldDeclarationSyntax>().Modifiers.Any(SyntaxKind.NewKeyword)); private static string GenerateFieldName(string correspondingPropertyName) => char.ToLower(correspondingPropertyName[0]).ToString() + correspondingPropertyName.Substring(1); protected static string MakeUnique(string baseName, INamedTypeSymbol containingType) { var containingTypeMemberNames = containingType.GetAccessibleMembersInThisAndBaseTypes<ISymbol>(containingType).Select(m => m.Name); return NameGenerator.GenerateUniqueName(baseName, containingTypeMemberNames.ToSet(), StringComparer.Ordinal); } internal override IEnumerable<SyntaxNode> GetConstructorNodes(INamedTypeSymbol containingType) => containingType.Constructors.SelectMany(c => c.DeclaringSyntaxReferences.Select(d => d.GetSyntax())); } }
-1
dotnet/roslyn
55,427
Fixes #50462
Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
Blokyk
2021-08-05T01:17:37Z
2021-08-25T05:42:59Z
fefb8c2110625bc4908db4bbdaa367b12bfb1069
fb4ac545a1f1f365e7df570637699d9085ea4f87
Fixes #50462. Fixes #50462 Uses a different diagnostic message for IDE0078 (use pattern combinators instead of && and ||) depending on whether the associated code-fix could have side-effects or not. For example, for a condition of the form ```csharp if ($expr == a || $expr == b) { /* ... */ } ``` To be rewritten as ```csharp if ($expr is a or b) { /* ... */ } ``` The analyzer will check if $expr is a method call or not (as per Cyrus's recommendation), and if it is will warn the user that the code-fix might have side-effects. All that should be remaining now is to write tests for it
./src/Workspaces/Core/Portable/Utilities/SpellChecker.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Linq; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Internal.Log; using Microsoft.CodeAnalysis.Utilities; namespace Roslyn.Utilities { internal class SpellChecker : IObjectWritable, IChecksummedObject { private const string SerializationFormat = "3"; public Checksum Checksum { get; } private readonly BKTree _bkTree; public SpellChecker(Checksum checksum, BKTree bKTree) { Checksum = checksum; _bkTree = bKTree; } public SpellChecker(Checksum checksum, IEnumerable<ReadOnlyMemory<char>> corpus) : this(checksum, BKTree.Create(corpus)) { } public IList<string> FindSimilarWords(string value) => FindSimilarWords(value, substringsAreSimilar: false); public IList<string> FindSimilarWords(string value, bool substringsAreSimilar) { var result = _bkTree.Find(value, threshold: null); var checker = WordSimilarityChecker.Allocate(value, substringsAreSimilar); var array = result.Where(checker.AreSimilar).ToArray(); checker.Free(); return array; } bool IObjectWritable.ShouldReuseInSerialization => true; void IObjectWritable.WriteTo(ObjectWriter writer) { writer.WriteString(SerializationFormat); Checksum.WriteTo(writer); _bkTree.WriteTo(writer); } internal static SpellChecker TryReadFrom(ObjectReader reader) { try { var formatVersion = reader.ReadString(); if (string.Equals(formatVersion, SerializationFormat, StringComparison.Ordinal)) { var checksum = Checksum.ReadFrom(reader); var bkTree = BKTree.ReadFrom(reader); if (bkTree != null) { return new SpellChecker(checksum, bkTree); } } } catch { Logger.Log(FunctionId.SpellChecker_ExceptionInCacheRead); } 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.Linq; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Internal.Log; using Microsoft.CodeAnalysis.Utilities; namespace Roslyn.Utilities { internal class SpellChecker : IObjectWritable, IChecksummedObject { private const string SerializationFormat = "3"; public Checksum Checksum { get; } private readonly BKTree _bkTree; public SpellChecker(Checksum checksum, BKTree bKTree) { Checksum = checksum; _bkTree = bKTree; } public SpellChecker(Checksum checksum, IEnumerable<ReadOnlyMemory<char>> corpus) : this(checksum, BKTree.Create(corpus)) { } public IList<string> FindSimilarWords(string value) => FindSimilarWords(value, substringsAreSimilar: false); public IList<string> FindSimilarWords(string value, bool substringsAreSimilar) { var result = _bkTree.Find(value, threshold: null); var checker = WordSimilarityChecker.Allocate(value, substringsAreSimilar); var array = result.Where(checker.AreSimilar).ToArray(); checker.Free(); return array; } bool IObjectWritable.ShouldReuseInSerialization => true; void IObjectWritable.WriteTo(ObjectWriter writer) { writer.WriteString(SerializationFormat); Checksum.WriteTo(writer); _bkTree.WriteTo(writer); } internal static SpellChecker TryReadFrom(ObjectReader reader) { try { var formatVersion = reader.ReadString(); if (string.Equals(formatVersion, SerializationFormat, StringComparison.Ordinal)) { var checksum = Checksum.ReadFrom(reader); var bkTree = BKTree.ReadFrom(reader); if (bkTree != null) { return new SpellChecker(checksum, bkTree); } } } catch { Logger.Log(FunctionId.SpellChecker_ExceptionInCacheRead); } return null; } } }
-1